zlib: Don't use PASTE for INTMAX error messages
[jimtcl.git] / linenoise.c
blobe805356d8bc5de8779019a7b8caf9da3348570d4
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 * EL (Erase Line)
60 * Sequence: ESC [ n K
61 * Effect: if n is 0 or missing, clear from cursor to end of line
62 * Effect: if n is 1, clear from beginning of line to cursor
63 * Effect: if n is 2, clear entire line
65 * CUF (CUrsor Forward)
66 * Sequence: ESC [ n C
67 * Effect: moves cursor forward of n chars
69 * CR (Carriage Return)
70 * Sequence: \r
71 * Effect: moves cursor to column 1
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 _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
106 #include <windows.h>
107 #include <fcntl.h>
108 #define USE_WINCONSOLE
109 #ifdef __MINGW32__
110 #define HAVE_UNISTD_H
111 #else
112 /* Microsoft headers don't like old POSIX names */
113 #define strdup _strdup
114 #define snprintf _snprintf
115 #endif
116 #else
117 #include <termios.h>
118 #include <sys/ioctl.h>
119 #include <sys/poll.h>
120 #define USE_TERMIOS
121 #define HAVE_UNISTD_H
122 #endif
124 #ifdef HAVE_UNISTD_H
125 #include <unistd.h>
126 #endif
127 #include <stdlib.h>
128 #include <stdarg.h>
129 #include <stdio.h>
130 #include <errno.h>
131 #include <string.h>
132 #include <stdlib.h>
133 #include <sys/types.h>
135 #include "linenoise.h"
137 #include "jim-config.h"
138 #ifdef JIM_UTF8
139 #define USE_UTF8
140 #endif
141 #include "utf8.h"
143 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
144 #define LINENOISE_MAX_LINE 4096
146 #define ctrl(C) ((C) - '@')
148 /* Use -ve numbers here to co-exist with normal unicode chars */
149 enum {
150 SPECIAL_NONE,
151 SPECIAL_UP = -20,
152 SPECIAL_DOWN = -21,
153 SPECIAL_LEFT = -22,
154 SPECIAL_RIGHT = -23,
155 SPECIAL_DELETE = -24,
156 SPECIAL_HOME = -25,
157 SPECIAL_END = -26,
158 SPECIAL_INSERT = -27,
159 SPECIAL_PAGE_UP = -28,
160 SPECIAL_PAGE_DOWN = -29
163 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
164 static int history_len = 0;
165 static char **history = NULL;
167 /* Structure to contain the status of the current (being edited) line */
168 struct current {
169 char *buf; /* Current buffer. Always null terminated */
170 int bufmax; /* Size of the buffer, including space for the null termination */
171 int len; /* Number of bytes in 'buf' */
172 int chars; /* Number of chars in 'buf' (utf-8 chars) */
173 int pos; /* Cursor position, measured in chars */
174 int cols; /* Size of the window, in chars */
175 const char *prompt;
176 char *capture; /* Allocated capture buffer, or NULL for none. Always null terminated */
177 #if defined(USE_TERMIOS)
178 int fd; /* Terminal fd */
179 #elif defined(USE_WINCONSOLE)
180 HANDLE outh; /* Console output handle */
181 HANDLE inh; /* Console input handle */
182 int rows; /* Screen rows */
183 int x; /* Current column during output */
184 int y; /* Current row */
185 #endif
188 static int fd_read(struct current *current);
189 static int getWindowSize(struct current *current);
191 void linenoiseHistoryFree(void) {
192 if (history) {
193 int j;
195 for (j = 0; j < history_len; j++)
196 free(history[j]);
197 free(history);
198 history = NULL;
199 history_len = 0;
203 #if defined(USE_TERMIOS)
204 static void linenoiseAtExit(void);
205 static struct termios orig_termios; /* in order to restore at exit */
206 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
207 static int atexit_registered = 0; /* register atexit just 1 time */
209 static const char *unsupported_term[] = {"dumb","cons25",NULL};
211 static int isUnsupportedTerm(void) {
212 char *term = getenv("TERM");
214 if (term) {
215 int j;
216 for (j = 0; unsupported_term[j]; j++) {
217 if (strcmp(term, unsupported_term[j]) == 0) {
218 return 1;
222 return 0;
225 static int enableRawMode(struct current *current) {
226 struct termios raw;
228 current->fd = STDIN_FILENO;
230 if (!isatty(current->fd) || isUnsupportedTerm() ||
231 tcgetattr(current->fd, &orig_termios) == -1) {
232 fatal:
233 errno = ENOTTY;
234 return -1;
237 if (!atexit_registered) {
238 atexit(linenoiseAtExit);
239 atexit_registered = 1;
242 raw = orig_termios; /* modify the original mode */
243 /* input modes: no break, no CR to NL, no parity check, no strip char,
244 * no start/stop output control. */
245 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
246 /* output modes - disable post processing */
247 raw.c_oflag &= ~(OPOST);
248 /* control modes - set 8 bit chars */
249 raw.c_cflag |= (CS8);
250 /* local modes - choing off, canonical off, no extended functions,
251 * no signal chars (^Z,^C) */
252 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
253 /* control chars - set return condition: min number of bytes and timer.
254 * We want read to return every single byte, without timeout. */
255 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
257 /* put terminal in raw mode after flushing */
258 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
259 goto fatal;
261 rawmode = 1;
263 current->cols = 0;
264 return 0;
267 static void disableRawMode(struct current *current) {
268 /* Don't even check the return value as it's too late. */
269 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
270 rawmode = 0;
273 /* At exit we'll try to fix the terminal to the initial conditions. */
274 static void linenoiseAtExit(void) {
275 if (rawmode) {
276 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
278 linenoiseHistoryFree();
281 /* gcc/glibc insists that we care about the return code of write!
282 * Clarification: This means that a void-cast like "(void) (EXPR)"
283 * does not work.
285 #define IGNORE_RC(EXPR) if (EXPR) {}
287 /* This is fdprintf() on some systems, but use a different
288 * name to avoid conflicts
290 static void fd_printf(int fd, const char *format, ...)
292 va_list args;
293 char buf[64];
294 int n;
296 va_start(args, format);
297 n = vsnprintf(buf, sizeof(buf), format, args);
298 va_end(args);
299 IGNORE_RC(write(fd, buf, n));
302 static void clearScreen(struct current *current)
304 fd_printf(current->fd, "\x1b[H\x1b[2J");
307 static void cursorToLeft(struct current *current)
309 fd_printf(current->fd, "\r");
312 static int outputChars(struct current *current, const char *buf, int len)
314 return write(current->fd, buf, len);
317 static void outputControlChar(struct current *current, char ch)
319 fd_printf(current->fd, "\x1b[7m^%c\x1b[0m", ch);
322 static void eraseEol(struct current *current)
324 fd_printf(current->fd, "\x1b[0K");
327 static void setCursorPos(struct current *current, int x)
329 fd_printf(current->fd, "\r\x1b[%dC", x);
333 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
335 * A timeout of -1 means to wait forever.
337 * Returns -1 if no char is received within the time or an error occurs.
339 static int fd_read_char(int fd, int timeout)
341 struct pollfd p;
342 unsigned char c;
344 p.fd = fd;
345 p.events = POLLIN;
347 if (poll(&p, 1, timeout) == 0) {
348 /* timeout */
349 return -1;
351 if (read(fd, &c, 1) != 1) {
352 return -1;
354 return c;
358 * Reads a complete utf-8 character
359 * and returns the unicode value, or -1 on error.
361 static int fd_read(struct current *current)
363 #ifdef USE_UTF8
364 char buf[4];
365 int n;
366 int i;
367 int c;
369 if (read(current->fd, &buf[0], 1) != 1) {
370 return -1;
372 n = utf8_charlen(buf[0]);
373 if (n < 1 || n > 3) {
374 return -1;
376 for (i = 1; i < n; i++) {
377 if (read(current->fd, &buf[i], 1) != 1) {
378 return -1;
381 buf[n] = 0;
382 /* decode and return the character */
383 utf8_tounicode(buf, &c);
384 return c;
385 #else
386 return fd_read_char(current->fd, -1);
387 #endif
390 static int countColorControlChars(const char* prompt)
392 /* ANSI color control sequences have the form:
393 * "\x1b" "[" [0-9;]* "m"
394 * We parse them with a simple state machine.
397 enum {
398 search_esc,
399 expect_bracket,
400 expect_trail
401 } state = search_esc;
402 int len = 0, found = 0;
403 char ch;
405 /* XXX: Strictly we should be checking utf8 chars rather than
406 * bytes in case of the extremely unlikely scenario where
407 * an ANSI sequence is part of a utf8 sequence.
409 while ((ch = *prompt++) != 0) {
410 switch (state) {
411 case search_esc:
412 if (ch == '\x1b') {
413 state = expect_bracket;
415 break;
416 case expect_bracket:
417 if (ch == '[') {
418 state = expect_trail;
419 /* 3 for "\e[ ... m" */
420 len = 3;
421 break;
423 state = search_esc;
424 break;
425 case expect_trail:
426 if ((ch == ';') || ((ch >= '0' && ch <= '9'))) {
427 /* 0-9, or semicolon */
428 len++;
429 break;
431 if (ch == 'm') {
432 found += len;
434 state = search_esc;
435 break;
439 return found;
442 static int getWindowSize(struct current *current)
444 struct winsize ws;
446 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
447 current->cols = ws.ws_col;
448 return 0;
451 /* Failed to query the window size. Perhaps we are on a serial terminal.
452 * Try to query the width by sending the cursor as far to the right
453 * and reading back the cursor position.
454 * Note that this is only done once per call to linenoise rather than
455 * every time the line is refreshed for efficiency reasons.
457 if (current->cols == 0) {
458 current->cols = 80;
460 /* Move cursor far right and report cursor position, then back to the left */
461 fd_printf(current->fd, "\x1b[999C" "\x1b[6n");
463 /* Parse the response: ESC [ rows ; cols R */
464 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
465 int n = 0;
466 while (1) {
467 int ch = fd_read_char(current->fd, 100);
468 if (ch == ';') {
469 /* Ignore rows */
470 n = 0;
472 else if (ch == 'R') {
473 /* Got cols */
474 if (n != 0 && n < 1000) {
475 current->cols = n;
477 break;
479 else if (ch >= 0 && ch <= '9') {
480 n = n * 10 + ch - '0';
482 else {
483 break;
488 return 0;
492 * If escape (27) was received, reads subsequent
493 * chars to determine if this is a known special key.
495 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
497 * If no additional char is received within a short time,
498 * 27 is returned.
500 static int check_special(int fd)
502 int c = fd_read_char(fd, 50);
503 int c2;
505 if (c < 0) {
506 return 27;
509 c2 = fd_read_char(fd, 50);
510 if (c2 < 0) {
511 return c2;
513 if (c == '[' || c == 'O') {
514 /* Potential arrow key */
515 switch (c2) {
516 case 'A':
517 return SPECIAL_UP;
518 case 'B':
519 return SPECIAL_DOWN;
520 case 'C':
521 return SPECIAL_RIGHT;
522 case 'D':
523 return SPECIAL_LEFT;
524 case 'F':
525 return SPECIAL_END;
526 case 'H':
527 return SPECIAL_HOME;
530 if (c == '[' && c2 >= '1' && c2 <= '8') {
531 /* extended escape */
532 c = fd_read_char(fd, 50);
533 if (c == '~') {
534 switch (c2) {
535 case '2':
536 return SPECIAL_INSERT;
537 case '3':
538 return SPECIAL_DELETE;
539 case '5':
540 return SPECIAL_PAGE_UP;
541 case '6':
542 return SPECIAL_PAGE_DOWN;
543 case '7':
544 return SPECIAL_HOME;
545 case '8':
546 return SPECIAL_END;
549 while (c != -1 && c != '~') {
550 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
551 c = fd_read_char(fd, 50);
555 return SPECIAL_NONE;
557 #elif defined(USE_WINCONSOLE)
559 static DWORD orig_consolemode = 0;
561 static int enableRawMode(struct current *current) {
562 DWORD n;
563 INPUT_RECORD irec;
565 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
566 current->inh = GetStdHandle(STD_INPUT_HANDLE);
568 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
569 return -1;
571 if (getWindowSize(current) != 0) {
572 return -1;
574 if (GetConsoleMode(current->inh, &orig_consolemode)) {
575 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
577 return 0;
580 static void disableRawMode(struct current *current)
582 SetConsoleMode(current->inh, orig_consolemode);
585 static void clearScreen(struct current *current)
587 COORD topleft = { 0, 0 };
588 DWORD n;
590 FillConsoleOutputCharacter(current->outh, ' ',
591 current->cols * current->rows, topleft, &n);
592 FillConsoleOutputAttribute(current->outh,
593 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
594 current->cols * current->rows, topleft, &n);
595 SetConsoleCursorPosition(current->outh, topleft);
598 static void cursorToLeft(struct current *current)
600 COORD pos = { 0, (SHORT)current->y };
601 DWORD n;
603 FillConsoleOutputAttribute(current->outh,
604 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
605 current->x = 0;
608 static int outputChars(struct current *current, const char *buf, int len)
610 COORD pos = { (SHORT)current->x, (SHORT)current->y };
611 DWORD n;
613 WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
614 current->x += len;
615 return 0;
618 static void outputControlChar(struct current *current, char ch)
620 COORD pos = { (SHORT)current->x, (SHORT)current->y };
621 DWORD n;
623 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
624 outputChars(current, "^", 1);
625 outputChars(current, &ch, 1);
628 static void eraseEol(struct current *current)
630 COORD pos = { (SHORT)current->x, (SHORT)current->y };
631 DWORD n;
633 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
636 static void setCursorPos(struct current *current, int x)
638 COORD pos = { (SHORT)x, (SHORT)current->y };
640 SetConsoleCursorPosition(current->outh, pos);
641 current->x = x;
644 static int fd_read(struct current *current)
646 while (1) {
647 INPUT_RECORD irec;
648 DWORD n;
649 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
650 break;
652 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
653 break;
655 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
656 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
657 if (k->dwControlKeyState & ENHANCED_KEY) {
658 switch (k->wVirtualKeyCode) {
659 case VK_LEFT:
660 return SPECIAL_LEFT;
661 case VK_RIGHT:
662 return SPECIAL_RIGHT;
663 case VK_UP:
664 return SPECIAL_UP;
665 case VK_DOWN:
666 return SPECIAL_DOWN;
667 case VK_INSERT:
668 return SPECIAL_INSERT;
669 case VK_DELETE:
670 return SPECIAL_DELETE;
671 case VK_HOME:
672 return SPECIAL_HOME;
673 case VK_END:
674 return SPECIAL_END;
675 case VK_PRIOR:
676 return SPECIAL_PAGE_UP;
677 case VK_NEXT:
678 return SPECIAL_PAGE_DOWN;
681 /* Note that control characters are already translated in AsciiChar */
682 else {
683 #ifdef USE_UTF8
684 return k->uChar.UnicodeChar;
685 #else
686 return k->uChar.AsciiChar;
687 #endif
691 return -1;
694 static int countColorControlChars(const char* prompt)
696 /* For windows we assume that there are no embedded ansi color
697 * control sequences.
699 return 0;
702 static int getWindowSize(struct current *current)
704 CONSOLE_SCREEN_BUFFER_INFO info;
705 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
706 return -1;
708 current->cols = info.dwSize.X;
709 current->rows = info.dwSize.Y;
710 if (current->cols <= 0 || current->rows <= 0) {
711 current->cols = 80;
712 return -1;
714 current->y = info.dwCursorPosition.Y;
715 current->x = info.dwCursorPosition.X;
716 return 0;
718 #endif
721 * Returns the unicode character at the given offset,
722 * or -1 if none.
724 static int get_char(struct current *current, int pos)
726 if (pos >= 0 && pos < current->chars) {
727 int c;
728 int i = utf8_index(current->buf, pos);
729 (void)utf8_tounicode(current->buf + i, &c);
730 return c;
732 return -1;
735 static void refreshLine(const char *prompt, struct current *current)
737 int plen;
738 int pchars;
739 int backup = 0;
740 int i;
741 const char *buf = current->buf;
742 int chars = current->chars;
743 int pos = current->pos;
744 int b;
745 int ch;
746 int n;
748 /* Should intercept SIGWINCH. For now, just get the size every time */
749 getWindowSize(current);
751 plen = strlen(prompt);
752 pchars = utf8_strlen(prompt, plen);
754 /* Scan the prompt for embedded ansi color control sequences and
755 * discount them as characters/columns.
757 pchars -= countColorControlChars(prompt);
759 /* Account for a line which is too long to fit in the window.
760 * Note that control chars require an extra column
763 /* How many cols are required to the left of 'pos'?
764 * The prompt, plus one extra for each control char
766 n = pchars + utf8_strlen(buf, current->len);
767 b = 0;
768 for (i = 0; i < pos; i++) {
769 b += utf8_tounicode(buf + b, &ch);
770 if (ch < ' ') {
771 n++;
775 /* If too many are needed, strip chars off the front of 'buf'
776 * until it fits. Note that if the current char is a control character,
777 * we need one extra col.
779 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
780 n++;
783 while (n >= current->cols && pos > 0) {
784 b = utf8_tounicode(buf, &ch);
785 if (ch < ' ') {
786 n--;
788 n--;
789 buf += b;
790 pos--;
791 chars--;
794 /* Cursor to left edge, then the prompt */
795 cursorToLeft(current);
796 outputChars(current, prompt, plen);
798 /* Now the current buffer content */
800 /* Need special handling for control characters.
801 * If we hit 'cols', stop.
803 b = 0; /* unwritted bytes */
804 n = 0; /* How many control chars were written */
805 for (i = 0; i < chars; i++) {
806 int ch;
807 int w = utf8_tounicode(buf + b, &ch);
808 if (ch < ' ') {
809 n++;
811 if (pchars + i + n >= current->cols) {
812 break;
814 if (ch < ' ') {
815 /* A control character, so write the buffer so far */
816 outputChars(current, buf, b);
817 buf += b + w;
818 b = 0;
819 outputControlChar(current, ch + '@');
820 if (i < pos) {
821 backup++;
824 else {
825 b += w;
828 outputChars(current, buf, b);
830 /* Erase to right, move cursor to original position */
831 eraseEol(current);
832 setCursorPos(current, pos + pchars + backup);
835 static void set_current(struct current *current, const char *str)
837 strncpy(current->buf, str, current->bufmax);
838 current->buf[current->bufmax - 1] = 0;
839 current->len = strlen(current->buf);
840 current->pos = current->chars = utf8_strlen(current->buf, current->len);
843 static int has_room(struct current *current, int bytes)
845 return current->len + bytes < current->bufmax - 1;
849 * Removes the char at 'pos'.
851 * Returns 1 if the line needs to be refreshed, 2 if not
852 * and 0 if nothing was removed
854 static int remove_char(struct current *current, int pos)
856 if (pos >= 0 && pos < current->chars) {
857 int p1, p2;
858 int ret = 1;
859 p1 = utf8_index(current->buf, pos);
860 p2 = p1 + utf8_index(current->buf + p1, 1);
862 #ifdef USE_TERMIOS
863 /* optimise remove char in the case of removing the last char */
864 if (current->pos == pos + 1 && current->pos == current->chars) {
865 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
866 ret = 2;
867 fd_printf(current->fd, "\b \b");
870 #endif
872 /* Move the null char too */
873 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
874 current->len -= (p2 - p1);
875 current->chars--;
877 if (current->pos > pos) {
878 current->pos--;
880 return ret;
882 return 0;
886 * Insert 'ch' at position 'pos'
888 * Returns 1 if the line needs to be refreshed, 2 if not
889 * and 0 if nothing was inserted (no room)
891 static int insert_char(struct current *current, int pos, int ch)
893 char buf[3];
894 int n = utf8_getchars(buf, ch);
896 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
897 int p1, p2;
898 int ret = 1;
899 p1 = utf8_index(current->buf, pos);
900 p2 = p1 + n;
902 #ifdef USE_TERMIOS
903 /* optimise the case where adding a single char to the end and no scrolling is needed */
904 if (current->pos == pos && current->chars == pos) {
905 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
906 IGNORE_RC(write(current->fd, buf, n));
907 ret = 2;
910 #endif
912 memmove(current->buf + p2, current->buf + p1, current->len - p1);
913 memcpy(current->buf + p1, buf, n);
914 current->len += n;
916 current->chars++;
917 if (current->pos >= pos) {
918 current->pos++;
920 return ret;
922 return 0;
926 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
928 * This replaces any existing characters in the cut buffer.
930 static void capture_chars(struct current *current, int pos, int n)
932 if (pos >= 0 && (pos + n - 1) < current->chars) {
933 int p1 = utf8_index(current->buf, pos);
934 int nbytes = utf8_index(current->buf + p1, n);
936 if (nbytes) {
937 free(current->capture);
938 /* Include space for the null terminator */
939 current->capture = (char *)malloc(nbytes + 1);
940 memcpy(current->capture, current->buf + p1, nbytes);
941 current->capture[nbytes] = '\0';
947 * Removes up to 'n' characters at cursor position 'pos'.
949 * Returns 0 if no chars were removed or non-zero otherwise.
951 static int remove_chars(struct current *current, int pos, int n)
953 int removed = 0;
955 /* First save any chars which will be removed */
956 capture_chars(current, pos, n);
958 while (n-- && remove_char(current, pos)) {
959 removed++;
961 return removed;
964 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
966 * Returns 0 if no chars were inserted or non-zero otherwise.
968 static int insert_chars(struct current *current, int pos, const char *chars)
970 int inserted = 0;
972 while (*chars) {
973 int ch;
974 int n = utf8_tounicode(chars, &ch);
975 if (insert_char(current, pos, ch) == 0) {
976 break;
978 inserted++;
979 pos++;
980 chars += n;
982 return inserted;
985 #ifndef NO_COMPLETION
986 static linenoiseCompletionCallback *completionCallback = NULL;
988 static void beep() {
989 #ifdef USE_TERMIOS
990 fprintf(stderr, "\x7");
991 fflush(stderr);
992 #endif
995 static void freeCompletions(linenoiseCompletions *lc) {
996 size_t i;
997 for (i = 0; i < lc->len; i++)
998 free(lc->cvec[i]);
999 free(lc->cvec);
1002 static int completeLine(struct current *current) {
1003 linenoiseCompletions lc = { 0, NULL };
1004 int c = 0;
1006 completionCallback(current->buf,&lc);
1007 if (lc.len == 0) {
1008 beep();
1009 } else {
1010 size_t stop = 0, i = 0;
1012 while(!stop) {
1013 /* Show completion or original buffer */
1014 if (i < lc.len) {
1015 struct current tmp = *current;
1016 tmp.buf = lc.cvec[i];
1017 tmp.pos = tmp.len = strlen(tmp.buf);
1018 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
1019 refreshLine(current->prompt, &tmp);
1020 } else {
1021 refreshLine(current->prompt, current);
1024 c = fd_read(current);
1025 if (c == -1) {
1026 break;
1029 switch(c) {
1030 case '\t': /* tab */
1031 i = (i+1) % (lc.len+1);
1032 if (i == lc.len) beep();
1033 break;
1034 case 27: /* escape */
1035 /* Re-show original buffer */
1036 if (i < lc.len) {
1037 refreshLine(current->prompt, current);
1039 stop = 1;
1040 break;
1041 default:
1042 /* Update buffer and return */
1043 if (i < lc.len) {
1044 set_current(current,lc.cvec[i]);
1046 stop = 1;
1047 break;
1052 freeCompletions(&lc);
1053 return c; /* Return last read character */
1056 /* Register a callback function to be called for tab-completion. */
1057 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
1058 completionCallback = fn;
1061 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1062 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1063 lc->cvec[lc->len++] = strdup(str);
1066 #endif
1068 static int linenoiseEdit(struct current *current) {
1069 int history_index = 0;
1071 /* The latest history entry is always our current buffer, that
1072 * initially is just an empty string. */
1073 linenoiseHistoryAdd("");
1075 set_current(current, "");
1076 refreshLine(current->prompt, current);
1078 while(1) {
1079 int dir = -1;
1080 int c = fd_read(current);
1082 #ifndef NO_COMPLETION
1083 /* Only autocomplete when the callback is set. It returns < 0 when
1084 * there was an error reading from fd. Otherwise it will return the
1085 * character that should be handled next. */
1086 if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1087 c = completeLine(current);
1088 /* Return on errors */
1089 if (c < 0) return current->len;
1090 /* Read next character when 0 */
1091 if (c == 0) continue;
1093 #endif
1095 process_char:
1096 if (c == -1) return current->len;
1097 #ifdef USE_TERMIOS
1098 if (c == 27) { /* escape sequence */
1099 c = check_special(current->fd);
1101 #endif
1102 switch(c) {
1103 case '\r': /* enter */
1104 history_len--;
1105 free(history[history_len]);
1106 return current->len;
1107 case ctrl('C'): /* ctrl-c */
1108 errno = EAGAIN;
1109 return -1;
1110 case 127: /* backspace */
1111 case ctrl('H'):
1112 if (remove_char(current, current->pos - 1) == 1) {
1113 refreshLine(current->prompt, current);
1115 break;
1116 case ctrl('D'): /* ctrl-d */
1117 if (current->len == 0) {
1118 /* Empty line, so EOF */
1119 history_len--;
1120 free(history[history_len]);
1121 return -1;
1123 /* Otherwise fall through to delete char to right of cursor */
1124 case SPECIAL_DELETE:
1125 if (remove_char(current, current->pos) == 1) {
1126 refreshLine(current->prompt, current);
1128 break;
1129 case SPECIAL_INSERT:
1130 /* Ignore. Expansion Hook.
1131 * Future possibility: Toggle Insert/Overwrite Modes
1133 break;
1134 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1135 /* eat any spaces on the left */
1137 int pos = current->pos;
1138 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1139 pos--;
1142 /* now eat any non-spaces on the left */
1143 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1144 pos--;
1147 if (remove_chars(current, pos, current->pos - pos)) {
1148 refreshLine(current->prompt, current);
1151 break;
1152 case ctrl('R'): /* ctrl-r */
1154 /* Display the reverse-i-search prompt and process chars */
1155 char rbuf[50];
1156 char rprompt[80];
1157 int rchars = 0;
1158 int rlen = 0;
1159 int searchpos = history_len - 1;
1161 rbuf[0] = 0;
1162 while (1) {
1163 int n = 0;
1164 const char *p = NULL;
1165 int skipsame = 0;
1166 int searchdir = -1;
1168 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1169 refreshLine(rprompt, current);
1170 c = fd_read(current);
1171 if (c == ctrl('H') || c == 127) {
1172 if (rchars) {
1173 int p = utf8_index(rbuf, --rchars);
1174 rbuf[p] = 0;
1175 rlen = strlen(rbuf);
1177 continue;
1179 #ifdef USE_TERMIOS
1180 if (c == 27) {
1181 c = check_special(current->fd);
1183 #endif
1184 if (c == ctrl('P') || c == SPECIAL_UP) {
1185 /* Search for the previous (earlier) match */
1186 if (searchpos > 0) {
1187 searchpos--;
1189 skipsame = 1;
1191 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1192 /* Search for the next (later) match */
1193 if (searchpos < history_len) {
1194 searchpos++;
1196 searchdir = 1;
1197 skipsame = 1;
1199 else if (c >= ' ') {
1200 if (rlen >= (int)sizeof(rbuf) + 3) {
1201 continue;
1204 n = utf8_getchars(rbuf + rlen, c);
1205 rlen += n;
1206 rchars++;
1207 rbuf[rlen] = 0;
1209 /* Adding a new char resets the search location */
1210 searchpos = history_len - 1;
1212 else {
1213 /* Exit from incremental search mode */
1214 break;
1217 /* Now search through the history for a match */
1218 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1219 p = strstr(history[searchpos], rbuf);
1220 if (p) {
1221 /* Found a match */
1222 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1223 /* But it is identical, so skip it */
1224 continue;
1226 /* Copy the matching line and set the cursor position */
1227 set_current(current,history[searchpos]);
1228 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1229 break;
1232 if (!p && n) {
1233 /* No match, so don't add it */
1234 rchars--;
1235 rlen -= n;
1236 rbuf[rlen] = 0;
1239 if (c == ctrl('G') || c == ctrl('C')) {
1240 /* ctrl-g terminates the search with no effect */
1241 set_current(current, "");
1242 c = 0;
1244 else if (c == ctrl('J')) {
1245 /* ctrl-j terminates the search leaving the buffer in place */
1246 c = 0;
1248 /* Go process the char normally */
1249 refreshLine(current->prompt, current);
1250 goto process_char;
1252 break;
1253 case ctrl('T'): /* ctrl-t */
1254 if (current->pos > 0 && current->pos <= current->chars) {
1255 /* If cursor is at end, transpose the previous two chars */
1256 int fixer = (current->pos == current->chars);
1257 c = get_char(current, current->pos - fixer);
1258 remove_char(current, current->pos - fixer);
1259 insert_char(current, current->pos - 1, c);
1260 refreshLine(current->prompt, current);
1262 break;
1263 case ctrl('V'): /* ctrl-v */
1264 if (has_room(current, 3)) {
1265 /* Insert the ^V first */
1266 if (insert_char(current, current->pos, c)) {
1267 refreshLine(current->prompt, current);
1268 /* Now wait for the next char. Can insert anything except \0 */
1269 c = fd_read(current);
1271 /* Remove the ^V first */
1272 remove_char(current, current->pos - 1);
1273 if (c != -1) {
1274 /* Insert the actual char */
1275 insert_char(current, current->pos, c);
1277 refreshLine(current->prompt, current);
1280 break;
1281 case ctrl('B'):
1282 case SPECIAL_LEFT:
1283 if (current->pos > 0) {
1284 current->pos--;
1285 refreshLine(current->prompt, current);
1287 break;
1288 case ctrl('F'):
1289 case SPECIAL_RIGHT:
1290 if (current->pos < current->chars) {
1291 current->pos++;
1292 refreshLine(current->prompt, current);
1294 break;
1295 case SPECIAL_PAGE_UP:
1296 dir = history_len - history_index - 1; /* move to start of history */
1297 goto history_navigation;
1298 case SPECIAL_PAGE_DOWN:
1299 dir = -history_index; /* move to 0 == end of history, i.e. current */
1300 goto history_navigation;
1301 case ctrl('P'):
1302 case SPECIAL_UP:
1303 dir = 1;
1304 goto history_navigation;
1305 case ctrl('N'):
1306 case SPECIAL_DOWN:
1307 history_navigation:
1308 if (history_len > 1) {
1309 /* Update the current history entry before to
1310 * overwrite it with tne next one. */
1311 free(history[history_len - 1 - history_index]);
1312 history[history_len - 1 - history_index] = strdup(current->buf);
1313 /* Show the new entry */
1314 history_index += dir;
1315 if (history_index < 0) {
1316 history_index = 0;
1317 break;
1318 } else if (history_index >= history_len) {
1319 history_index = history_len - 1;
1320 break;
1322 set_current(current, history[history_len - 1 - history_index]);
1323 refreshLine(current->prompt, current);
1325 break;
1326 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1327 case SPECIAL_HOME:
1328 current->pos = 0;
1329 refreshLine(current->prompt, current);
1330 break;
1331 case ctrl('E'): /* ctrl+e, go to the end of the line */
1332 case SPECIAL_END:
1333 current->pos = current->chars;
1334 refreshLine(current->prompt, current);
1335 break;
1336 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1337 if (remove_chars(current, 0, current->pos)) {
1338 refreshLine(current->prompt, current);
1340 break;
1341 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1342 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1343 refreshLine(current->prompt, current);
1345 break;
1346 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1347 if (current->capture && insert_chars(current, current->pos, current->capture)) {
1348 refreshLine(current->prompt, current);
1350 break;
1351 case ctrl('L'): /* Ctrl+L, clear screen */
1352 clearScreen(current);
1353 /* Force recalc of window size for serial terminals */
1354 current->cols = 0;
1355 refreshLine(current->prompt, current);
1356 break;
1357 default:
1358 /* Only tab is allowed without ^V */
1359 if (c == '\t' || c >= ' ') {
1360 if (insert_char(current, current->pos, c) == 1) {
1361 refreshLine(current->prompt, current);
1364 break;
1367 return current->len;
1370 int linenoiseColumns(void)
1372 struct current current;
1373 enableRawMode (&current);
1374 getWindowSize (&current);
1375 disableRawMode (&current);
1376 return current.cols;
1379 char *linenoise(const char *prompt)
1381 int count;
1382 struct current current;
1383 char buf[LINENOISE_MAX_LINE];
1385 if (enableRawMode(&current) == -1) {
1386 printf("%s", prompt);
1387 fflush(stdout);
1388 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1389 return NULL;
1391 count = strlen(buf);
1392 if (count && buf[count-1] == '\n') {
1393 count--;
1394 buf[count] = '\0';
1397 else
1399 current.buf = buf;
1400 current.bufmax = sizeof(buf);
1401 current.len = 0;
1402 current.chars = 0;
1403 current.pos = 0;
1404 current.prompt = prompt;
1405 current.capture = NULL;
1407 count = linenoiseEdit(&current);
1409 disableRawMode(&current);
1410 printf("\n");
1412 free(current.capture);
1413 if (count == -1) {
1414 return NULL;
1417 return strdup(buf);
1420 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1421 int linenoiseHistoryAdd(const char *line) {
1422 char *linecopy;
1424 if (history_max_len == 0) return 0;
1425 if (history == NULL) {
1426 history = (char **)malloc(sizeof(char*)*history_max_len);
1427 if (history == NULL) return 0;
1428 memset(history,0,(sizeof(char*)*history_max_len));
1431 /* do not insert duplicate lines into history */
1432 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1433 return 0;
1436 linecopy = strdup(line);
1437 if (!linecopy) return 0;
1438 if (history_len == history_max_len) {
1439 free(history[0]);
1440 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1441 history_len--;
1443 history[history_len] = linecopy;
1444 history_len++;
1445 return 1;
1448 int linenoiseHistoryGetMaxLen(void) {
1449 return history_max_len;
1452 int linenoiseHistorySetMaxLen(int len) {
1453 char **newHistory;
1455 if (len < 1) return 0;
1456 if (history) {
1457 int tocopy = history_len;
1459 newHistory = (char **)malloc(sizeof(char*)*len);
1460 if (newHistory == NULL) return 0;
1462 /* If we can't copy everything, free the elements we'll not use. */
1463 if (len < tocopy) {
1464 int j;
1466 for (j = 0; j < tocopy-len; j++) free(history[j]);
1467 tocopy = len;
1469 memset(newHistory,0,sizeof(char*)*len);
1470 memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1471 free(history);
1472 history = newHistory;
1474 history_max_len = len;
1475 if (history_len > history_max_len)
1476 history_len = history_max_len;
1477 return 1;
1480 /* Save the history in the specified file. On success 0 is returned
1481 * otherwise -1 is returned. */
1482 int linenoiseHistorySave(const char *filename) {
1483 FILE *fp = fopen(filename,"w");
1484 int j;
1486 if (fp == NULL) return -1;
1487 for (j = 0; j < history_len; j++) {
1488 const char *str = history[j];
1489 /* Need to encode backslash, nl and cr */
1490 while (*str) {
1491 if (*str == '\\') {
1492 fputs("\\\\", fp);
1494 else if (*str == '\n') {
1495 fputs("\\n", fp);
1497 else if (*str == '\r') {
1498 fputs("\\r", fp);
1500 else {
1501 fputc(*str, fp);
1503 str++;
1505 fputc('\n', fp);
1508 fclose(fp);
1509 return 0;
1512 /* Load the history from the specified file. If the file does not exist
1513 * zero is returned and no operation is performed.
1515 * If the file exists and the operation succeeded 0 is returned, otherwise
1516 * on error -1 is returned. */
1517 int linenoiseHistoryLoad(const char *filename) {
1518 FILE *fp = fopen(filename,"r");
1519 char buf[LINENOISE_MAX_LINE];
1521 if (fp == NULL) return -1;
1523 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1524 char *src, *dest;
1526 /* Decode backslash escaped values */
1527 for (src = dest = buf; *src; src++) {
1528 char ch = *src;
1530 if (ch == '\\') {
1531 src++;
1532 if (*src == 'n') {
1533 ch = '\n';
1535 else if (*src == 'r') {
1536 ch = '\r';
1537 } else {
1538 ch = *src;
1541 *dest++ = ch;
1543 /* Remove trailing newline */
1544 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1545 dest--;
1547 *dest = 0;
1549 linenoiseHistoryAdd(buf);
1551 fclose(fp);
1552 return 0;
1555 /* Provide access to the history buffer.
1557 * If 'len' is not NULL, the length is stored in *len.
1559 char **linenoiseHistory(int *len) {
1560 if (len) {
1561 *len = history_len;
1563 return history;