Add a general purpose hashtable pattern matcher
[jimtcl.git] / linenoise.c
blob418bede997b1070a1058cd14c4fc69eedb1bd72c
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/msteveb/linenoise
7 * (forked from http://github.com/antirez/linenoise)
9 * Does a number of crazy assumptions that happen to be true in 99.9999% of
10 * the 2010 UNIX computers around.
12 * ------------------------------------------------------------------------
14 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
15 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16 * Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
18 * All rights reserved.
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions are
22 * met:
24 * * Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
27 * * Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 * ------------------------------------------------------------------------
45 * References:
46 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
49 * Bloat:
50 * - Completion?
52 * Unix/termios
53 * ------------
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
98 * win32/console
99 * -------------
100 * If __MINGW32__ is defined, the win32 console API is used.
101 * This could probably be made to work for the msvc compiler too.
102 * This support based in part on work by Jon Griffiths.
105 #ifdef __MINGW32__
106 #include <windows.h>
107 #include <fcntl.h>
108 #define USE_WINCONSOLE
109 #else
110 #include <termios.h>
111 #include <sys/ioctl.h>
112 #include <sys/poll.h>
113 #define USE_TERMIOS
114 #endif
116 #include <unistd.h>
117 #include <stdlib.h>
118 #include <stdarg.h>
119 #include <stdio.h>
120 #include <errno.h>
121 #include <string.h>
122 #include <stdlib.h>
123 #include <sys/types.h>
124 #include <unistd.h>
126 #include "linenoise.h"
128 #include "jim-config.h"
129 #ifdef JIM_UTF8
130 #define USE_UTF8
131 #endif
132 #include "utf8.h"
134 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
135 #define LINENOISE_MAX_LINE 4096
137 #define ctrl(C) ((C) - '@')
139 /* Use -ve numbers here to co-exist with normal unicode chars */
140 enum {
141 SPECIAL_NONE,
142 SPECIAL_UP = -20,
143 SPECIAL_DOWN = -21,
144 SPECIAL_LEFT = -22,
145 SPECIAL_RIGHT = -23,
146 SPECIAL_DELETE = -24,
147 SPECIAL_HOME = -25,
148 SPECIAL_END = -26,
151 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
152 static int history_len = 0;
153 static char **history = NULL;
155 /* Structure to contain the status of the current (being edited) line */
156 struct current {
157 char *buf; /* Current buffer. Always null terminated */
158 int bufmax; /* Size of the buffer, including space for the null termination */
159 int len; /* Number of bytes in 'buf' */
160 int chars; /* Number of chars in 'buf' (utf-8 chars) */
161 int pos; /* Cursor position, measured in chars */
162 int cols; /* Size of the window, in chars */
163 const char *prompt;
164 #if defined(USE_TERMIOS)
165 int fd; /* Terminal fd */
166 #elif defined(USE_WINCONSOLE)
167 HANDLE outh; /* Console output handle */
168 HANDLE inh; /* Console input handle */
169 int rows; /* Screen rows */
170 int x; /* Current column during output */
171 int y; /* Current row */
172 #endif
175 static int fd_read(struct current *current);
176 static int getWindowSize(struct current *current);
178 void linenoiseHistoryFree(void) {
179 if (history) {
180 int j;
182 for (j = 0; j < history_len; j++)
183 free(history[j]);
184 free(history);
185 history = NULL;
189 #if defined(USE_TERMIOS)
190 static void linenoiseAtExit(void);
191 static struct termios orig_termios; /* in order to restore at exit */
192 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
193 static int atexit_registered = 0; /* register atexit just 1 time */
195 static const char *unsupported_term[] = {"dumb","cons25",NULL};
197 static int isUnsupportedTerm(void) {
198 char *term = getenv("TERM");
200 if (term) {
201 int j;
202 for (j = 0; unsupported_term[j]; j++) {
203 if (strcasecmp(term, unsupported_term[j]) == 0) {
204 return 1;
208 return 0;
211 static int enableRawMode(struct current *current) {
212 struct termios raw;
214 current->fd = STDIN_FILENO;
216 if (!isatty(current->fd) || isUnsupportedTerm() ||
217 tcgetattr(current->fd, &orig_termios) == -1) {
218 fatal:
219 errno = ENOTTY;
220 return -1;
223 if (!atexit_registered) {
224 atexit(linenoiseAtExit);
225 atexit_registered = 1;
228 raw = orig_termios; /* modify the original mode */
229 /* input modes: no break, no CR to NL, no parity check, no strip char,
230 * no start/stop output control. */
231 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
232 /* output modes - disable post processing */
233 raw.c_oflag &= ~(OPOST);
234 /* control modes - set 8 bit chars */
235 raw.c_cflag |= (CS8);
236 /* local modes - choing off, canonical off, no extended functions,
237 * no signal chars (^Z,^C) */
238 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
239 /* control chars - set return condition: min number of bytes and timer.
240 * We want read to return every single byte, without timeout. */
241 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
243 /* put terminal in raw mode after flushing */
244 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
245 goto fatal;
247 rawmode = 1;
249 current->cols = 0;
250 return 0;
253 static void disableRawMode(struct current *current) {
254 /* Don't even check the return value as it's too late. */
255 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
256 rawmode = 0;
259 /* At exit we'll try to fix the terminal to the initial conditions. */
260 static void linenoiseAtExit(void) {
261 if (rawmode) {
262 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
264 linenoiseHistoryFree();
267 /* gcc/glibc insists that we care about the return code of write! */
268 #define IGNORE_RC(EXPR) if (EXPR) {}
270 /* This is fdprintf() on some systems, but use a different
271 * name to avoid conflicts
273 static void fd_printf(int fd, const char *format, ...)
275 va_list args;
276 char buf[64];
277 int n;
279 va_start(args, format);
280 n = vsnprintf(buf, sizeof(buf), format, args);
281 va_end(args);
282 IGNORE_RC(write(fd, buf, n));
285 static void clearScreen(struct current *current)
287 fd_printf(current->fd, "\x1b[H\x1b[2J");
290 static void cursorToLeft(struct current *current)
292 fd_printf(current->fd, "\x1b[1G");
295 static int outputChars(struct current *current, const char *buf, int len)
297 return write(current->fd, buf, len);
300 static void outputControlChar(struct current *current, char ch)
302 fd_printf(current->fd, "\033[7m^%c\033[0m", ch);
305 static void eraseEol(struct current *current)
307 fd_printf(current->fd, "\x1b[0K");
310 static void setCursorPos(struct current *current, int x)
312 fd_printf(current->fd, "\x1b[1G\x1b[%dC", x);
316 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
318 * A timeout of -1 means to wait forever.
320 * Returns -1 if no char is received within the time or an error occurs.
322 static int fd_read_char(int fd, int timeout)
324 struct pollfd p;
325 unsigned char c;
327 p.fd = fd;
328 p.events = POLLIN;
330 if (poll(&p, 1, timeout) == 0) {
331 /* timeout */
332 return -1;
334 if (read(fd, &c, 1) != 1) {
335 return -1;
337 return c;
341 * Reads a complete utf-8 character
342 * and returns the unicode value, or -1 on error.
344 static int fd_read(struct current *current)
346 #ifdef USE_UTF8
347 char buf[4];
348 int n;
349 int i;
350 int c;
352 if (read(current->fd, &buf[0], 1) != 1) {
353 return -1;
355 n = utf8_charlen(buf[0]);
356 if (n < 1 || n > 3) {
357 return -1;
359 for (i = 1; i < n; i++) {
360 if (read(current->fd, &buf[i], 1) != 1) {
361 return -1;
364 buf[n] = 0;
365 /* decode and return the character */
366 utf8_tounicode(buf, &c);
367 return c;
368 #else
369 return fd_read_char(current->fd, -1);
370 #endif
373 static int getWindowSize(struct current *current)
375 struct winsize ws;
377 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
378 current->cols = ws.ws_col;
379 return 0;
382 /* Failed to query the window size. Perhaps we are on a serial terminal.
383 * Try to query the width by sending the cursor as far to the right
384 * and reading back the cursor position.
385 * Note that this is only done once per call to linenoise rather than
386 * every time the line is refreshed for efficiency reasons.
388 if (current->cols == 0) {
389 current->cols = 80;
391 /* Move cursor far right and report cursor position */
392 fd_printf(current->fd, "\x1b[999G" "\x1b[6n");
394 /* Parse the response: ESC [ rows ; cols R */
395 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
396 int n = 0;
397 while (1) {
398 int ch = fd_read_char(current->fd, 100);
399 if (ch == ';') {
400 /* Ignore rows */
401 n = 0;
403 else if (ch == 'R') {
404 /* Got cols */
405 if (n != 0 && n < 1000) {
406 current->cols = n;
408 break;
410 else if (ch >= 0 && ch <= '9') {
411 n = n * 10 + ch - '0';
413 else {
414 break;
419 return 0;
423 * If escape (27) was received, reads subsequent
424 * chars to determine if this is a known special key.
426 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
428 * If no additional char is received within a short time,
429 * 27 is returned.
431 static int check_special(int fd)
433 int c = fd_read_char(fd, 50);
434 int c2;
436 if (c < 0) {
437 return 27;
440 c2 = fd_read_char(fd, 50);
441 if (c2 < 0) {
442 return c2;
444 if (c == '[' || c == 'O') {
445 /* Potential arrow key */
446 switch (c2) {
447 case 'A':
448 return SPECIAL_UP;
449 case 'B':
450 return SPECIAL_DOWN;
451 case 'C':
452 return SPECIAL_RIGHT;
453 case 'D':
454 return SPECIAL_LEFT;
455 case 'F':
456 return SPECIAL_END;
457 case 'H':
458 return SPECIAL_HOME;
461 if (c == '[' && c2 >= '1' && c2 <= '8') {
462 /* extended escape */
463 c = fd_read_char(fd, 50);
464 if (c == '~') {
465 switch (c2) {
466 case '3':
467 return SPECIAL_DELETE;
468 case '7':
469 return SPECIAL_HOME;
470 case '8':
471 return SPECIAL_END;
474 while (c != -1 && c != '~') {
475 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
476 c = fd_read_char(fd, 50);
480 return SPECIAL_NONE;
482 #elif defined(USE_WINCONSOLE)
484 static DWORD orig_consolemode = 0;
486 static int enableRawMode(struct current *current) {
487 DWORD n;
488 INPUT_RECORD irec;
490 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
491 current->inh = GetStdHandle(STD_INPUT_HANDLE);
493 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
494 return -1;
496 if (getWindowSize(current) != 0) {
497 return -1;
499 if (GetConsoleMode(current->inh, &orig_consolemode)) {
500 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
502 return 0;
505 static void disableRawMode(struct current *current)
507 SetConsoleMode(current->inh, orig_consolemode);
510 static void clearScreen(struct current *current)
512 COORD topleft = { 0, 0 };
513 DWORD n;
515 FillConsoleOutputCharacter(current->outh, ' ',
516 current->cols * current->rows, topleft, &n);
517 FillConsoleOutputAttribute(current->outh,
518 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
519 current->cols * current->rows, topleft, &n);
520 SetConsoleCursorPosition(current->outh, topleft);
523 static void cursorToLeft(struct current *current)
525 COORD pos = { 0, current->y };
526 DWORD n;
528 FillConsoleOutputAttribute(current->outh,
529 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
530 current->x = 0;
533 static int outputChars(struct current *current, const char *buf, int len)
535 COORD pos = { current->x, current->y };
536 WriteConsoleOutputCharacter(current->outh, buf, len, pos, 0);
537 current->x += len;
538 return 0;
541 static void outputControlChar(struct current *current, char ch)
543 COORD pos = { current->x, current->y };
544 DWORD n;
546 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
547 outputChars(current, "^", 1);
548 outputChars(current, &ch, 1);
551 static void eraseEol(struct current *current)
553 COORD pos = { current->x, current->y };
554 DWORD n;
556 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
559 static void setCursorPos(struct current *current, int x)
561 COORD pos = { x, current->y };
563 SetConsoleCursorPosition(current->outh, pos);
564 current->x = x;
567 static int fd_read(struct current *current)
569 while (1) {
570 INPUT_RECORD irec;
571 DWORD n;
572 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
573 break;
575 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
576 break;
578 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
579 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
580 if (k->dwControlKeyState & ENHANCED_KEY) {
581 switch (k->wVirtualKeyCode) {
582 case VK_LEFT:
583 return SPECIAL_LEFT;
584 case VK_RIGHT:
585 return SPECIAL_RIGHT;
586 case VK_UP:
587 return SPECIAL_UP;
588 case VK_DOWN:
589 return SPECIAL_DOWN;
590 case VK_DELETE:
591 return SPECIAL_DELETE;
592 case VK_HOME:
593 return SPECIAL_HOME;
594 case VK_END:
595 return SPECIAL_END;
598 /* Note that control characters are already translated in AsciiChar */
599 else {
600 #ifdef USE_UTF8
601 return k->uChar.UnicodeChar;
602 #else
603 return k->uChar.AsciiChar;
604 #endif
608 return -1;
611 static int getWindowSize(struct current *current)
613 CONSOLE_SCREEN_BUFFER_INFO info;
614 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
615 return -1;
617 current->cols = info.dwSize.X;
618 current->rows = info.dwSize.Y;
619 if (current->cols <= 0 || current->rows <= 0) {
620 current->cols = 80;
621 return -1;
623 current->y = info.dwCursorPosition.Y;
624 current->x = info.dwCursorPosition.X;
625 return 0;
627 #endif
629 static int utf8_getchars(char *buf, int c)
631 #ifdef USE_UTF8
632 return utf8_fromunicode(buf, c);
633 #else
634 *buf = c;
635 return 1;
636 #endif
640 * Returns the unicode character at the given offset,
641 * or -1 if none.
643 static int get_char(struct current *current, int pos)
645 if (pos >= 0 && pos < current->chars) {
646 int c;
647 int i = utf8_index(current->buf, pos);
648 (void)utf8_tounicode(current->buf + i, &c);
649 return c;
651 return -1;
654 static void refreshLine(const char *prompt, struct current *current)
656 int plen;
657 int pchars;
658 int backup = 0;
659 int i;
660 const char *buf = current->buf;
661 int chars = current->chars;
662 int pos = current->pos;
663 int b;
664 int ch;
665 int n;
667 /* Should intercept SIGWINCH. For now, just get the size every time */
668 getWindowSize(current);
670 plen = strlen(prompt);
671 pchars = utf8_strlen(prompt, plen);
673 /* Account for a line which is too long to fit in the window.
674 * Note that control chars require an extra column
677 /* How many cols are required to the left of 'pos'?
678 * The prompt, plus one extra for each control char
680 n = pchars + utf8_strlen(buf, current->len);
681 b = 0;
682 for (i = 0; i < pos; i++) {
683 b += utf8_tounicode(buf + b, &ch);
684 if (ch < ' ') {
685 n++;
689 /* If too many are need, strip chars off the front of 'buf'
690 * until it fits. Note that if the current char is a control character,
691 * we need one extra col.
693 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
694 n++;
697 while (n >= current->cols) {
698 b = utf8_tounicode(buf, &ch);
699 if (ch < ' ') {
700 n--;
702 n--;
703 buf += b;
704 pos--;
705 chars--;
708 /* Cursor to left edge, then the prompt */
709 cursorToLeft(current);
710 outputChars(current, prompt, plen);
712 /* Now the current buffer content */
714 /* Need special handling for control characters.
715 * If we hit 'cols', stop.
717 b = 0; /* unwritted bytes */
718 n = 0; /* How many control chars were written */
719 for (i = 0; i < chars; i++) {
720 int ch;
721 int w = utf8_tounicode(buf + b, &ch);
722 if (ch < ' ') {
723 n++;
725 if (pchars + i + n >= current->cols) {
726 break;
728 if (ch < ' ') {
729 /* A control character, so write the buffer so far */
730 outputChars(current, buf, b);
731 buf += b + w;
732 b = 0;
733 outputControlChar(current, ch + '@');
734 if (i < pos) {
735 backup++;
738 else {
739 b += w;
742 outputChars(current, buf, b);
744 /* Erase to right, move cursor to original position */
745 eraseEol(current);
746 setCursorPos(current, pos + pchars + backup);
749 static void set_current(struct current *current, const char *str)
751 strncpy(current->buf, str, current->bufmax);
752 current->buf[current->bufmax - 1] = 0;
753 current->len = strlen(current->buf);
754 current->pos = current->chars = utf8_strlen(current->buf, current->len);
757 static int has_room(struct current *current, int bytes)
759 return current->len + bytes < current->bufmax - 1;
763 * Removes the char at 'pos'.
765 * Returns 1 if the line needs to be refreshed, 2 if not
766 * and 0 if nothing was removed
768 static int remove_char(struct current *current, int pos)
770 if (pos >= 0 && pos < current->chars) {
771 int p1, p2;
772 int ret = 1;
773 p1 = utf8_index(current->buf, pos);
774 p2 = p1 + utf8_index(current->buf + p1, 1);
776 #ifdef USE_TERMIOS
777 /* optimise remove char in the case of removing the last char */
778 if (current->pos == pos + 1 && current->pos == current->chars) {
779 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
780 ret = 2;
781 fd_printf(current->fd, "\b \b");
784 #endif
786 /* Move the null char too */
787 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
788 current->len -= (p2 - p1);
789 current->chars--;
791 if (current->pos > pos) {
792 current->pos--;
794 return ret;
796 return 0;
800 * Insert 'ch' at position 'pos'
802 * Returns 1 if the line needs to be refreshed, 2 if not
803 * and 0 if nothing was inserted (no room)
805 static int insert_char(struct current *current, int pos, int ch)
807 char buf[3];
808 int n = utf8_getchars(buf, ch);
810 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
811 int p1, p2;
812 int ret = 1;
813 p1 = utf8_index(current->buf, pos);
814 p2 = p1 + n;
816 #ifdef USE_TERMIOS
817 /* optimise the case where adding a single char to the end and no scrolling is needed */
818 if (current->pos == pos && current->chars == pos) {
819 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
820 IGNORE_RC(write(current->fd, buf, n));
821 ret = 2;
824 #endif
826 memmove(current->buf + p2, current->buf + p1, current->len - p1);
827 memcpy(current->buf + p1, buf, n);
828 current->len += n;
830 current->chars++;
831 if (current->pos >= pos) {
832 current->pos++;
834 return ret;
836 return 0;
840 * Returns 0 if no chars were removed or non-zero otherwise.
842 static int remove_chars(struct current *current, int pos, int n)
844 int removed = 0;
845 while (n-- && remove_char(current, pos)) {
846 removed++;
848 return removed;
851 #ifndef NO_COMPLETION
852 static linenoiseCompletionCallback *completionCallback = NULL;
854 static void beep() {
855 #ifdef USE_TERMIOS
856 fprintf(stderr, "\x7");
857 fflush(stderr);
858 #endif
861 static void freeCompletions(linenoiseCompletions *lc) {
862 size_t i;
863 for (i = 0; i < lc->len; i++)
864 free(lc->cvec[i]);
865 free(lc->cvec);
868 static int completeLine(struct current *current) {
869 linenoiseCompletions lc = { 0, NULL };
870 int c = 0;
872 completionCallback(current->buf,&lc);
873 if (lc.len == 0) {
874 beep();
875 } else {
876 size_t stop = 0, i = 0;
878 while(!stop) {
879 /* Show completion or original buffer */
880 if (i < lc.len) {
881 struct current tmp = *current;
882 tmp.buf = lc.cvec[i];
883 tmp.pos = tmp.len = strlen(tmp.buf);
884 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
885 refreshLine(current->prompt, &tmp);
886 } else {
887 refreshLine(current->prompt, current);
890 c = fd_read(current);
891 if (c == -1) {
892 break;
895 switch(c) {
896 case '\t': /* tab */
897 i = (i+1) % (lc.len+1);
898 if (i == lc.len) beep();
899 break;
900 case 27: /* escape */
901 /* Re-show original buffer */
902 if (i < lc.len) {
903 refreshLine(current->prompt, current);
905 stop = 1;
906 break;
907 default:
908 /* Update buffer and return */
909 if (i < lc.len) {
910 set_current(current,lc.cvec[i]);
912 stop = 1;
913 break;
918 freeCompletions(&lc);
919 return c; /* Return last read character */
922 /* Register a callback function to be called for tab-completion. */
923 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
924 completionCallback = fn;
927 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
928 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
929 lc->cvec[lc->len++] = strdup(str);
932 #endif
934 static int linenoisePrompt(struct current *current) {
935 int history_index = 0;
937 /* The latest history entry is always our current buffer, that
938 * initially is just an empty string. */
939 linenoiseHistoryAdd("");
941 set_current(current, "");
942 refreshLine(current->prompt, current);
944 while(1) {
945 int dir = -1;
946 int c = fd_read(current);
948 #ifndef NO_COMPLETION
949 /* Only autocomplete when the callback is set. It returns < 0 when
950 * there was an error reading from fd. Otherwise it will return the
951 * character that should be handled next. */
952 if (c == 9 && completionCallback != NULL) {
953 c = completeLine(current);
954 /* Return on errors */
955 if (c < 0) return current->len;
956 /* Read next character when 0 */
957 if (c == 0) continue;
959 #endif
961 process_char:
962 if (c == -1) return current->len;
963 #ifdef USE_TERMIOS
964 if (c == 27) { /* escape sequence */
965 c = check_special(current->fd);
967 #endif
968 switch(c) {
969 case '\r': /* enter */
970 history_len--;
971 free(history[history_len]);
972 return current->len;
973 case ctrl('C'): /* ctrl-c */
974 errno = EAGAIN;
975 return -1;
976 case 127: /* backspace */
977 case ctrl('H'):
978 if (remove_char(current, current->pos - 1) == 1) {
979 refreshLine(current->prompt, current);
981 break;
982 case ctrl('D'): /* ctrl-d */
983 if (current->len == 0) {
984 /* Empty line, so EOF */
985 history_len--;
986 free(history[history_len]);
987 return -1;
989 /* Otherwise fall through to delete char to right of cursor */
990 case SPECIAL_DELETE:
991 if (remove_char(current, current->pos) == 1) {
992 refreshLine(current->prompt, current);
994 break;
995 case ctrl('W'): /* ctrl-w */
996 /* eat any spaces on the left */
998 int pos = current->pos;
999 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1000 pos--;
1003 /* now eat any non-spaces on the left */
1004 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1005 pos--;
1008 if (remove_chars(current, pos, current->pos - pos)) {
1009 refreshLine(current->prompt, current);
1012 break;
1013 case ctrl('R'): /* ctrl-r */
1015 /* Display the reverse-i-search prompt and process chars */
1016 char rbuf[50];
1017 char rprompt[80];
1018 int rchars = 0;
1019 int rlen = 0;
1020 int searchpos = history_len - 1;
1022 rbuf[0] = 0;
1023 while (1) {
1024 int n = 0;
1025 const char *p = NULL;
1026 int skipsame = 0;
1027 int searchdir = -1;
1029 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1030 refreshLine(rprompt, current);
1031 c = fd_read(current);
1032 if (c == ctrl('H') || c == 127) {
1033 if (rchars) {
1034 int p = utf8_index(rbuf, --rchars);
1035 rbuf[p] = 0;
1036 rlen = strlen(rbuf);
1038 continue;
1040 #ifdef USE_TERMIOS
1041 if (c == 27) {
1042 c = check_special(current->fd);
1044 #endif
1045 if (c == ctrl('P') || c == SPECIAL_UP) {
1046 /* Search for the previous (earlier) match */
1047 if (searchpos > 0) {
1048 searchpos--;
1050 skipsame = 1;
1052 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1053 /* Search for the next (later) match */
1054 if (searchpos < history_len) {
1055 searchpos++;
1057 searchdir = 1;
1058 skipsame = 1;
1060 else if (c >= ' ') {
1061 if (rlen >= (int)sizeof(rbuf) + 3) {
1062 continue;
1065 n = utf8_getchars(rbuf + rlen, c);
1066 rlen += n;
1067 rchars++;
1068 rbuf[rlen] = 0;
1070 /* Adding a new char resets the search location */
1071 searchpos = history_len - 1;
1073 else {
1074 /* Exit from incremental search mode */
1075 break;
1078 /* Now search through the history for a match */
1079 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1080 p = strstr(history[searchpos], rbuf);
1081 if (p) {
1082 /* Found a match */
1083 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1084 /* But it is identical, so skip it */
1085 continue;
1087 /* Copy the matching line and set the cursor position */
1088 set_current(current,history[searchpos]);
1089 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1090 break;
1093 if (!p && n) {
1094 /* No match, so don't add it */
1095 rchars--;
1096 rlen -= n;
1097 rbuf[rlen] = 0;
1100 if (c == ctrl('G') || c == ctrl('C')) {
1101 /* ctrl-g terminates the search with no effect */
1102 set_current(current, "");
1103 c = 0;
1105 else if (c == ctrl('J')) {
1106 /* ctrl-j terminates the search leaving the buffer in place */
1107 c = 0;
1109 /* Go process the char normally */
1110 refreshLine(current->prompt, current);
1111 goto process_char;
1113 break;
1114 case ctrl('T'): /* ctrl-t */
1115 if (current->pos > 0 && current->pos < current->chars) {
1116 c = get_char(current, current->pos);
1117 remove_char(current, current->pos);
1118 insert_char(current, current->pos - 1, c);
1119 refreshLine(current->prompt, current);
1121 break;
1122 case ctrl('V'): /* ctrl-v */
1123 if (has_room(current, 3)) {
1124 /* Insert the ^V first */
1125 if (insert_char(current, current->pos, c)) {
1126 refreshLine(current->prompt, current);
1127 /* Now wait for the next char. Can insert anything except \0 */
1128 c = fd_read(current);
1130 /* Remove the ^V first */
1131 remove_char(current, current->pos - 1);
1132 if (c != -1) {
1133 /* Insert the actual char */
1134 insert_char(current, current->pos, c);
1136 refreshLine(current->prompt, current);
1139 break;
1140 case ctrl('B'):
1141 case SPECIAL_LEFT:
1142 if (current->pos > 0) {
1143 current->pos--;
1144 refreshLine(current->prompt, current);
1146 break;
1147 case ctrl('F'):
1148 case SPECIAL_RIGHT:
1149 if (current->pos < current->chars) {
1150 current->pos++;
1151 refreshLine(current->prompt, current);
1153 break;
1154 case ctrl('P'):
1155 case SPECIAL_UP:
1156 dir = 1;
1157 case ctrl('N'):
1158 case SPECIAL_DOWN:
1159 if (history_len > 1) {
1160 /* Update the current history entry before to
1161 * overwrite it with tne next one. */
1162 free(history[history_len-1-history_index]);
1163 history[history_len-1-history_index] = strdup(current->buf);
1164 /* Show the new entry */
1165 history_index += dir;
1166 if (history_index < 0) {
1167 history_index = 0;
1168 break;
1169 } else if (history_index >= history_len) {
1170 history_index = history_len-1;
1171 break;
1173 set_current(current, history[history_len-1-history_index]);
1174 refreshLine(current->prompt, current);
1176 break;
1177 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1178 case SPECIAL_HOME:
1179 current->pos = 0;
1180 refreshLine(current->prompt, current);
1181 break;
1182 case ctrl('E'): /* ctrl+e, go to the end of the line */
1183 case SPECIAL_END:
1184 current->pos = current->chars;
1185 refreshLine(current->prompt, current);
1186 break;
1187 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1188 if (remove_chars(current, 0, current->pos)) {
1189 refreshLine(current->prompt, current);
1191 break;
1192 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1193 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1194 refreshLine(current->prompt, current);
1196 break;
1197 case ctrl('L'): /* Ctrl+L, clear screen */
1198 clearScreen(current);
1199 /* Force recalc of window size for serial terminals */
1200 current->cols = 0;
1201 refreshLine(current->prompt, current);
1202 break;
1203 default:
1204 /* Only tab is allowed without ^V */
1205 if (c == '\t' || c >= ' ') {
1206 if (insert_char(current, current->pos, c) == 1) {
1207 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));
1264 /* do not insert duplicate lines into history */
1265 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1266 return 0;
1269 linecopy = strdup(line);
1270 if (!linecopy) return 0;
1271 if (history_len == history_max_len) {
1272 free(history[0]);
1273 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1274 history_len--;
1276 history[history_len] = linecopy;
1277 history_len++;
1278 return 1;
1281 int linenoiseHistorySetMaxLen(int len) {
1282 char **newHistory;
1284 if (len < 1) return 0;
1285 if (history) {
1286 int tocopy = history_len;
1288 newHistory = (char **)malloc(sizeof(char*)*len);
1289 if (newHistory == NULL) return 0;
1290 if (len < tocopy) tocopy = len;
1291 memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1292 free(history);
1293 history = newHistory;
1295 history_max_len = len;
1296 if (history_len > history_max_len)
1297 history_len = history_max_len;
1298 return 1;
1301 /* Save the history in the specified file. On success 0 is returned
1302 * otherwise -1 is returned. */
1303 int linenoiseHistorySave(const char *filename) {
1304 FILE *fp = fopen(filename,"w");
1305 int j;
1307 if (fp == NULL) return -1;
1308 for (j = 0; j < history_len; j++) {
1309 const char *str = history[j];
1310 /* Need to encode backslash, nl and cr */
1311 while (*str) {
1312 if (*str == '\\') {
1313 fputs("\\\\", fp);
1315 else if (*str == '\n') {
1316 fputs("\\n", fp);
1318 else if (*str == '\r') {
1319 fputs("\\r", fp);
1321 else {
1322 fputc(*str, fp);
1324 str++;
1326 fputc('\n', fp);
1329 fclose(fp);
1330 return 0;
1333 /* Load the history from the specified file. If the file does not exist
1334 * zero is returned and no operation is performed.
1336 * If the file exists and the operation succeeded 0 is returned, otherwise
1337 * on error -1 is returned. */
1338 int linenoiseHistoryLoad(const char *filename) {
1339 FILE *fp = fopen(filename,"r");
1340 char buf[LINENOISE_MAX_LINE];
1342 if (fp == NULL) return -1;
1344 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1345 char *src, *dest;
1347 /* Decode backslash escaped values */
1348 for (src = dest = buf; *src; src++) {
1349 char ch = *src;
1351 if (ch == '\\') {
1352 src++;
1353 if (*src == 'n') {
1354 ch = '\n';
1356 else if (*src == 'r') {
1357 ch = '\r';
1358 } else {
1359 ch = *src;
1362 *dest++ = ch;
1364 /* Remove trailing newline */
1365 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1366 dest--;
1368 *dest = 0;
1370 linenoiseHistoryAdd(buf);
1372 fclose(fp);
1373 return 0;
1376 /* Provide access to the history buffer.
1378 * If 'len' is not NULL, the length is stored in *len.
1380 char **linenoiseHistory(int *len) {
1381 if (len) {
1382 *len = history_len;
1384 return history;