aio: Fall back to stdio error if no ssl error
[jimtcl.git] / linenoise.c
blobcc0ca5327b156e9eff72dea285eb1e7a937e540c
1 #ifndef STRINGBUF_H
2 #define STRINGBUF_H
4 /* (c) 2017 Workware Systems Pty Ltd -- All Rights Reserved */
6 #ifdef __cplusplus
7 extern "C" {
8 #endif
10 /** @file
11 * A stringbuf is a resizing, null terminated string buffer.
13 * The buffer is reallocated as necessary.
15 * In general it is *not* OK to call these functions with a NULL pointer
16 * unless stated otherwise.
18 * If USE_UTF8 is defined, supports utf8.
21 /**
22 * The stringbuf structure should not be accessed directly.
23 * Use the functions below.
25 typedef struct {
26 int remaining; /**< Allocated, but unused space */
27 int last; /**< Index of the null terminator (and thus the length of the string) */
28 #ifdef USE_UTF8
29 int chars; /**< Count of characters */
30 #endif
31 char *data; /**< Allocated memory containing the string or NULL for empty */
32 } stringbuf;
34 /**
35 * Allocates and returns a new stringbuf with no elements.
37 stringbuf *sb_alloc(void);
39 /**
40 * Frees a stringbuf.
41 * It is OK to call this with NULL.
43 void sb_free(stringbuf *sb);
45 /**
46 * Returns an allocated copy of the stringbuf
48 stringbuf *sb_copy(stringbuf *sb);
50 /**
51 * Returns the length of the buffer.
53 * Returns 0 for both a NULL buffer and an empty buffer.
55 static inline int sb_len(stringbuf *sb) {
56 return sb->last;
59 /**
60 * Returns the utf8 character length of the buffer.
62 * Returns 0 for both a NULL buffer and an empty buffer.
64 static inline int sb_chars(stringbuf *sb) {
65 #ifdef USE_UTF8
66 return sb->chars;
67 #else
68 return sb->last;
69 #endif
72 /**
73 * Appends a null terminated string to the stringbuf
75 void sb_append(stringbuf *sb, const char *str);
77 /**
78 * Like sb_append() except does not require a null terminated string.
79 * The length of 'str' is given as 'len'
81 * Note that in utf8 mode, characters will *not* be counted correctly
82 * if a partial utf8 sequence is added with sb_append_len()
84 void sb_append_len(stringbuf *sb, const char *str, int len);
86 /**
87 * Returns a pointer to the null terminated string in the buffer.
89 * Note this pointer only remains valid until the next modification to the
90 * string buffer.
92 * The returned pointer can be used to update the buffer in-place
93 * as long as care is taken to not overwrite the end of the buffer.
95 static inline char *sb_str(const stringbuf *sb)
97 return sb->data;
101 * Inserts the given string *before* (zero-based) 'index' in the stringbuf.
102 * If index is past the end of the buffer, the string is appended,
103 * just like sb_append()
105 void sb_insert(stringbuf *sb, int index, const char *str);
108 * Delete 'len' bytes in the string at the given index.
110 * Any bytes past the end of the buffer are ignored.
111 * The buffer remains null terminated.
113 * If len is -1, deletes to the end of the buffer.
115 void sb_delete(stringbuf *sb, int index, int len);
118 * Clear to an empty buffer.
120 void sb_clear(stringbuf *sb);
123 * Return an allocated copy of buffer and frees 'sb'.
125 * If 'sb' is empty, returns an allocated copy of "".
127 char *sb_to_string(stringbuf *sb);
129 #ifdef __cplusplus
131 #endif
133 #endif
134 #include <stdlib.h>
135 #include <string.h>
136 #include <stdio.h>
137 #include <ctype.h>
138 #include <assert.h>
140 #ifndef STRINGBUF_H
141 #include "stringbuf.h"
142 #endif
143 #ifdef USE_UTF8
144 #include "utf8.h"
145 #endif
147 #define SB_INCREMENT 200
149 stringbuf *sb_alloc(void)
151 stringbuf *sb = (stringbuf *)malloc(sizeof(*sb));
152 sb->remaining = 0;
153 sb->last = 0;
154 #ifdef USE_UTF8
155 sb->chars = 0;
156 #endif
157 sb->data = NULL;
159 return(sb);
162 void sb_free(stringbuf *sb)
164 if (sb) {
165 free(sb->data);
167 free(sb);
170 void sb_realloc(stringbuf *sb, int newlen)
172 sb->data = (char *)realloc(sb->data, newlen);
173 sb->remaining = newlen - sb->last;
176 void sb_append(stringbuf *sb, const char *str)
178 sb_append_len(sb, str, strlen(str));
181 void sb_append_len(stringbuf *sb, const char *str, int len)
183 int utf8_strlen(const char *str, int bytelen);
184 if (sb->remaining < len + 1) {
185 sb_realloc(sb, sb->last + len + 1 + SB_INCREMENT);
187 memcpy(sb->data + sb->last, str, len);
188 sb->data[sb->last + len] = 0;
190 sb->last += len;
191 sb->remaining -= len;
192 #ifdef USE_UTF8
193 sb->chars += utf8_strlen(str, len);
194 #endif
197 char *sb_to_string(stringbuf *sb)
199 if (sb->data == NULL) {
200 /* Return an allocated empty string, not null */
201 return strdup("");
203 else {
204 /* Just return the data and free the stringbuf structure */
205 char *pt = sb->data;
206 free(sb);
207 return pt;
211 /* Insert and delete operations */
213 /* Moves up all the data at position 'pos' and beyond by 'len' bytes
214 * to make room for new data
216 * Note: Does *not* update sb->chars
218 static void sb_insert_space(stringbuf *sb, int pos, int len)
220 assert(pos <= sb->last);
222 /* Make sure there is enough space */
223 if (sb->remaining < len) {
224 sb_realloc(sb, sb->last + len + SB_INCREMENT);
226 /* Now move it up */
227 memmove(sb->data + pos + len, sb->data + pos, sb->last - pos);
228 sb->last += len;
229 sb->remaining -= len;
230 /* And null terminate */
231 sb->data[sb->last] = 0;
235 * Move down all the data from pos + len, effectively
236 * deleting the data at position 'pos' of length 'len'
238 static void sb_delete_space(stringbuf *sb, int pos, int len)
240 assert(pos < sb->last);
241 assert(pos + len <= sb->last);
243 #ifdef USE_UTF8
244 sb->chars -= utf8_strlen(sb->data + pos, len);
245 #endif
247 /* Now move it up */
248 memmove(sb->data + pos, sb->data + pos + len, sb->last - pos - len);
249 sb->last -= len;
250 sb->remaining += len;
251 /* And null terminate */
252 sb->data[sb->last] = 0;
255 void sb_insert(stringbuf *sb, int index, const char *str)
257 if (index >= sb->last) {
258 /* Inserting after the end of the list appends. */
259 sb_append(sb, str);
261 else {
262 int len = strlen(str);
264 sb_insert_space(sb, index, len);
265 memcpy(sb->data + index, str, len);
266 #ifdef USE_UTF8
267 sb->chars += utf8_strlen(str, len);
268 #endif
273 * Delete the bytes at index 'index' for length 'len'
274 * Has no effect if the index is past the end of the list.
276 void sb_delete(stringbuf *sb, int index, int len)
278 if (index < sb->last) {
279 char *pos = sb->data + index;
280 if (len < 0) {
281 len = sb->last;
284 sb_delete_space(sb, pos - sb->data, len);
288 void sb_clear(stringbuf *sb)
290 if (sb->data) {
291 /* Null terminate */
292 sb->data[0] = 0;
293 sb->last = 0;
294 #ifdef USE_UTF8
295 sb->chars = 0;
296 #endif
299 /* linenoise.c -- guerrilla line editing library against the idea that a
300 * line editing lib needs to be 20,000 lines of C code.
302 * You can find the latest source code at:
304 * http://github.com/msteveb/linenoise
305 * (forked from http://github.com/antirez/linenoise)
307 * Does a number of crazy assumptions that happen to be true in 99.9999% of
308 * the 2010 UNIX computers around.
310 * ------------------------------------------------------------------------
312 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
313 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
314 * Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
316 * All rights reserved.
318 * Redistribution and use in source and binary forms, with or without
319 * modification, are permitted provided that the following conditions are
320 * met:
322 * * Redistributions of source code must retain the above copyright
323 * notice, this list of conditions and the following disclaimer.
325 * * Redistributions in binary form must reproduce the above copyright
326 * notice, this list of conditions and the following disclaimer in the
327 * documentation and/or other materials provided with the distribution.
329 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
330 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
331 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
332 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
333 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
334 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
335 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
336 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
337 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
338 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
339 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
341 * ------------------------------------------------------------------------
343 * References:
344 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
345 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
347 * Bloat:
348 * - Completion?
350 * Unix/termios
351 * ------------
352 * List of escape sequences used by this program, we do everything just
353 * a few sequences. In order to be so cheap we may have some
354 * flickering effect with some slow terminal, but the lesser sequences
355 * the more compatible.
357 * EL (Erase Line)
358 * Sequence: ESC [ 0 K
359 * Effect: clear from cursor to end of line
361 * CUF (CUrsor Forward)
362 * Sequence: ESC [ n C
363 * Effect: moves cursor forward n chars
365 * CR (Carriage Return)
366 * Sequence: \r
367 * Effect: moves cursor to column 1
369 * The following are used to clear the screen: ESC [ H ESC [ 2 J
370 * This is actually composed of two sequences:
372 * cursorhome
373 * Sequence: ESC [ H
374 * Effect: moves the cursor to upper left corner
376 * ED2 (Clear entire screen)
377 * Sequence: ESC [ 2 J
378 * Effect: clear the whole screen
380 * == For highlighting control characters, we also use the following two ==
381 * SO (enter StandOut)
382 * Sequence: ESC [ 7 m
383 * Effect: Uses some standout mode such as reverse video
385 * SE (Standout End)
386 * Sequence: ESC [ 0 m
387 * Effect: Exit standout mode
389 * == Only used if TIOCGWINSZ fails ==
390 * DSR/CPR (Report cursor position)
391 * Sequence: ESC [ 6 n
392 * Effect: reports current cursor position as ESC [ NNN ; MMM R
394 * == Only used in multiline mode ==
395 * CUU (Cursor Up)
396 * Sequence: ESC [ n A
397 * Effect: moves cursor up n chars.
399 * CUD (Cursor Down)
400 * Sequence: ESC [ n B
401 * Effect: moves cursor down n chars.
403 * win32/console
404 * -------------
405 * If __MINGW32__ is defined, the win32 console API is used.
406 * This could probably be made to work for the msvc compiler too.
407 * This support based in part on work by Jon Griffiths.
410 #ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
411 #include <windows.h>
412 #include <fcntl.h>
413 #define USE_WINCONSOLE
414 #ifdef __MINGW32__
415 #define HAVE_UNISTD_H
416 #else
417 /* Microsoft headers don't like old POSIX names */
418 #define strdup _strdup
419 #define snprintf _snprintf
420 #endif
421 #else
422 #include <termios.h>
423 #include <sys/ioctl.h>
424 #include <poll.h>
425 #define USE_TERMIOS
426 #define HAVE_UNISTD_H
427 #endif
429 #ifdef HAVE_UNISTD_H
430 #include <unistd.h>
431 #endif
432 #include <stdlib.h>
433 #include <stdarg.h>
434 #include <stdio.h>
435 #include <assert.h>
436 #include <errno.h>
437 #include <string.h>
438 #include <signal.h>
439 #include <stdlib.h>
440 #include <sys/types.h>
442 #include "linenoise.h"
443 #ifndef STRINGBUF_H
444 #include "stringbuf.h"
445 #endif
446 #include "utf8.h"
448 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
450 #define ctrl(C) ((C) - '@')
452 /* Use -ve numbers here to co-exist with normal unicode chars */
453 enum {
454 SPECIAL_NONE,
455 /* don't use -1 here since that indicates error */
456 SPECIAL_UP = -20,
457 SPECIAL_DOWN = -21,
458 SPECIAL_LEFT = -22,
459 SPECIAL_RIGHT = -23,
460 SPECIAL_DELETE = -24,
461 SPECIAL_HOME = -25,
462 SPECIAL_END = -26,
463 SPECIAL_INSERT = -27,
464 SPECIAL_PAGE_UP = -28,
465 SPECIAL_PAGE_DOWN = -29,
467 /* Some handy names for other special keycodes */
468 CHAR_ESCAPE = 27,
469 CHAR_DELETE = 127,
472 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
473 static int history_len = 0;
474 static char **history = NULL;
476 /* Structure to contain the status of the current (being edited) line */
477 struct current {
478 stringbuf *buf; /* Current buffer. Always null terminated */
479 int pos; /* Cursor position, measured in chars */
480 int cols; /* Size of the window, in chars */
481 int nrows; /* How many rows are being used in multiline mode (>= 1) */
482 int rpos; /* The current row containing the cursor - multiline mode only */
483 const char *prompt;
484 stringbuf *capture; /* capture buffer, or NULL for none. Always null terminated */
485 stringbuf *output; /* used only during refreshLine() - output accumulator */
486 #if defined(USE_TERMIOS)
487 int fd; /* Terminal fd */
488 #elif defined(USE_WINCONSOLE)
489 HANDLE outh; /* Console output handle */
490 HANDLE inh; /* Console input handle */
491 int rows; /* Screen rows */
492 int x; /* Current column during output */
493 int y; /* Current row */
494 #ifdef USE_UTF8
495 #define UBUF_MAX_CHARS 132
496 WORD ubuf[UBUF_MAX_CHARS + 1]; /* Accumulates utf16 output - one extra for final surrogate pairs */
497 int ubuflen; /* length used in ubuf */
498 int ubufcols; /* how many columns are represented by the chars in ubuf? */
499 #endif
500 #endif
503 static int fd_read(struct current *current);
504 static int getWindowSize(struct current *current);
505 static void cursorDown(struct current *current, int n);
506 static void cursorUp(struct current *current, int n);
507 static void eraseEol(struct current *current);
508 static void refreshLine(struct current *current);
509 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos);
510 static void setCursorPos(struct current *current, int x);
511 static void setOutputHighlight(struct current *current, const int *props, int nprops);
512 static void set_current(struct current *current, const char *str);
514 void linenoiseHistoryFree(void) {
515 if (history) {
516 int j;
518 for (j = 0; j < history_len; j++)
519 free(history[j]);
520 free(history);
521 history = NULL;
522 history_len = 0;
526 struct esc_parser {
527 enum {
528 EP_START, /* looking for ESC */
529 EP_ESC, /* looking for [ */
530 EP_DIGITS, /* parsing digits */
531 EP_PROPS, /* parsing digits or semicolons */
532 EP_END, /* ok */
533 EP_ERROR, /* error */
534 } state;
535 int props[5]; /* properties are stored here */
536 int maxprops; /* size of the props[] array */
537 int numprops; /* number of properties found */
538 int termchar; /* terminator char, or 0 for any alpha */
539 int current; /* current (partial) property value */
543 * Initialise the escape sequence parser at *parser.
545 * If termchar is 0 any alpha char terminates ok. Otherwise only the given
546 * char terminates successfully.
547 * Run the parser state machine with calls to parseEscapeSequence() for each char.
549 static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
551 parser->state = EP_START;
552 parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
553 parser->numprops = 0;
554 parser->current = 0;
555 parser->termchar = termchar;
559 * Pass character 'ch' into the state machine to parse:
560 * 'ESC' '[' <digits> (';' <digits>)* <termchar>
562 * The first character must be ESC.
563 * Returns the current state. The state machine is done when it returns either EP_END
564 * or EP_ERROR.
566 * On EP_END, the "property/attribute" values can be read from parser->props[]
567 * of length parser->numprops.
569 static int parseEscapeSequence(struct esc_parser *parser, int ch)
571 switch (parser->state) {
572 case EP_START:
573 parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
574 break;
575 case EP_ESC:
576 parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
577 break;
578 case EP_PROPS:
579 if (ch == ';') {
580 parser->state = EP_DIGITS;
581 donedigits:
582 if (parser->numprops + 1 < parser->maxprops) {
583 parser->props[parser->numprops++] = parser->current;
584 parser->current = 0;
586 break;
588 /* fall through */
589 case EP_DIGITS:
590 if (ch >= '0' && ch <= '9') {
591 parser->current = parser->current * 10 + (ch - '0');
592 parser->state = EP_PROPS;
593 break;
595 /* must be terminator */
596 if (parser->termchar != ch) {
597 if (parser->termchar != 0 || !((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
598 parser->state = EP_ERROR;
599 break;
602 parser->state = EP_END;
603 goto donedigits;
604 case EP_END:
605 parser->state = EP_ERROR;
606 break;
607 case EP_ERROR:
608 break;
610 return parser->state;
613 /*#define DEBUG_REFRESHLINE*/
615 #ifdef DEBUG_REFRESHLINE
616 #define DRL(ARGS...) fprintf(dfh, ARGS)
617 static FILE *dfh;
619 static void DRL_CHAR(int ch)
621 if (ch < ' ') {
622 DRL("^%c", ch + '@');
624 else if (ch > 127) {
625 DRL("\\u%04x", ch);
627 else {
628 DRL("%c", ch);
631 static void DRL_STR(const char *str)
633 while (*str) {
634 int ch;
635 int n = utf8_tounicode(str, &ch);
636 str += n;
637 DRL_CHAR(ch);
640 #else
641 #define DRL(ARGS...)
642 #define DRL_CHAR(ch)
643 #define DRL_STR(str)
644 #endif
646 #if defined(USE_WINCONSOLE)
647 #include "linenoise-win32.c"
648 #endif
650 #if defined(USE_TERMIOS)
651 static void linenoiseAtExit(void);
652 static struct termios orig_termios; /* in order to restore at exit */
653 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
654 static int atexit_registered = 0; /* register atexit just 1 time */
656 static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
658 static int isUnsupportedTerm(void) {
659 char *term = getenv("TERM");
661 if (term) {
662 int j;
663 for (j = 0; unsupported_term[j]; j++) {
664 if (strcmp(term, unsupported_term[j]) == 0) {
665 return 1;
669 return 0;
672 static int enableRawMode(struct current *current) {
673 struct termios raw;
675 current->fd = STDIN_FILENO;
676 current->cols = 0;
678 if (!isatty(current->fd) || isUnsupportedTerm() ||
679 tcgetattr(current->fd, &orig_termios) == -1) {
680 fatal:
681 errno = ENOTTY;
682 return -1;
685 if (!atexit_registered) {
686 atexit(linenoiseAtExit);
687 atexit_registered = 1;
690 raw = orig_termios; /* modify the original mode */
691 /* input modes: no break, no CR to NL, no parity check, no strip char,
692 * no start/stop output control. */
693 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
694 /* output modes - actually, no need to disable post processing */
695 /*raw.c_oflag &= ~(OPOST);*/
696 /* control modes - set 8 bit chars */
697 raw.c_cflag |= (CS8);
698 /* local modes - choing off, canonical off, no extended functions,
699 * no signal chars (^Z,^C) */
700 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
701 /* control chars - set return condition: min number of bytes and timer.
702 * We want read to return every single byte, without timeout. */
703 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
705 /* put terminal in raw mode after flushing */
706 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
707 goto fatal;
709 rawmode = 1;
710 return 0;
713 static void disableRawMode(struct current *current) {
714 /* Don't even check the return value as it's too late. */
715 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
716 rawmode = 0;
719 /* At exit we'll try to fix the terminal to the initial conditions. */
720 static void linenoiseAtExit(void) {
721 if (rawmode) {
722 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
724 linenoiseHistoryFree();
727 /* gcc/glibc insists that we care about the return code of write!
728 * Clarification: This means that a void-cast like "(void) (EXPR)"
729 * does not work.
731 #define IGNORE_RC(EXPR) if (EXPR) {}
734 * Output bytes directly, or accumulate output (if current->output is set)
736 static void outputChars(struct current *current, const char *buf, int len)
738 if (len < 0) {
739 len = strlen(buf);
741 if (current->output) {
742 sb_append_len(current->output, buf, len);
744 else {
745 IGNORE_RC(write(current->fd, buf, len));
749 /* Like outputChars, but using printf-style formatting
751 static void outputFormatted(struct current *current, const char *format, ...)
753 va_list args;
754 char buf[64];
755 int n;
757 va_start(args, format);
758 n = vsnprintf(buf, sizeof(buf), format, args);
759 /* This will never happen because we are sure to use outputFormatted() only for short sequences */
760 assert(n < (int)sizeof(buf));
761 va_end(args);
762 outputChars(current, buf, n);
765 static void cursorToLeft(struct current *current)
767 outputChars(current, "\r", -1);
770 static void setOutputHighlight(struct current *current, const int *props, int nprops)
772 outputChars(current, "\x1b[", -1);
773 while (nprops--) {
774 outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
775 props++;
779 static void eraseEol(struct current *current)
781 outputChars(current, "\x1b[0K", -1);
784 static void setCursorPos(struct current *current, int x)
786 if (x == 0) {
787 cursorToLeft(current);
789 else {
790 outputFormatted(current, "\r\x1b[%dC", x);
794 static void cursorUp(struct current *current, int n)
796 if (n) {
797 outputFormatted(current, "\x1b[%dA", n);
801 static void cursorDown(struct current *current, int n)
803 if (n) {
804 outputFormatted(current, "\x1b[%dB", n);
808 void linenoiseClearScreen(void)
810 write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7);
814 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
816 * A timeout of -1 means to wait forever.
818 * Returns -1 if no char is received within the time or an error occurs.
820 static int fd_read_char(int fd, int timeout)
822 struct pollfd p;
823 unsigned char c;
825 p.fd = fd;
826 p.events = POLLIN;
828 if (poll(&p, 1, timeout) == 0) {
829 /* timeout */
830 return -1;
832 if (read(fd, &c, 1) != 1) {
833 return -1;
835 return c;
839 * Reads a complete utf-8 character
840 * and returns the unicode value, or -1 on error.
842 static int fd_read(struct current *current)
844 #ifdef USE_UTF8
845 char buf[MAX_UTF8_LEN];
846 int n;
847 int i;
848 int c;
850 if (read(current->fd, &buf[0], 1) != 1) {
851 return -1;
853 n = utf8_charlen(buf[0]);
854 if (n < 1) {
855 return -1;
857 for (i = 1; i < n; i++) {
858 if (read(current->fd, &buf[i], 1) != 1) {
859 return -1;
862 /* decode and return the character */
863 utf8_tounicode(buf, &c);
864 return c;
865 #else
866 return fd_read_char(current->fd, -1);
867 #endif
872 * Stores the current cursor column in '*cols'.
873 * Returns 1 if OK, or 0 if failed to determine cursor pos.
875 static int queryCursor(struct current *current, int* cols)
877 struct esc_parser parser;
878 int ch;
880 /* Should not be buffering this output, it needs to go immediately */
881 assert(current->output == NULL);
883 /* control sequence - report cursor location */
884 outputChars(current, "\x1b[6n", -1);
886 /* Parse the response: ESC [ rows ; cols R */
887 initParseEscapeSeq(&parser, 'R');
888 while ((ch = fd_read_char(current->fd, 100)) > 0) {
889 switch (parseEscapeSequence(&parser, ch)) {
890 default:
891 continue;
892 case EP_END:
893 if (parser.numprops == 2 && parser.props[1] < 1000) {
894 *cols = parser.props[1];
895 return 1;
897 break;
898 case EP_ERROR:
899 break;
901 /* failed */
902 break;
904 return 0;
908 * Updates current->cols with the current window size (width)
910 static int getWindowSize(struct current *current)
912 struct winsize ws;
914 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
915 current->cols = ws.ws_col;
916 return 0;
919 /* Failed to query the window size. Perhaps we are on a serial terminal.
920 * Try to query the width by sending the cursor as far to the right
921 * and reading back the cursor position.
922 * Note that this is only done once per call to linenoise rather than
923 * every time the line is refreshed for efficiency reasons.
925 * In more detail, we:
926 * (a) request current cursor position,
927 * (b) move cursor far right,
928 * (c) request cursor position again,
929 * (d) at last move back to the old position.
930 * This gives us the width without messing with the externally
931 * visible cursor position.
934 if (current->cols == 0) {
935 int here;
937 /* If anything fails => default 80 */
938 current->cols = 80;
940 /* (a) */
941 if (queryCursor (current, &here)) {
942 /* (b) */
943 setCursorPos(current, 999);
945 /* (c). Note: If (a) succeeded, then (c) should as well.
946 * For paranoia we still check and have a fallback action
947 * for (d) in case of failure..
949 if (queryCursor (current, &current->cols)) {
950 /* (d) Reset the cursor back to the original location. */
951 if (current->cols > here) {
952 setCursorPos(current, here);
958 return 0;
962 * If CHAR_ESCAPE was received, reads subsequent
963 * chars to determine if this is a known special key.
965 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
967 * If no additional char is received within a short time,
968 * CHAR_ESCAPE is returned.
970 static int check_special(int fd)
972 int c = fd_read_char(fd, 50);
973 int c2;
975 if (c < 0) {
976 return CHAR_ESCAPE;
979 c2 = fd_read_char(fd, 50);
980 if (c2 < 0) {
981 return c2;
983 if (c == '[' || c == 'O') {
984 /* Potential arrow key */
985 switch (c2) {
986 case 'A':
987 return SPECIAL_UP;
988 case 'B':
989 return SPECIAL_DOWN;
990 case 'C':
991 return SPECIAL_RIGHT;
992 case 'D':
993 return SPECIAL_LEFT;
994 case 'F':
995 return SPECIAL_END;
996 case 'H':
997 return SPECIAL_HOME;
1000 if (c == '[' && c2 >= '1' && c2 <= '8') {
1001 /* extended escape */
1002 c = fd_read_char(fd, 50);
1003 if (c == '~') {
1004 switch (c2) {
1005 case '2':
1006 return SPECIAL_INSERT;
1007 case '3':
1008 return SPECIAL_DELETE;
1009 case '5':
1010 return SPECIAL_PAGE_UP;
1011 case '6':
1012 return SPECIAL_PAGE_DOWN;
1013 case '7':
1014 return SPECIAL_HOME;
1015 case '8':
1016 return SPECIAL_END;
1019 while (c != -1 && c != '~') {
1020 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
1021 c = fd_read_char(fd, 50);
1025 return SPECIAL_NONE;
1027 #endif
1029 static void clearOutputHighlight(struct current *current)
1031 int nohighlight = 0;
1032 setOutputHighlight(current, &nohighlight, 1);
1035 static void outputControlChar(struct current *current, char ch)
1037 int reverse = 7;
1038 setOutputHighlight(current, &reverse, 1);
1039 outputChars(current, "^", 1);
1040 outputChars(current, &ch, 1);
1041 clearOutputHighlight(current);
1044 #ifndef utf8_getchars
1045 static int utf8_getchars(char *buf, int c)
1047 #ifdef USE_UTF8
1048 return utf8_fromunicode(buf, c);
1049 #else
1050 *buf = c;
1051 return 1;
1052 #endif
1054 #endif
1057 * Returns the unicode character at the given offset,
1058 * or -1 if none.
1060 static int get_char(struct current *current, int pos)
1062 if (pos >= 0 && pos < sb_chars(current->buf)) {
1063 int c;
1064 int i = utf8_index(sb_str(current->buf), pos);
1065 (void)utf8_tounicode(sb_str(current->buf) + i, &c);
1066 return c;
1068 return -1;
1071 static int char_display_width(int ch)
1073 if (ch < ' ') {
1074 /* control chars take two positions */
1075 return 2;
1077 else {
1078 return utf8_width(ch);
1082 #ifndef NO_COMPLETION
1083 static linenoiseCompletionCallback *completionCallback = NULL;
1084 static void *completionUserdata = NULL;
1085 static int showhints = 1;
1086 static linenoiseHintsCallback *hintsCallback = NULL;
1087 static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
1088 static void *hintsUserdata = NULL;
1090 static void beep() {
1091 #ifdef USE_TERMIOS
1092 fprintf(stderr, "\x7");
1093 fflush(stderr);
1094 #endif
1097 static void freeCompletions(linenoiseCompletions *lc) {
1098 size_t i;
1099 for (i = 0; i < lc->len; i++)
1100 free(lc->cvec[i]);
1101 free(lc->cvec);
1104 static int completeLine(struct current *current) {
1105 linenoiseCompletions lc = { 0, NULL };
1106 int c = 0;
1108 completionCallback(sb_str(current->buf),&lc,completionUserdata);
1109 if (lc.len == 0) {
1110 beep();
1111 } else {
1112 size_t stop = 0, i = 0;
1114 while(!stop) {
1115 /* Show completion or original buffer */
1116 if (i < lc.len) {
1117 int chars = utf8_strlen(lc.cvec[i], -1);
1118 refreshLineAlt(current, current->prompt, lc.cvec[i], chars);
1119 } else {
1120 refreshLine(current);
1123 c = fd_read(current);
1124 if (c == -1) {
1125 break;
1128 switch(c) {
1129 case '\t': /* tab */
1130 i = (i+1) % (lc.len+1);
1131 if (i == lc.len) beep();
1132 break;
1133 case CHAR_ESCAPE: /* escape */
1134 /* Re-show original buffer */
1135 if (i < lc.len) {
1136 refreshLine(current);
1138 stop = 1;
1139 break;
1140 default:
1141 /* Update buffer and return */
1142 if (i < lc.len) {
1143 set_current(current,lc.cvec[i]);
1145 stop = 1;
1146 break;
1151 freeCompletions(&lc);
1152 return c; /* Return last read character */
1155 /* Register a callback function to be called for tab-completion.
1156 Returns the prior callback so that the caller may (if needed)
1157 restore it when done. */
1158 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
1159 linenoiseCompletionCallback * old = completionCallback;
1160 completionCallback = fn;
1161 completionUserdata = userdata;
1162 return old;
1165 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1166 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1167 lc->cvec[lc->len++] = strdup(str);
1170 void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
1172 hintsCallback = callback;
1173 hintsUserdata = userdata;
1176 void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
1178 freeHintsCallback = callback;
1181 #endif
1184 static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
1186 /* We have availcols columns available.
1187 * If necessary, strip chars off the front of buf until *cursor_pos
1188 * fits within availcols
1190 int needcols = 0;
1191 int pos = 0;
1192 int new_cursor_pos = *cursor_pos;
1193 const char *pt = buf;
1195 DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);
1197 while (*pt) {
1198 int ch;
1199 int n = utf8_tounicode(pt, &ch);
1200 pt += n;
1202 needcols += char_display_width(ch);
1204 /* If we need too many cols, strip
1205 * chars off the front of buf to make it fit.
1206 * We keep 3 extra cols to the right of the cursor.
1207 * 2 for possible wide chars, 1 for the last column that
1208 * can't be used.
1210 while (needcols >= availcols - 3) {
1211 n = utf8_tounicode(buf, &ch);
1212 buf += n;
1213 needcols -= char_display_width(ch);
1214 DRL_CHAR(ch);
1216 /* and adjust the apparent cursor position */
1217 new_cursor_pos--;
1219 if (buf == pt) {
1220 /* can't remove more than this */
1221 break;
1225 if (pos++ == *cursor_pos) {
1226 break;
1230 DRL("<snip>");
1231 DRL_STR(buf);
1232 DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);
1234 /* Done, now new_cursor_pos contains the adjusted cursor position
1235 * and buf points to he adjusted start
1237 *cursor_pos = new_cursor_pos;
1238 return buf;
1241 static int mlmode = 0;
1243 void linenoiseSetMultiLine(int enableml)
1245 mlmode = enableml;
1248 /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
1249 * to the right of the prompt. */
1250 static void refreshShowHints(struct current *current, const char *buf, int availcols) {
1251 if (showhints && hintsCallback && availcols > 0) {
1252 int bold = 0;
1253 int color = -1;
1254 char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
1255 if (hint) {
1256 const char *pt;
1257 if (bold == 1 && color == -1) color = 37;
1258 if (bold || color > 0) {
1259 int props[3] = { bold, color, 49 }; /* bold, color, fgnormal */
1260 setOutputHighlight(current, props, 3);
1262 DRL("<hint bold=%d,color=%d>", bold, color);
1263 pt = hint;
1264 while (*pt) {
1265 int ch;
1266 int n = utf8_tounicode(pt, &ch);
1267 int width = char_display_width(ch);
1269 if (width >= availcols) {
1270 DRL("<hinteol>");
1271 break;
1273 DRL_CHAR(ch);
1275 availcols -= width;
1276 outputChars(current, pt, n);
1277 pt += n;
1279 if (bold || color > 0) {
1280 clearOutputHighlight(current);
1282 /* Call the function to free the hint returned. */
1283 if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
1288 #ifdef USE_TERMIOS
1289 static void refreshStart(struct current *current)
1291 /* We accumulate all output here */
1292 assert(current->output == NULL);
1293 current->output = sb_alloc();
1296 static void refreshEnd(struct current *current)
1298 /* Output everything at once */
1299 IGNORE_RC(write(current->fd, sb_str(current->output), sb_len(current->output)));
1300 sb_free(current->output);
1301 current->output = NULL;
1304 static void refreshStartChars(struct current *current)
1308 static void refreshNewline(struct current *current)
1310 DRL("<nl>");
1311 outputChars(current, "\n", 1);
1314 static void refreshEndChars(struct current *current)
1317 #endif
1319 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
1321 int i;
1322 const char *pt;
1323 int displaycol;
1324 int displayrow;
1325 int visible;
1326 int currentpos;
1327 int notecursor;
1328 int cursorcol = 0;
1329 int cursorrow = 0;
1330 struct esc_parser parser;
1332 #ifdef DEBUG_REFRESHLINE
1333 dfh = fopen("linenoise.debuglog", "a");
1334 #endif
1336 /* Should intercept SIGWINCH. For now, just get the size every time */
1337 getWindowSize(current);
1339 refreshStart(current);
1341 DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);
1343 /* Here is the plan:
1344 * (a) move the the bottom row, going down the appropriate number of lines
1345 * (b) move to beginning of line and erase the current line
1346 * (c) go up one line and do the same, until we have erased up to the first row
1347 * (d) output the prompt, counting cols and rows, taking into account escape sequences
1348 * (e) output the buffer, counting cols and rows
1349 * (e') when we hit the current pos, save the cursor position
1350 * (f) move the cursor to the saved cursor position
1351 * (g) save the current cursor row and number of rows
1354 /* (a) - The cursor is currently at row rpos */
1355 cursorDown(current, current->nrows - current->rpos - 1);
1356 DRL("<cud=%d>", current->nrows - current->rpos - 1);
1358 /* (b), (c) - Erase lines upwards until we get to the first row */
1359 for (i = 0; i < current->nrows; i++) {
1360 if (i) {
1361 DRL("<cup>");
1362 cursorUp(current, 1);
1364 DRL("<clearline>");
1365 cursorToLeft(current);
1366 eraseEol(current);
1368 DRL("\n");
1370 /* (d) First output the prompt. control sequences don't take up display space */
1371 pt = prompt;
1372 displaycol = 0; /* current display column */
1373 displayrow = 0; /* current display row */
1374 visible = 1;
1376 refreshStartChars(current);
1378 while (*pt) {
1379 int width;
1380 int ch;
1381 int n = utf8_tounicode(pt, &ch);
1383 if (visible && ch == CHAR_ESCAPE) {
1384 /* The start of an escape sequence, so not visible */
1385 visible = 0;
1386 initParseEscapeSeq(&parser, 'm');
1387 DRL("<esc-seq-start>");
1390 if (ch == '\n' || ch == '\r') {
1391 /* treat both CR and NL the same and force wrap */
1392 refreshNewline(current);
1393 displaycol = 0;
1394 displayrow++;
1396 else {
1397 width = visible * utf8_width(ch);
1399 displaycol += width;
1400 if (displaycol >= current->cols) {
1401 /* need to wrap to the next line because of newline or if it doesn't fit
1402 * XXX this is a problem in single line mode
1404 refreshNewline(current);
1405 displaycol = width;
1406 displayrow++;
1409 DRL_CHAR(ch);
1410 #ifdef USE_WINCONSOLE
1411 if (visible) {
1412 outputChars(current, pt, n);
1414 #else
1415 outputChars(current, pt, n);
1416 #endif
1418 pt += n;
1420 if (!visible) {
1421 switch (parseEscapeSequence(&parser, ch)) {
1422 case EP_END:
1423 visible = 1;
1424 setOutputHighlight(current, parser.props, parser.numprops);
1425 DRL("<esc-seq-end,numprops=%d>", parser.numprops);
1426 break;
1427 case EP_ERROR:
1428 DRL("<esc-seq-err>");
1429 visible = 1;
1430 break;
1435 /* Now we are at the first line with all lines erased */
1436 DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);
1439 /* (e) output the buffer, counting cols and rows */
1440 if (mlmode == 0) {
1441 /* In this mode we may need to trim chars from the start of the buffer until the
1442 * cursor fits in the window.
1444 pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
1446 else {
1447 pt = buf;
1450 currentpos = 0;
1451 notecursor = -1;
1453 while (*pt) {
1454 int ch;
1455 int n = utf8_tounicode(pt, &ch);
1456 int width = char_display_width(ch);
1458 if (currentpos == cursor_pos) {
1459 /* (e') wherever we output this character is where we want the cursor */
1460 notecursor = 1;
1463 if (displaycol + width >= current->cols) {
1464 if (mlmode == 0) {
1465 /* In single line mode stop once we print as much as we can on one line */
1466 DRL("<slmode>");
1467 break;
1469 /* need to wrap to the next line since it doesn't fit */
1470 refreshNewline(current);
1471 displaycol = 0;
1472 displayrow++;
1475 if (notecursor == 1) {
1476 /* (e') Save this position as the current cursor position */
1477 cursorcol = displaycol;
1478 cursorrow = displayrow;
1479 notecursor = 0;
1480 DRL("<cursor>");
1483 displaycol += width;
1485 if (ch < ' ') {
1486 outputControlChar(current, ch + '@');
1488 else {
1489 outputChars(current, pt, n);
1491 DRL_CHAR(ch);
1492 if (width != 1) {
1493 DRL("<w=%d>", width);
1496 pt += n;
1497 currentpos++;
1500 /* If we didn't see the cursor, it is at the current location */
1501 if (notecursor) {
1502 DRL("<cursor>");
1503 cursorcol = displaycol;
1504 cursorrow = displayrow;
1507 DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n\n", displaycol, displayrow, cursorcol, cursorrow);
1509 /* (f) show hints */
1510 refreshShowHints(current, buf, current->cols - displaycol);
1512 refreshEndChars(current);
1514 /* (g) move the cursor to the correct place */
1515 cursorUp(current, displayrow - cursorrow);
1516 setCursorPos(current, cursorcol);
1518 /* (h) Update the number of rows if larger, but never reduce this */
1519 if (displayrow >= current->nrows) {
1520 current->nrows = displayrow + 1;
1522 /* And remember the row that the cursor is on */
1523 current->rpos = cursorrow;
1525 refreshEnd(current);
1527 #ifdef DEBUG_REFRESHLINE
1528 fclose(dfh);
1529 #endif
1532 static void refreshLine(struct current *current)
1534 refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
1537 static void set_current(struct current *current, const char *str)
1539 sb_clear(current->buf);
1540 sb_append(current->buf, str);
1541 current->pos = sb_chars(current->buf);
1545 * Removes the char at 'pos'.
1547 * Returns 1 if the line needs to be refreshed, 2 if not
1548 * and 0 if nothing was removed
1550 static int remove_char(struct current *current, int pos)
1552 if (pos >= 0 && pos < sb_chars(current->buf)) {
1553 int offset = utf8_index(sb_str(current->buf), pos);
1554 int nbytes = utf8_index(sb_str(current->buf) + offset, 1);
1556 /* Note that we no longer try to optimise the remove-at-end case
1557 * since control characters and wide characters mess
1558 * up the simple count
1560 sb_delete(current->buf, offset, nbytes);
1562 if (current->pos > pos) {
1563 current->pos--;
1565 return 1;
1567 return 0;
1571 * Insert 'ch' at position 'pos'
1573 * Returns 1 if the line needs to be refreshed, 2 if not
1574 * and 0 if nothing was inserted (no room)
1576 static int insert_char(struct current *current, int pos, int ch)
1578 if (pos >= 0 && pos <= sb_chars(current->buf)) {
1579 char buf[MAX_UTF8_LEN + 1];
1580 int offset = utf8_index(sb_str(current->buf), pos);
1581 int n = utf8_getchars(buf, ch);
1583 /* null terminate since sb_insert() requires it */
1584 buf[n] = 0;
1586 /* Optimisation removed - see reason in remove_char() */
1588 sb_insert(current->buf, offset, buf);
1589 if (current->pos >= pos) {
1590 current->pos++;
1592 return 1;
1594 return 0;
1598 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
1600 * This replaces any existing characters in the cut buffer.
1602 static void capture_chars(struct current *current, int pos, int nchars)
1604 if (pos >= 0 && (pos + nchars - 1) < sb_chars(current->buf)) {
1605 int offset = utf8_index(sb_str(current->buf), pos);
1606 int nbytes = utf8_index(sb_str(current->buf) + offset, nchars);
1608 if (nbytes) {
1609 if (current->capture) {
1610 sb_clear(current->capture);
1612 else {
1613 current->capture = sb_alloc();
1615 sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
1621 * Removes up to 'n' characters at cursor position 'pos'.
1623 * Returns 0 if no chars were removed or non-zero otherwise.
1625 static int remove_chars(struct current *current, int pos, int n)
1627 int removed = 0;
1629 /* First save any chars which will be removed */
1630 capture_chars(current, pos, n);
1632 while (n-- && remove_char(current, pos)) {
1633 removed++;
1635 return removed;
1638 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1640 * Returns 0 if no chars were inserted or non-zero otherwise.
1642 static int insert_chars(struct current *current, int pos, const char *chars)
1644 int inserted = 0;
1646 while (*chars) {
1647 int ch;
1648 int n = utf8_tounicode(chars, &ch);
1649 if (insert_char(current, pos, ch) == 0) {
1650 break;
1652 inserted++;
1653 pos++;
1654 chars += n;
1656 return inserted;
1660 * Returns the keycode to process, or 0 if none.
1662 static int reverseIncrementalSearch(struct current *current)
1664 /* Display the reverse-i-search prompt and process chars */
1665 char rbuf[50];
1666 char rprompt[80];
1667 int rchars = 0;
1668 int rlen = 0;
1669 int searchpos = history_len - 1;
1670 int c;
1672 rbuf[0] = 0;
1673 while (1) {
1674 int n = 0;
1675 const char *p = NULL;
1676 int skipsame = 0;
1677 int searchdir = -1;
1679 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1680 refreshLineAlt(current, rprompt, sb_str(current->buf), current->pos);
1681 c = fd_read(current);
1682 if (c == ctrl('H') || c == CHAR_DELETE) {
1683 if (rchars) {
1684 int p = utf8_index(rbuf, --rchars);
1685 rbuf[p] = 0;
1686 rlen = strlen(rbuf);
1688 continue;
1690 #ifdef USE_TERMIOS
1691 if (c == CHAR_ESCAPE) {
1692 c = check_special(current->fd);
1694 #endif
1695 if (c == ctrl('P') || c == SPECIAL_UP) {
1696 /* Search for the previous (earlier) match */
1697 if (searchpos > 0) {
1698 searchpos--;
1700 skipsame = 1;
1702 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1703 /* Search for the next (later) match */
1704 if (searchpos < history_len) {
1705 searchpos++;
1707 searchdir = 1;
1708 skipsame = 1;
1710 else if (c >= ' ') {
1711 /* >= here to allow for null terminator */
1712 if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
1713 continue;
1716 n = utf8_getchars(rbuf + rlen, c);
1717 rlen += n;
1718 rchars++;
1719 rbuf[rlen] = 0;
1721 /* Adding a new char resets the search location */
1722 searchpos = history_len - 1;
1724 else {
1725 /* Exit from incremental search mode */
1726 break;
1729 /* Now search through the history for a match */
1730 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1731 p = strstr(history[searchpos], rbuf);
1732 if (p) {
1733 /* Found a match */
1734 if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
1735 /* But it is identical, so skip it */
1736 continue;
1738 /* Copy the matching line and set the cursor position */
1739 set_current(current,history[searchpos]);
1740 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1741 break;
1744 if (!p && n) {
1745 /* No match, so don't add it */
1746 rchars--;
1747 rlen -= n;
1748 rbuf[rlen] = 0;
1751 if (c == ctrl('G') || c == ctrl('C')) {
1752 /* ctrl-g terminates the search with no effect */
1753 set_current(current, "");
1754 c = 0;
1756 else if (c == ctrl('J')) {
1757 /* ctrl-j terminates the search leaving the buffer in place */
1758 c = 0;
1761 /* Go process the char normally */
1762 refreshLine(current);
1763 return c;
1766 static int linenoiseEdit(struct current *current) {
1767 int history_index = 0;
1769 /* The latest history entry is always our current buffer, that
1770 * initially is just an empty string. */
1771 linenoiseHistoryAdd("");
1773 set_current(current, "");
1774 refreshLine(current);
1776 while(1) {
1777 int dir = -1;
1778 int c = fd_read(current);
1780 #ifndef NO_COMPLETION
1781 /* Only autocomplete when the callback is set. It returns < 0 when
1782 * there was an error reading from fd. Otherwise it will return the
1783 * character that should be handled next. */
1784 if (c == '\t' && current->pos == sb_chars(current->buf) && completionCallback != NULL) {
1785 c = completeLine(current);
1787 #endif
1788 if (c == ctrl('R')) {
1789 /* reverse incremental search will provide an alternative keycode or 0 for none */
1790 c = reverseIncrementalSearch(current);
1791 /* go on to process the returned char normally */
1794 #ifdef USE_TERMIOS
1795 if (c == CHAR_ESCAPE) { /* escape sequence */
1796 c = check_special(current->fd);
1798 #endif
1799 if (c == -1) {
1800 /* Return on errors */
1801 return sb_len(current->buf);
1804 switch(c) {
1805 case SPECIAL_NONE:
1806 break;
1807 case '\r': /* enter */
1808 history_len--;
1809 free(history[history_len]);
1810 current->pos = sb_chars(current->buf);
1811 if (mlmode || hintsCallback) {
1812 showhints = 0;
1813 refreshLine(current);
1814 showhints = 1;
1816 return sb_len(current->buf);
1817 case ctrl('C'): /* ctrl-c */
1818 errno = EAGAIN;
1819 return -1;
1820 case ctrl('Z'): /* ctrl-z */
1821 #ifdef SIGTSTP
1822 /* send ourselves SIGSUSP */
1823 disableRawMode(current);
1824 raise(SIGTSTP);
1825 /* and resume */
1826 enableRawMode(current);
1827 refreshLine(current);
1828 #endif
1829 continue;
1830 case CHAR_DELETE: /* backspace */
1831 case ctrl('H'):
1832 if (remove_char(current, current->pos - 1) == 1) {
1833 refreshLine(current);
1835 break;
1836 case ctrl('D'): /* ctrl-d */
1837 if (sb_len(current->buf) == 0) {
1838 /* Empty line, so EOF */
1839 history_len--;
1840 free(history[history_len]);
1841 return -1;
1843 /* Otherwise fall through to delete char to right of cursor */
1844 case SPECIAL_DELETE:
1845 if (remove_char(current, current->pos) == 1) {
1846 refreshLine(current);
1848 break;
1849 case SPECIAL_INSERT:
1850 /* Ignore. Expansion Hook.
1851 * Future possibility: Toggle Insert/Overwrite Modes
1853 break;
1854 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1855 /* eat any spaces on the left */
1857 int pos = current->pos;
1858 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1859 pos--;
1862 /* now eat any non-spaces on the left */
1863 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1864 pos--;
1867 if (remove_chars(current, pos, current->pos - pos)) {
1868 refreshLine(current);
1871 break;
1872 case ctrl('T'): /* ctrl-t */
1873 if (current->pos > 0 && current->pos <= sb_chars(current->buf)) {
1874 /* If cursor is at end, transpose the previous two chars */
1875 int fixer = (current->pos == sb_chars(current->buf));
1876 c = get_char(current, current->pos - fixer);
1877 remove_char(current, current->pos - fixer);
1878 insert_char(current, current->pos - 1, c);
1879 refreshLine(current);
1881 break;
1882 case ctrl('V'): /* ctrl-v */
1883 /* Insert the ^V first */
1884 if (insert_char(current, current->pos, c)) {
1885 refreshLine(current);
1886 /* Now wait for the next char. Can insert anything except \0 */
1887 c = fd_read(current);
1889 /* Remove the ^V first */
1890 remove_char(current, current->pos - 1);
1891 if (c > 0) {
1892 /* Insert the actual char, can't be error or null */
1893 insert_char(current, current->pos, c);
1895 refreshLine(current);
1897 break;
1898 case ctrl('B'):
1899 case SPECIAL_LEFT:
1900 if (current->pos > 0) {
1901 current->pos--;
1902 refreshLine(current);
1904 break;
1905 case ctrl('F'):
1906 case SPECIAL_RIGHT:
1907 if (current->pos < sb_chars(current->buf)) {
1908 current->pos++;
1909 refreshLine(current);
1911 break;
1912 case SPECIAL_PAGE_UP:
1913 dir = history_len - history_index - 1; /* move to start of history */
1914 goto history_navigation;
1915 case SPECIAL_PAGE_DOWN:
1916 dir = -history_index; /* move to 0 == end of history, i.e. current */
1917 goto history_navigation;
1918 case ctrl('P'):
1919 case SPECIAL_UP:
1920 dir = 1;
1921 goto history_navigation;
1922 case ctrl('N'):
1923 case SPECIAL_DOWN:
1924 history_navigation:
1925 if (history_len > 1) {
1926 /* Update the current history entry before to
1927 * overwrite it with tne next one. */
1928 free(history[history_len - 1 - history_index]);
1929 history[history_len - 1 - history_index] = strdup(sb_str(current->buf));
1930 /* Show the new entry */
1931 history_index += dir;
1932 if (history_index < 0) {
1933 history_index = 0;
1934 break;
1935 } else if (history_index >= history_len) {
1936 history_index = history_len - 1;
1937 break;
1939 set_current(current, history[history_len - 1 - history_index]);
1940 refreshLine(current);
1942 break;
1943 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1944 case SPECIAL_HOME:
1945 current->pos = 0;
1946 refreshLine(current);
1947 break;
1948 case ctrl('E'): /* ctrl+e, go to the end of the line */
1949 case SPECIAL_END:
1950 current->pos = sb_chars(current->buf);
1951 refreshLine(current);
1952 break;
1953 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1954 if (remove_chars(current, 0, current->pos)) {
1955 refreshLine(current);
1957 break;
1958 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1959 if (remove_chars(current, current->pos, sb_chars(current->buf) - current->pos)) {
1960 refreshLine(current);
1962 break;
1963 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1964 if (current->capture && insert_chars(current, current->pos, sb_str(current->capture))) {
1965 refreshLine(current);
1967 break;
1968 case ctrl('L'): /* Ctrl+L, clear screen */
1969 linenoiseClearScreen();
1970 /* Force recalc of window size for serial terminals */
1971 current->cols = 0;
1972 current->rpos = 0;
1973 refreshLine(current);
1974 break;
1975 default:
1976 /* Only tab is allowed without ^V */
1977 if (c == '\t' || c >= ' ') {
1978 if (insert_char(current, current->pos, c) == 1) {
1979 refreshLine(current);
1982 break;
1985 return sb_len(current->buf);
1988 int linenoiseColumns(void)
1990 struct current current;
1991 enableRawMode (&current);
1992 getWindowSize (&current);
1993 disableRawMode (&current);
1994 return current.cols;
1998 * Reads a line from the file handle (without the trailing NL or CRNL)
1999 * and returns it in a stringbuf.
2000 * Returns NULL if no characters are read before EOF or error.
2002 * Note that the character count will *not* be correct for lines containing
2003 * utf8 sequences. Do not rely on the character count.
2005 static stringbuf *sb_getline(FILE *fh)
2007 stringbuf *sb = sb_alloc();
2008 int c;
2009 int n = 0;
2011 while ((c = getc(fh)) != EOF) {
2012 char ch;
2013 n++;
2014 if (c == '\r') {
2015 /* CRLF -> LF */
2016 continue;
2018 if (c == '\n' || c == '\r') {
2019 break;
2021 ch = c;
2022 /* ignore the effect of character count for partial utf8 sequences */
2023 sb_append_len(sb, &ch, 1);
2025 if (n == 0) {
2026 sb_free(sb);
2027 return NULL;
2029 return sb;
2032 char *linenoise(const char *prompt)
2034 int count;
2035 struct current current;
2036 stringbuf *sb;
2038 memset(&current, 0, sizeof(current));
2040 if (enableRawMode(&current) == -1) {
2041 printf("%s", prompt);
2042 fflush(stdout);
2043 sb = sb_getline(stdin);
2045 else {
2046 current.buf = sb_alloc();
2047 current.pos = 0;
2048 current.nrows = 1;
2049 current.prompt = prompt;
2051 count = linenoiseEdit(&current);
2053 disableRawMode(&current);
2054 printf("\n");
2056 sb_free(current.capture);
2057 if (count == -1) {
2058 sb_free(current.buf);
2059 return NULL;
2061 sb = current.buf;
2063 return sb ? sb_to_string(sb) : NULL;
2066 /* Using a circular buffer is smarter, but a bit more complex to handle. */
2067 int linenoiseHistoryAddAllocated(char *line) {
2069 if (history_max_len == 0) {
2070 notinserted:
2071 free(line);
2072 return 0;
2074 if (history == NULL) {
2075 history = (char **)calloc(sizeof(char*), history_max_len);
2078 /* do not insert duplicate lines into history */
2079 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
2080 goto notinserted;
2083 if (history_len == history_max_len) {
2084 free(history[0]);
2085 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
2086 history_len--;
2088 history[history_len] = line;
2089 history_len++;
2090 return 1;
2093 int linenoiseHistoryAdd(const char *line) {
2094 return linenoiseHistoryAddAllocated(strdup(line));
2097 int linenoiseHistoryGetMaxLen(void) {
2098 return history_max_len;
2101 int linenoiseHistorySetMaxLen(int len) {
2102 char **newHistory;
2104 if (len < 1) return 0;
2105 if (history) {
2106 int tocopy = history_len;
2108 newHistory = (char **)calloc(sizeof(char*), len);
2110 /* If we can't copy everything, free the elements we'll not use. */
2111 if (len < tocopy) {
2112 int j;
2114 for (j = 0; j < tocopy-len; j++) free(history[j]);
2115 tocopy = len;
2117 memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
2118 free(history);
2119 history = newHistory;
2121 history_max_len = len;
2122 if (history_len > history_max_len)
2123 history_len = history_max_len;
2124 return 1;
2127 /* Save the history in the specified file. On success 0 is returned
2128 * otherwise -1 is returned. */
2129 int linenoiseHistorySave(const char *filename) {
2130 FILE *fp = fopen(filename,"w");
2131 int j;
2133 if (fp == NULL) return -1;
2134 for (j = 0; j < history_len; j++) {
2135 const char *str = history[j];
2136 /* Need to encode backslash, nl and cr */
2137 while (*str) {
2138 if (*str == '\\') {
2139 fputs("\\\\", fp);
2141 else if (*str == '\n') {
2142 fputs("\\n", fp);
2144 else if (*str == '\r') {
2145 fputs("\\r", fp);
2147 else {
2148 fputc(*str, fp);
2150 str++;
2152 fputc('\n', fp);
2155 fclose(fp);
2156 return 0;
2159 /* Load the history from the specified file.
2161 * If the file does not exist or can't be opened, no operation is performed
2162 * and -1 is returned.
2163 * Otherwise 0 is returned.
2165 int linenoiseHistoryLoad(const char *filename) {
2166 FILE *fp = fopen(filename,"r");
2167 stringbuf *sb;
2169 if (fp == NULL) return -1;
2171 while ((sb = sb_getline(fp)) != NULL) {
2172 /* Take the stringbuf and decode backslash escaped values */
2173 char *buf = sb_to_string(sb);
2174 char *dest = buf;
2175 const char *src;
2177 for (src = buf; *src; src++) {
2178 char ch = *src;
2180 if (ch == '\\') {
2181 src++;
2182 if (*src == 'n') {
2183 ch = '\n';
2185 else if (*src == 'r') {
2186 ch = '\r';
2187 } else {
2188 ch = *src;
2191 *dest++ = ch;
2193 *dest = 0;
2195 linenoiseHistoryAddAllocated(buf);
2197 fclose(fp);
2198 return 0;
2201 /* Provide access to the history buffer.
2203 * If 'len' is not NULL, the length is stored in *len.
2205 char **linenoiseHistory(int *len) {
2206 if (len) {
2207 *len = history_len;
2209 return history;