Fix memory management of aio event handlers
[jimtcl.git] / linenoise.c
blob6a16eee84f18b3d2e7545d70b561a5d5288387c2
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, int plen)
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_inner,
401 expect_trail
402 } state = search_esc;
403 int len, found = 0;
404 char ch;
406 /* XXX: Strictly we should be checking utf8 chars rather than
407 * bytes in case of the extremely unlikely scenario where
408 * an ANSI sequence is part of a utf8 sequence.
410 for (; plen ; plen--, prompt++) {
411 ch = *prompt;
413 switch (state) {
414 case search_esc:
415 len = 0;
416 if (ch == '\x1b') {
417 state = expect_bracket;
418 len++;
420 break;
421 case expect_bracket:
422 if (ch == '[') {
423 state = expect_inner;
424 len++;
425 } else {
426 state = search_esc;
428 break;
429 case expect_inner:
430 if (ch >= '0' && ch <= '9') {
431 len++;
432 state = expect_trail;
433 } else {
434 state = search_esc;
436 break;
437 case expect_trail:
438 if (ch == 'm') {
439 len++;
440 found += len;
441 state = search_esc;
442 } else if ((ch != ';') && ((ch < '0') || (ch > '9'))) {
443 state = search_esc;
445 /* 0-9, or semicolon */
446 len++;
447 break;
451 return found;
454 static int getWindowSize(struct current *current)
456 struct winsize ws;
458 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
459 current->cols = ws.ws_col;
460 return 0;
463 /* Failed to query the window size. Perhaps we are on a serial terminal.
464 * Try to query the width by sending the cursor as far to the right
465 * and reading back the cursor position.
466 * Note that this is only done once per call to linenoise rather than
467 * every time the line is refreshed for efficiency reasons.
469 if (current->cols == 0) {
470 current->cols = 80;
472 /* Move cursor far right and report cursor position, then back to the left */
473 fd_printf(current->fd, "\x1b[999C" "\x1b[6n");
475 /* Parse the response: ESC [ rows ; cols R */
476 if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
477 int n = 0;
478 while (1) {
479 int ch = fd_read_char(current->fd, 100);
480 if (ch == ';') {
481 /* Ignore rows */
482 n = 0;
484 else if (ch == 'R') {
485 /* Got cols */
486 if (n != 0 && n < 1000) {
487 current->cols = n;
489 break;
491 else if (ch >= 0 && ch <= '9') {
492 n = n * 10 + ch - '0';
494 else {
495 break;
500 return 0;
504 * If escape (27) was received, reads subsequent
505 * chars to determine if this is a known special key.
507 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
509 * If no additional char is received within a short time,
510 * 27 is returned.
512 static int check_special(int fd)
514 int c = fd_read_char(fd, 50);
515 int c2;
517 if (c < 0) {
518 return 27;
521 c2 = fd_read_char(fd, 50);
522 if (c2 < 0) {
523 return c2;
525 if (c == '[' || c == 'O') {
526 /* Potential arrow key */
527 switch (c2) {
528 case 'A':
529 return SPECIAL_UP;
530 case 'B':
531 return SPECIAL_DOWN;
532 case 'C':
533 return SPECIAL_RIGHT;
534 case 'D':
535 return SPECIAL_LEFT;
536 case 'F':
537 return SPECIAL_END;
538 case 'H':
539 return SPECIAL_HOME;
542 if (c == '[' && c2 >= '1' && c2 <= '8') {
543 /* extended escape */
544 c = fd_read_char(fd, 50);
545 if (c == '~') {
546 switch (c2) {
547 case '2':
548 return SPECIAL_INSERT;
549 case '3':
550 return SPECIAL_DELETE;
551 case '5':
552 return SPECIAL_PAGE_UP;
553 case '6':
554 return SPECIAL_PAGE_DOWN;
555 case '7':
556 return SPECIAL_HOME;
557 case '8':
558 return SPECIAL_END;
561 while (c != -1 && c != '~') {
562 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
563 c = fd_read_char(fd, 50);
567 return SPECIAL_NONE;
569 #elif defined(USE_WINCONSOLE)
571 static DWORD orig_consolemode = 0;
573 static int enableRawMode(struct current *current) {
574 DWORD n;
575 INPUT_RECORD irec;
577 current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
578 current->inh = GetStdHandle(STD_INPUT_HANDLE);
580 if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
581 return -1;
583 if (getWindowSize(current) != 0) {
584 return -1;
586 if (GetConsoleMode(current->inh, &orig_consolemode)) {
587 SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
589 return 0;
592 static void disableRawMode(struct current *current)
594 SetConsoleMode(current->inh, orig_consolemode);
597 static void clearScreen(struct current *current)
599 COORD topleft = { 0, 0 };
600 DWORD n;
602 FillConsoleOutputCharacter(current->outh, ' ',
603 current->cols * current->rows, topleft, &n);
604 FillConsoleOutputAttribute(current->outh,
605 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
606 current->cols * current->rows, topleft, &n);
607 SetConsoleCursorPosition(current->outh, topleft);
610 static void cursorToLeft(struct current *current)
612 COORD pos = { 0, (SHORT)current->y };
613 DWORD n;
615 FillConsoleOutputAttribute(current->outh,
616 FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
617 current->x = 0;
620 static int outputChars(struct current *current, const char *buf, int len)
622 COORD pos = { (SHORT)current->x, (SHORT)current->y };
623 DWORD n;
625 WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
626 current->x += len;
627 return 0;
630 static void outputControlChar(struct current *current, char ch)
632 COORD pos = { (SHORT)current->x, (SHORT)current->y };
633 DWORD n;
635 FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
636 outputChars(current, "^", 1);
637 outputChars(current, &ch, 1);
640 static void eraseEol(struct current *current)
642 COORD pos = { (SHORT)current->x, (SHORT)current->y };
643 DWORD n;
645 FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
648 static void setCursorPos(struct current *current, int x)
650 COORD pos = { (SHORT)x, (SHORT)current->y };
652 SetConsoleCursorPosition(current->outh, pos);
653 current->x = x;
656 static int fd_read(struct current *current)
658 while (1) {
659 INPUT_RECORD irec;
660 DWORD n;
661 if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
662 break;
664 if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
665 break;
667 if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
668 KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
669 if (k->dwControlKeyState & ENHANCED_KEY) {
670 switch (k->wVirtualKeyCode) {
671 case VK_LEFT:
672 return SPECIAL_LEFT;
673 case VK_RIGHT:
674 return SPECIAL_RIGHT;
675 case VK_UP:
676 return SPECIAL_UP;
677 case VK_DOWN:
678 return SPECIAL_DOWN;
679 case VK_INSERT:
680 return SPECIAL_INSERT;
681 case VK_DELETE:
682 return SPECIAL_DELETE;
683 case VK_HOME:
684 return SPECIAL_HOME;
685 case VK_END:
686 return SPECIAL_END;
687 case VK_PRIOR:
688 return SPECIAL_PAGE_UP;
689 case VK_NEXT:
690 return SPECIAL_PAGE_DOWN;
693 /* Note that control characters are already translated in AsciiChar */
694 else {
695 #ifdef USE_UTF8
696 return k->uChar.UnicodeChar;
697 #else
698 return k->uChar.AsciiChar;
699 #endif
703 return -1;
706 static int countColorControlChars(char* prompt, int plen)
708 /* For windows we assume that there are no embedded ansi color
709 * control sequences.
711 return 0;
714 static int getWindowSize(struct current *current)
716 CONSOLE_SCREEN_BUFFER_INFO info;
717 if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
718 return -1;
720 current->cols = info.dwSize.X;
721 current->rows = info.dwSize.Y;
722 if (current->cols <= 0 || current->rows <= 0) {
723 current->cols = 80;
724 return -1;
726 current->y = info.dwCursorPosition.Y;
727 current->x = info.dwCursorPosition.X;
728 return 0;
730 #endif
732 static int utf8_getchars(char *buf, int c)
734 #ifdef USE_UTF8
735 return utf8_fromunicode(buf, c);
736 #else
737 *buf = c;
738 return 1;
739 #endif
743 * Returns the unicode character at the given offset,
744 * or -1 if none.
746 static int get_char(struct current *current, int pos)
748 if (pos >= 0 && pos < current->chars) {
749 int c;
750 int i = utf8_index(current->buf, pos);
751 (void)utf8_tounicode(current->buf + i, &c);
752 return c;
754 return -1;
757 static void refreshLine(const char *prompt, struct current *current)
759 int plen;
760 int pchars;
761 int backup = 0;
762 int i;
763 const char *buf = current->buf;
764 int chars = current->chars;
765 int pos = current->pos;
766 int b;
767 int ch;
768 int n;
770 /* Should intercept SIGWINCH. For now, just get the size every time */
771 getWindowSize(current);
773 plen = strlen(prompt);
774 pchars = utf8_strlen(prompt, plen);
776 /* Scan the prompt for embedded ansi color control sequences and
777 * discount them as characters/columns.
779 pchars -= countColorControlChars(prompt, plen);
781 /* Account for a line which is too long to fit in the window.
782 * Note that control chars require an extra column
785 /* How many cols are required to the left of 'pos'?
786 * The prompt, plus one extra for each control char
788 n = pchars + utf8_strlen(buf, current->len);
789 b = 0;
790 for (i = 0; i < pos; i++) {
791 b += utf8_tounicode(buf + b, &ch);
792 if (ch < ' ') {
793 n++;
797 /* If too many are needed, strip chars off the front of 'buf'
798 * until it fits. Note that if the current char is a control character,
799 * we need one extra col.
801 if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
802 n++;
805 while (n >= current->cols && pos > 0) {
806 b = utf8_tounicode(buf, &ch);
807 if (ch < ' ') {
808 n--;
810 n--;
811 buf += b;
812 pos--;
813 chars--;
816 /* Cursor to left edge, then the prompt */
817 cursorToLeft(current);
818 outputChars(current, prompt, plen);
820 /* Now the current buffer content */
822 /* Need special handling for control characters.
823 * If we hit 'cols', stop.
825 b = 0; /* unwritted bytes */
826 n = 0; /* How many control chars were written */
827 for (i = 0; i < chars; i++) {
828 int ch;
829 int w = utf8_tounicode(buf + b, &ch);
830 if (ch < ' ') {
831 n++;
833 if (pchars + i + n >= current->cols) {
834 break;
836 if (ch < ' ') {
837 /* A control character, so write the buffer so far */
838 outputChars(current, buf, b);
839 buf += b + w;
840 b = 0;
841 outputControlChar(current, ch + '@');
842 if (i < pos) {
843 backup++;
846 else {
847 b += w;
850 outputChars(current, buf, b);
852 /* Erase to right, move cursor to original position */
853 eraseEol(current);
854 setCursorPos(current, pos + pchars + backup);
857 static void set_current(struct current *current, const char *str)
859 strncpy(current->buf, str, current->bufmax);
860 current->buf[current->bufmax - 1] = 0;
861 current->len = strlen(current->buf);
862 current->pos = current->chars = utf8_strlen(current->buf, current->len);
865 static int has_room(struct current *current, int bytes)
867 return current->len + bytes < current->bufmax - 1;
871 * Removes the char at 'pos'.
873 * Returns 1 if the line needs to be refreshed, 2 if not
874 * and 0 if nothing was removed
876 static int remove_char(struct current *current, int pos)
878 if (pos >= 0 && pos < current->chars) {
879 int p1, p2;
880 int ret = 1;
881 p1 = utf8_index(current->buf, pos);
882 p2 = p1 + utf8_index(current->buf + p1, 1);
884 #ifdef USE_TERMIOS
885 /* optimise remove char in the case of removing the last char */
886 if (current->pos == pos + 1 && current->pos == current->chars) {
887 if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
888 ret = 2;
889 fd_printf(current->fd, "\b \b");
892 #endif
894 /* Move the null char too */
895 memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
896 current->len -= (p2 - p1);
897 current->chars--;
899 if (current->pos > pos) {
900 current->pos--;
902 return ret;
904 return 0;
908 * Insert 'ch' at position 'pos'
910 * Returns 1 if the line needs to be refreshed, 2 if not
911 * and 0 if nothing was inserted (no room)
913 static int insert_char(struct current *current, int pos, int ch)
915 char buf[3];
916 int n = utf8_getchars(buf, ch);
918 if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
919 int p1, p2;
920 int ret = 1;
921 p1 = utf8_index(current->buf, pos);
922 p2 = p1 + n;
924 #ifdef USE_TERMIOS
925 /* optimise the case where adding a single char to the end and no scrolling is needed */
926 if (current->pos == pos && current->chars == pos) {
927 if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
928 IGNORE_RC(write(current->fd, buf, n));
929 ret = 2;
932 #endif
934 memmove(current->buf + p2, current->buf + p1, current->len - p1);
935 memcpy(current->buf + p1, buf, n);
936 current->len += n;
938 current->chars++;
939 if (current->pos >= pos) {
940 current->pos++;
942 return ret;
944 return 0;
948 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
950 * This replaces any existing characters in the cut buffer.
952 static void capture_chars(struct current *current, int pos, int n)
954 if (pos >= 0 && (pos + n - 1) < current->chars) {
955 int p1 = utf8_index(current->buf, pos);
956 int nbytes = utf8_index(current->buf + p1, n);
958 if (nbytes) {
959 free(current->capture);
960 /* Include space for the null terminator */
961 current->capture = (char *)malloc(nbytes + 1);
962 memcpy(current->capture, current->buf + p1, nbytes);
963 current->capture[nbytes] = '\0';
969 * Removes up to 'n' characters at cursor position 'pos'.
971 * Returns 0 if no chars were removed or non-zero otherwise.
973 static int remove_chars(struct current *current, int pos, int n)
975 int removed = 0;
977 /* First save any chars which will be removed */
978 capture_chars(current, pos, n);
980 while (n-- && remove_char(current, pos)) {
981 removed++;
983 return removed;
986 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
988 * Returns 0 if no chars were inserted or non-zero otherwise.
990 static int insert_chars(struct current *current, int pos, const char *chars)
992 int inserted = 0;
994 while (*chars) {
995 int ch;
996 int n = utf8_tounicode(chars, &ch);
997 if (insert_char(current, pos, ch) == 0) {
998 break;
1000 inserted++;
1001 pos++;
1002 chars += n;
1004 return inserted;
1007 #ifndef NO_COMPLETION
1008 static linenoiseCompletionCallback *completionCallback = NULL;
1010 static void beep() {
1011 #ifdef USE_TERMIOS
1012 fprintf(stderr, "\x7");
1013 fflush(stderr);
1014 #endif
1017 static void freeCompletions(linenoiseCompletions *lc) {
1018 size_t i;
1019 for (i = 0; i < lc->len; i++)
1020 free(lc->cvec[i]);
1021 free(lc->cvec);
1024 static int completeLine(struct current *current) {
1025 linenoiseCompletions lc = { 0, NULL };
1026 int c = 0;
1028 completionCallback(current->buf,&lc);
1029 if (lc.len == 0) {
1030 beep();
1031 } else {
1032 size_t stop = 0, i = 0;
1034 while(!stop) {
1035 /* Show completion or original buffer */
1036 if (i < lc.len) {
1037 struct current tmp = *current;
1038 tmp.buf = lc.cvec[i];
1039 tmp.pos = tmp.len = strlen(tmp.buf);
1040 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
1041 refreshLine(current->prompt, &tmp);
1042 } else {
1043 refreshLine(current->prompt, current);
1046 c = fd_read(current);
1047 if (c == -1) {
1048 break;
1051 switch(c) {
1052 case '\t': /* tab */
1053 i = (i+1) % (lc.len+1);
1054 if (i == lc.len) beep();
1055 break;
1056 case 27: /* escape */
1057 /* Re-show original buffer */
1058 if (i < lc.len) {
1059 refreshLine(current->prompt, current);
1061 stop = 1;
1062 break;
1063 default:
1064 /* Update buffer and return */
1065 if (i < lc.len) {
1066 set_current(current,lc.cvec[i]);
1068 stop = 1;
1069 break;
1074 freeCompletions(&lc);
1075 return c; /* Return last read character */
1078 /* Register a callback function to be called for tab-completion. */
1079 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
1080 completionCallback = fn;
1083 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1084 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1085 lc->cvec[lc->len++] = strdup(str);
1088 #endif
1090 static int linenoiseEdit(struct current *current) {
1091 int history_index = 0;
1093 /* The latest history entry is always our current buffer, that
1094 * initially is just an empty string. */
1095 linenoiseHistoryAdd("");
1097 set_current(current, "");
1098 refreshLine(current->prompt, current);
1100 while(1) {
1101 int dir = -1;
1102 int c = fd_read(current);
1104 #ifndef NO_COMPLETION
1105 /* Only autocomplete when the callback is set. It returns < 0 when
1106 * there was an error reading from fd. Otherwise it will return the
1107 * character that should be handled next. */
1108 if (c == '\t' && current->pos == current->chars && completionCallback != NULL) {
1109 c = completeLine(current);
1110 /* Return on errors */
1111 if (c < 0) return current->len;
1112 /* Read next character when 0 */
1113 if (c == 0) continue;
1115 #endif
1117 process_char:
1118 if (c == -1) return current->len;
1119 #ifdef USE_TERMIOS
1120 if (c == 27) { /* escape sequence */
1121 c = check_special(current->fd);
1123 #endif
1124 switch(c) {
1125 case '\r': /* enter */
1126 history_len--;
1127 free(history[history_len]);
1128 return current->len;
1129 case ctrl('C'): /* ctrl-c */
1130 errno = EAGAIN;
1131 return -1;
1132 case 127: /* backspace */
1133 case ctrl('H'):
1134 if (remove_char(current, current->pos - 1) == 1) {
1135 refreshLine(current->prompt, current);
1137 break;
1138 case ctrl('D'): /* ctrl-d */
1139 if (current->len == 0) {
1140 /* Empty line, so EOF */
1141 history_len--;
1142 free(history[history_len]);
1143 return -1;
1145 /* Otherwise fall through to delete char to right of cursor */
1146 case SPECIAL_DELETE:
1147 if (remove_char(current, current->pos) == 1) {
1148 refreshLine(current->prompt, current);
1150 break;
1151 case SPECIAL_INSERT:
1152 /* Ignore. Expansion Hook.
1153 * Future possibility: Toggle Insert/Overwrite Modes
1155 break;
1156 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1157 /* eat any spaces on the left */
1159 int pos = current->pos;
1160 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1161 pos--;
1164 /* now eat any non-spaces on the left */
1165 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1166 pos--;
1169 if (remove_chars(current, pos, current->pos - pos)) {
1170 refreshLine(current->prompt, current);
1173 break;
1174 case ctrl('R'): /* ctrl-r */
1176 /* Display the reverse-i-search prompt and process chars */
1177 char rbuf[50];
1178 char rprompt[80];
1179 int rchars = 0;
1180 int rlen = 0;
1181 int searchpos = history_len - 1;
1183 rbuf[0] = 0;
1184 while (1) {
1185 int n = 0;
1186 const char *p = NULL;
1187 int skipsame = 0;
1188 int searchdir = -1;
1190 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1191 refreshLine(rprompt, current);
1192 c = fd_read(current);
1193 if (c == ctrl('H') || c == 127) {
1194 if (rchars) {
1195 int p = utf8_index(rbuf, --rchars);
1196 rbuf[p] = 0;
1197 rlen = strlen(rbuf);
1199 continue;
1201 #ifdef USE_TERMIOS
1202 if (c == 27) {
1203 c = check_special(current->fd);
1205 #endif
1206 if (c == ctrl('P') || c == SPECIAL_UP) {
1207 /* Search for the previous (earlier) match */
1208 if (searchpos > 0) {
1209 searchpos--;
1211 skipsame = 1;
1213 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1214 /* Search for the next (later) match */
1215 if (searchpos < history_len) {
1216 searchpos++;
1218 searchdir = 1;
1219 skipsame = 1;
1221 else if (c >= ' ') {
1222 if (rlen >= (int)sizeof(rbuf) + 3) {
1223 continue;
1226 n = utf8_getchars(rbuf + rlen, c);
1227 rlen += n;
1228 rchars++;
1229 rbuf[rlen] = 0;
1231 /* Adding a new char resets the search location */
1232 searchpos = history_len - 1;
1234 else {
1235 /* Exit from incremental search mode */
1236 break;
1239 /* Now search through the history for a match */
1240 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1241 p = strstr(history[searchpos], rbuf);
1242 if (p) {
1243 /* Found a match */
1244 if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1245 /* But it is identical, so skip it */
1246 continue;
1248 /* Copy the matching line and set the cursor position */
1249 set_current(current,history[searchpos]);
1250 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1251 break;
1254 if (!p && n) {
1255 /* No match, so don't add it */
1256 rchars--;
1257 rlen -= n;
1258 rbuf[rlen] = 0;
1261 if (c == ctrl('G') || c == ctrl('C')) {
1262 /* ctrl-g terminates the search with no effect */
1263 set_current(current, "");
1264 c = 0;
1266 else if (c == ctrl('J')) {
1267 /* ctrl-j terminates the search leaving the buffer in place */
1268 c = 0;
1270 /* Go process the char normally */
1271 refreshLine(current->prompt, current);
1272 goto process_char;
1274 break;
1275 case ctrl('T'): /* ctrl-t */
1276 if (current->pos > 0 && current->pos <= current->chars) {
1277 /* If cursor is at end, transpose the previous two chars */
1278 int fixer = (current->pos == current->chars);
1279 c = get_char(current, current->pos - fixer);
1280 remove_char(current, current->pos - fixer);
1281 insert_char(current, current->pos - 1, c);
1282 refreshLine(current->prompt, current);
1284 break;
1285 case ctrl('V'): /* ctrl-v */
1286 if (has_room(current, 3)) {
1287 /* Insert the ^V first */
1288 if (insert_char(current, current->pos, c)) {
1289 refreshLine(current->prompt, current);
1290 /* Now wait for the next char. Can insert anything except \0 */
1291 c = fd_read(current);
1293 /* Remove the ^V first */
1294 remove_char(current, current->pos - 1);
1295 if (c != -1) {
1296 /* Insert the actual char */
1297 insert_char(current, current->pos, c);
1299 refreshLine(current->prompt, current);
1302 break;
1303 case ctrl('B'):
1304 case SPECIAL_LEFT:
1305 if (current->pos > 0) {
1306 current->pos--;
1307 refreshLine(current->prompt, current);
1309 break;
1310 case ctrl('F'):
1311 case SPECIAL_RIGHT:
1312 if (current->pos < current->chars) {
1313 current->pos++;
1314 refreshLine(current->prompt, current);
1316 break;
1317 case SPECIAL_PAGE_UP:
1318 dir = history_len - history_index - 1; /* move to start of history */
1319 goto history_navigation;
1320 case SPECIAL_PAGE_DOWN:
1321 dir = -history_index; /* move to 0 == end of history, i.e. current */
1322 goto history_navigation;
1323 case ctrl('P'):
1324 case SPECIAL_UP:
1325 dir = 1;
1326 goto history_navigation;
1327 case ctrl('N'):
1328 case SPECIAL_DOWN:
1329 history_navigation:
1330 if (history_len > 1) {
1331 /* Update the current history entry before to
1332 * overwrite it with tne next one. */
1333 free(history[history_len - 1 - history_index]);
1334 history[history_len - 1 - history_index] = strdup(current->buf);
1335 /* Show the new entry */
1336 history_index += dir;
1337 if (history_index < 0) {
1338 history_index = 0;
1339 break;
1340 } else if (history_index >= history_len) {
1341 history_index = history_len - 1;
1342 break;
1344 set_current(current, history[history_len - 1 - history_index]);
1345 refreshLine(current->prompt, current);
1347 break;
1348 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1349 case SPECIAL_HOME:
1350 current->pos = 0;
1351 refreshLine(current->prompt, current);
1352 break;
1353 case ctrl('E'): /* ctrl+e, go to the end of the line */
1354 case SPECIAL_END:
1355 current->pos = current->chars;
1356 refreshLine(current->prompt, current);
1357 break;
1358 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1359 if (remove_chars(current, 0, current->pos)) {
1360 refreshLine(current->prompt, current);
1362 break;
1363 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1364 if (remove_chars(current, current->pos, current->chars - current->pos)) {
1365 refreshLine(current->prompt, current);
1367 break;
1368 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1369 if (current->capture && insert_chars(current, current->pos, current->capture)) {
1370 refreshLine(current->prompt, current);
1372 break;
1373 case ctrl('L'): /* Ctrl+L, clear screen */
1374 clearScreen(current);
1375 /* Force recalc of window size for serial terminals */
1376 current->cols = 0;
1377 refreshLine(current->prompt, current);
1378 break;
1379 default:
1380 /* Only tab is allowed without ^V */
1381 if (c == '\t' || c >= ' ') {
1382 if (insert_char(current, current->pos, c) == 1) {
1383 refreshLine(current->prompt, current);
1386 break;
1389 return current->len;
1392 int linenoiseColumns(void)
1394 struct current current;
1395 enableRawMode (&current);
1396 getWindowSize (&current);
1397 disableRawMode (&current);
1398 return current.cols;
1401 char *linenoise(const char *prompt)
1403 int count;
1404 struct current current;
1405 char buf[LINENOISE_MAX_LINE];
1407 if (enableRawMode(&current) == -1) {
1408 printf("%s", prompt);
1409 fflush(stdout);
1410 if (fgets(buf, sizeof(buf), stdin) == NULL) {
1411 return NULL;
1413 count = strlen(buf);
1414 if (count && buf[count-1] == '\n') {
1415 count--;
1416 buf[count] = '\0';
1419 else
1421 current.buf = buf;
1422 current.bufmax = sizeof(buf);
1423 current.len = 0;
1424 current.chars = 0;
1425 current.pos = 0;
1426 current.prompt = prompt;
1427 current.capture = NULL;
1429 count = linenoiseEdit(&current);
1431 disableRawMode(&current);
1432 printf("\n");
1434 free(current.capture);
1435 if (count == -1) {
1436 return NULL;
1439 return strdup(buf);
1442 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1443 int linenoiseHistoryAdd(const char *line) {
1444 char *linecopy;
1446 if (history_max_len == 0) return 0;
1447 if (history == NULL) {
1448 history = (char **)malloc(sizeof(char*)*history_max_len);
1449 if (history == NULL) return 0;
1450 memset(history,0,(sizeof(char*)*history_max_len));
1453 /* do not insert duplicate lines into history */
1454 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1455 return 0;
1458 linecopy = strdup(line);
1459 if (!linecopy) return 0;
1460 if (history_len == history_max_len) {
1461 free(history[0]);
1462 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1463 history_len--;
1465 history[history_len] = linecopy;
1466 history_len++;
1467 return 1;
1470 int linenoiseHistoryGetMaxLen(void) {
1471 return history_max_len;
1474 int linenoiseHistorySetMaxLen(int len) {
1475 char **newHistory;
1477 if (len < 1) return 0;
1478 if (history) {
1479 int tocopy = history_len;
1481 newHistory = (char **)malloc(sizeof(char*)*len);
1482 if (newHistory == NULL) return 0;
1484 /* If we can't copy everything, free the elements we'll not use. */
1485 if (len < tocopy) {
1486 int j;
1488 for (j = 0; j < tocopy-len; j++) free(history[j]);
1489 tocopy = len;
1491 memset(newHistory,0,sizeof(char*)*len);
1492 memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
1493 free(history);
1494 history = newHistory;
1496 history_max_len = len;
1497 if (history_len > history_max_len)
1498 history_len = history_max_len;
1499 return 1;
1502 /* Save the history in the specified file. On success 0 is returned
1503 * otherwise -1 is returned. */
1504 int linenoiseHistorySave(const char *filename) {
1505 FILE *fp = fopen(filename,"w");
1506 int j;
1508 if (fp == NULL) return -1;
1509 for (j = 0; j < history_len; j++) {
1510 const char *str = history[j];
1511 /* Need to encode backslash, nl and cr */
1512 while (*str) {
1513 if (*str == '\\') {
1514 fputs("\\\\", fp);
1516 else if (*str == '\n') {
1517 fputs("\\n", fp);
1519 else if (*str == '\r') {
1520 fputs("\\r", fp);
1522 else {
1523 fputc(*str, fp);
1525 str++;
1527 fputc('\n', fp);
1530 fclose(fp);
1531 return 0;
1534 /* Load the history from the specified file. If the file does not exist
1535 * zero is returned and no operation is performed.
1537 * If the file exists and the operation succeeded 0 is returned, otherwise
1538 * on error -1 is returned. */
1539 int linenoiseHistoryLoad(const char *filename) {
1540 FILE *fp = fopen(filename,"r");
1541 char buf[LINENOISE_MAX_LINE];
1543 if (fp == NULL) return -1;
1545 while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1546 char *src, *dest;
1548 /* Decode backslash escaped values */
1549 for (src = dest = buf; *src; src++) {
1550 char ch = *src;
1552 if (ch == '\\') {
1553 src++;
1554 if (*src == 'n') {
1555 ch = '\n';
1557 else if (*src == 'r') {
1558 ch = '\r';
1559 } else {
1560 ch = *src;
1563 *dest++ = ch;
1565 /* Remove trailing newline */
1566 if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1567 dest--;
1569 *dest = 0;
1571 linenoiseHistoryAdd(buf);
1573 fclose(fp);
1574 return 0;
1577 /* Provide access to the history buffer.
1579 * If 'len' is not NULL, the length is stored in *len.
1581 char **linenoiseHistory(int *len) {
1582 if (len) {
1583 *len = history_len;
1585 return history;