docs: clock: Document the -gmt flag
[jimtcl.git] / linenoise.c
blob35cef7b38d703aa023898789aaf1c57d403ef56a
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 if (sb->remaining < len + 1) {
184 sb_realloc(sb, sb->last + len + 1 + SB_INCREMENT);
186 memcpy(sb->data + sb->last, str, len);
187 sb->data[sb->last + len] = 0;
189 sb->last += len;
190 sb->remaining -= len;
191 #ifdef USE_UTF8
192 sb->chars += utf8_strlen(str, len);
193 #endif
196 char *sb_to_string(stringbuf *sb)
198 if (sb->data == NULL) {
199 /* Return an allocated empty string, not null */
200 return strdup("");
202 else {
203 /* Just return the data and free the stringbuf structure */
204 char *pt = sb->data;
205 free(sb);
206 return pt;
210 /* Insert and delete operations */
212 /* Moves up all the data at position 'pos' and beyond by 'len' bytes
213 * to make room for new data
215 * Note: Does *not* update sb->chars
217 static void sb_insert_space(stringbuf *sb, int pos, int len)
219 assert(pos <= sb->last);
221 /* Make sure there is enough space */
222 if (sb->remaining < len) {
223 sb_realloc(sb, sb->last + len + SB_INCREMENT);
225 /* Now move it up */
226 memmove(sb->data + pos + len, sb->data + pos, sb->last - pos);
227 sb->last += len;
228 sb->remaining -= len;
229 /* And null terminate */
230 sb->data[sb->last] = 0;
234 * Move down all the data from pos + len, effectively
235 * deleting the data at position 'pos' of length 'len'
237 static void sb_delete_space(stringbuf *sb, int pos, int len)
239 assert(pos < sb->last);
240 assert(pos + len <= sb->last);
242 #ifdef USE_UTF8
243 sb->chars -= utf8_strlen(sb->data + pos, len);
244 #endif
246 /* Now move it up */
247 memmove(sb->data + pos, sb->data + pos + len, sb->last - pos - len);
248 sb->last -= len;
249 sb->remaining += len;
250 /* And null terminate */
251 sb->data[sb->last] = 0;
254 void sb_insert(stringbuf *sb, int index, const char *str)
256 if (index >= sb->last) {
257 /* Inserting after the end of the list appends. */
258 sb_append(sb, str);
260 else {
261 int len = strlen(str);
263 sb_insert_space(sb, index, len);
264 memcpy(sb->data + index, str, len);
265 #ifdef USE_UTF8
266 sb->chars += utf8_strlen(str, len);
267 #endif
272 * Delete the bytes at index 'index' for length 'len'
273 * Has no effect if the index is past the end of the list.
275 void sb_delete(stringbuf *sb, int index, int len)
277 if (index < sb->last) {
278 char *pos = sb->data + index;
279 if (len < 0) {
280 len = sb->last;
283 sb_delete_space(sb, pos - sb->data, len);
287 void sb_clear(stringbuf *sb)
289 if (sb->data) {
290 /* Null terminate */
291 sb->data[0] = 0;
292 sb->last = 0;
293 #ifdef USE_UTF8
294 sb->chars = 0;
295 #endif
298 /* linenoise.c -- guerrilla line editing library against the idea that a
299 * line editing lib needs to be 20,000 lines of C code.
301 * You can find the latest source code at:
303 * http://github.com/msteveb/linenoise
304 * (forked from http://github.com/antirez/linenoise)
306 * Does a number of crazy assumptions that happen to be true in 99.9999% of
307 * the 2010 UNIX computers around.
309 * ------------------------------------------------------------------------
311 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
312 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
313 * Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
315 * All rights reserved.
317 * Redistribution and use in source and binary forms, with or without
318 * modification, are permitted provided that the following conditions are
319 * met:
321 * * Redistributions of source code must retain the above copyright
322 * notice, this list of conditions and the following disclaimer.
324 * * Redistributions in binary form must reproduce the above copyright
325 * notice, this list of conditions and the following disclaimer in the
326 * documentation and/or other materials provided with the distribution.
328 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
329 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
330 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
331 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
332 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
333 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
334 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
335 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
336 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
337 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
338 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
340 * ------------------------------------------------------------------------
342 * References:
343 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
344 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
346 * Bloat:
347 * - Completion?
349 * Unix/termios
350 * ------------
351 * List of escape sequences used by this program, we do everything just
352 * a few sequences. In order to be so cheap we may have some
353 * flickering effect with some slow terminal, but the lesser sequences
354 * the more compatible.
356 * EL (Erase Line)
357 * Sequence: ESC [ 0 K
358 * Effect: clear from cursor to end of line
360 * CUF (CUrsor Forward)
361 * Sequence: ESC [ n C
362 * Effect: moves cursor forward n chars
364 * CR (Carriage Return)
365 * Sequence: \r
366 * Effect: moves cursor to column 1
368 * The following are used to clear the screen: ESC [ H ESC [ 2 J
369 * This is actually composed of two sequences:
371 * cursorhome
372 * Sequence: ESC [ H
373 * Effect: moves the cursor to upper left corner
375 * ED2 (Clear entire screen)
376 * Sequence: ESC [ 2 J
377 * Effect: clear the whole screen
379 * == For highlighting control characters, we also use the following two ==
380 * SO (enter StandOut)
381 * Sequence: ESC [ 7 m
382 * Effect: Uses some standout mode such as reverse video
384 * SE (Standout End)
385 * Sequence: ESC [ 0 m
386 * Effect: Exit standout mode
388 * == Only used if TIOCGWINSZ fails ==
389 * DSR/CPR (Report cursor position)
390 * Sequence: ESC [ 6 n
391 * Effect: reports current cursor position as ESC [ NNN ; MMM R
393 * == Only used in multiline mode ==
394 * CUU (Cursor Up)
395 * Sequence: ESC [ n A
396 * Effect: moves cursor up n chars.
398 * CUD (Cursor Down)
399 * Sequence: ESC [ n B
400 * Effect: moves cursor down n chars.
402 * win32/console
403 * -------------
404 * If __MINGW32__ is defined, the win32 console API is used.
405 * This could probably be made to work for the msvc compiler too.
406 * This support based in part on work by Jon Griffiths.
409 #ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
410 #include <windows.h>
411 #include <fcntl.h>
412 #define USE_WINCONSOLE
413 #ifdef __MINGW32__
414 #define HAVE_UNISTD_H
415 #else
416 /* Microsoft headers don't like old POSIX names */
417 #define strdup _strdup
418 #define snprintf _snprintf
419 #endif
420 #else
421 #include <termios.h>
422 #include <sys/ioctl.h>
423 #include <poll.h>
424 #define USE_TERMIOS
425 #define HAVE_UNISTD_H
426 #endif
428 #ifdef HAVE_UNISTD_H
429 #include <unistd.h>
430 #endif
431 #include <stdlib.h>
432 #include <stdarg.h>
433 #include <stdio.h>
434 #include <assert.h>
435 #include <errno.h>
436 #include <string.h>
437 #include <signal.h>
438 #include <stdlib.h>
439 #include <sys/types.h>
441 #include "linenoise.h"
442 #ifndef STRINGBUF_H
443 #include "stringbuf.h"
444 #endif
445 #include "utf8.h"
447 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
449 #define ctrl(C) ((C) - '@')
451 /* Use -ve numbers here to co-exist with normal unicode chars */
452 enum {
453 SPECIAL_NONE,
454 /* don't use -1 here since that indicates error */
455 SPECIAL_UP = -20,
456 SPECIAL_DOWN = -21,
457 SPECIAL_LEFT = -22,
458 SPECIAL_RIGHT = -23,
459 SPECIAL_DELETE = -24,
460 SPECIAL_HOME = -25,
461 SPECIAL_END = -26,
462 SPECIAL_INSERT = -27,
463 SPECIAL_PAGE_UP = -28,
464 SPECIAL_PAGE_DOWN = -29,
466 /* Some handy names for other special keycodes */
467 CHAR_ESCAPE = 27,
468 CHAR_DELETE = 127,
471 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
472 static int history_len = 0;
473 static char **history = NULL;
475 /* Structure to contain the status of the current (being edited) line */
476 struct current {
477 stringbuf *buf; /* Current buffer. Always null terminated */
478 int pos; /* Cursor position, measured in chars */
479 int cols; /* Size of the window, in chars */
480 int nrows; /* How many rows are being used in multiline mode (>= 1) */
481 int rpos; /* The current row containing the cursor - multiline mode only */
482 int colsright; /* refreshLine() cached cols for insert_char() optimisation */
483 int colsleft; /* refreshLine() cached cols for remove_char() optimisation */
484 const char *prompt;
485 stringbuf *capture; /* capture buffer, or NULL for none. Always null terminated */
486 stringbuf *output; /* used only during refreshLine() - output accumulator */
487 #if defined(USE_TERMIOS)
488 int fd; /* Terminal fd */
489 #elif defined(USE_WINCONSOLE)
490 HANDLE outh; /* Console output handle */
491 HANDLE inh; /* Console input handle */
492 int rows; /* Screen rows */
493 int x; /* Current column during output */
494 int y; /* Current row */
495 #ifdef USE_UTF8
496 #define UBUF_MAX_CHARS 132
497 WORD ubuf[UBUF_MAX_CHARS + 1]; /* Accumulates utf16 output - one extra for final surrogate pairs */
498 int ubuflen; /* length used in ubuf */
499 int ubufcols; /* how many columns are represented by the chars in ubuf? */
500 #endif
501 #endif
504 static int fd_read(struct current *current);
505 static int getWindowSize(struct current *current);
506 static void cursorDown(struct current *current, int n);
507 static void cursorUp(struct current *current, int n);
508 static void eraseEol(struct current *current);
509 static void refreshLine(struct current *current);
510 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos);
511 static void setCursorPos(struct current *current, int x);
512 static void setOutputHighlight(struct current *current, const int *props, int nprops);
513 static void set_current(struct current *current, const char *str);
515 void linenoiseHistoryFree(void) {
516 if (history) {
517 int j;
519 for (j = 0; j < history_len; j++)
520 free(history[j]);
521 free(history);
522 history = NULL;
523 history_len = 0;
527 struct esc_parser {
528 enum {
529 EP_START, /* looking for ESC */
530 EP_ESC, /* looking for [ */
531 EP_DIGITS, /* parsing digits */
532 EP_PROPS, /* parsing digits or semicolons */
533 EP_END, /* ok */
534 EP_ERROR, /* error */
535 } state;
536 int props[5]; /* properties are stored here */
537 int maxprops; /* size of the props[] array */
538 int numprops; /* number of properties found */
539 int termchar; /* terminator char, or 0 for any alpha */
540 int current; /* current (partial) property value */
544 * Initialise the escape sequence parser at *parser.
546 * If termchar is 0 any alpha char terminates ok. Otherwise only the given
547 * char terminates successfully.
548 * Run the parser state machine with calls to parseEscapeSequence() for each char.
550 static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
552 parser->state = EP_START;
553 parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
554 parser->numprops = 0;
555 parser->current = 0;
556 parser->termchar = termchar;
560 * Pass character 'ch' into the state machine to parse:
561 * 'ESC' '[' <digits> (';' <digits>)* <termchar>
563 * The first character must be ESC.
564 * Returns the current state. The state machine is done when it returns either EP_END
565 * or EP_ERROR.
567 * On EP_END, the "property/attribute" values can be read from parser->props[]
568 * of length parser->numprops.
570 static int parseEscapeSequence(struct esc_parser *parser, int ch)
572 switch (parser->state) {
573 case EP_START:
574 parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
575 break;
576 case EP_ESC:
577 parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
578 break;
579 case EP_PROPS:
580 if (ch == ';') {
581 parser->state = EP_DIGITS;
582 donedigits:
583 if (parser->numprops + 1 < parser->maxprops) {
584 parser->props[parser->numprops++] = parser->current;
585 parser->current = 0;
587 break;
589 /* fall through */
590 case EP_DIGITS:
591 if (ch >= '0' && ch <= '9') {
592 parser->current = parser->current * 10 + (ch - '0');
593 parser->state = EP_PROPS;
594 break;
596 /* must be terminator */
597 if (parser->termchar != ch) {
598 if (parser->termchar != 0 || !((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
599 parser->state = EP_ERROR;
600 break;
603 parser->state = EP_END;
604 goto donedigits;
605 case EP_END:
606 parser->state = EP_ERROR;
607 break;
608 case EP_ERROR:
609 break;
611 return parser->state;
614 /*#define DEBUG_REFRESHLINE*/
616 #ifdef DEBUG_REFRESHLINE
617 #define DRL(ARGS...) fprintf(dfh, ARGS)
618 static FILE *dfh;
620 static void DRL_CHAR(int ch)
622 if (ch < ' ') {
623 DRL("^%c", ch + '@');
625 else if (ch > 127) {
626 DRL("\\u%04x", ch);
628 else {
629 DRL("%c", ch);
632 static void DRL_STR(const char *str)
634 while (*str) {
635 int ch;
636 int n = utf8_tounicode(str, &ch);
637 str += n;
638 DRL_CHAR(ch);
641 #else
642 #define DRL(ARGS...)
643 #define DRL_CHAR(ch)
644 #define DRL_STR(str)
645 #endif
647 #if defined(USE_WINCONSOLE)
648 #include "linenoise-win32.c"
649 #endif
651 #if defined(USE_TERMIOS)
652 static void linenoiseAtExit(void);
653 static struct termios orig_termios; /* in order to restore at exit */
654 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
655 static int atexit_registered = 0; /* register atexit just 1 time */
657 static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
659 static int isUnsupportedTerm(void) {
660 char *term = getenv("TERM");
662 if (term) {
663 int j;
664 for (j = 0; unsupported_term[j]; j++) {
665 if (strcmp(term, unsupported_term[j]) == 0) {
666 return 1;
670 return 0;
673 static int enableRawMode(struct current *current) {
674 struct termios raw;
676 current->fd = STDIN_FILENO;
677 current->cols = 0;
679 if (!isatty(current->fd) || isUnsupportedTerm() ||
680 tcgetattr(current->fd, &orig_termios) == -1) {
681 fatal:
682 errno = ENOTTY;
683 return -1;
686 if (!atexit_registered) {
687 atexit(linenoiseAtExit);
688 atexit_registered = 1;
691 raw = orig_termios; /* modify the original mode */
692 /* input modes: no break, no CR to NL, no parity check, no strip char,
693 * no start/stop output control. */
694 raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
695 /* output modes - actually, no need to disable post processing */
696 /*raw.c_oflag &= ~(OPOST);*/
697 /* control modes - set 8 bit chars */
698 raw.c_cflag |= (CS8);
699 /* local modes - choing off, canonical off, no extended functions,
700 * no signal chars (^Z,^C) */
701 raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
702 /* control chars - set return condition: min number of bytes and timer.
703 * We want read to return every single byte, without timeout. */
704 raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
706 /* put terminal in raw mode after flushing */
707 if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
708 goto fatal;
710 rawmode = 1;
711 return 0;
714 static void disableRawMode(struct current *current) {
715 /* Don't even check the return value as it's too late. */
716 if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
717 rawmode = 0;
720 /* At exit we'll try to fix the terminal to the initial conditions. */
721 static void linenoiseAtExit(void) {
722 if (rawmode) {
723 tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
725 linenoiseHistoryFree();
728 /* gcc/glibc insists that we care about the return code of write!
729 * Clarification: This means that a void-cast like "(void) (EXPR)"
730 * does not work.
732 #define IGNORE_RC(EXPR) if (EXPR) {}
735 * Output bytes directly, or accumulate output (if current->output is set)
737 static void outputChars(struct current *current, const char *buf, int len)
739 if (len < 0) {
740 len = strlen(buf);
742 if (current->output) {
743 sb_append_len(current->output, buf, len);
745 else {
746 IGNORE_RC(write(current->fd, buf, len));
750 /* Like outputChars, but using printf-style formatting
752 static void outputFormatted(struct current *current, const char *format, ...)
754 va_list args;
755 char buf[64];
756 int n;
758 va_start(args, format);
759 n = vsnprintf(buf, sizeof(buf), format, args);
760 /* This will never happen because we are sure to use outputFormatted() only for short sequences */
761 assert(n < (int)sizeof(buf));
762 va_end(args);
763 outputChars(current, buf, n);
766 static void cursorToLeft(struct current *current)
768 outputChars(current, "\r", -1);
771 static void setOutputHighlight(struct current *current, const int *props, int nprops)
773 outputChars(current, "\x1b[", -1);
774 while (nprops--) {
775 outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
776 props++;
780 static void eraseEol(struct current *current)
782 outputChars(current, "\x1b[0K", -1);
785 static void setCursorPos(struct current *current, int x)
787 if (x == 0) {
788 cursorToLeft(current);
790 else {
791 outputFormatted(current, "\r\x1b[%dC", x);
795 static void cursorUp(struct current *current, int n)
797 if (n) {
798 outputFormatted(current, "\x1b[%dA", n);
802 static void cursorDown(struct current *current, int n)
804 if (n) {
805 outputFormatted(current, "\x1b[%dB", n);
809 void linenoiseClearScreen(void)
811 IGNORE_RC(write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7));
815 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
817 * A timeout of -1 means to wait forever.
819 * Returns -1 if no char is received within the time or an error occurs.
821 static int fd_read_char(int fd, int timeout)
823 struct pollfd p;
824 unsigned char c;
826 p.fd = fd;
827 p.events = POLLIN;
829 if (poll(&p, 1, timeout) == 0) {
830 /* timeout */
831 return -1;
833 if (read(fd, &c, 1) != 1) {
834 return -1;
836 return c;
840 * Reads a complete utf-8 character
841 * and returns the unicode value, or -1 on error.
843 static int fd_read(struct current *current)
845 #ifdef USE_UTF8
846 char buf[MAX_UTF8_LEN];
847 int n;
848 int i;
849 int c;
851 if (read(current->fd, &buf[0], 1) != 1) {
852 return -1;
854 n = utf8_charlen(buf[0]);
855 if (n < 1) {
856 return -1;
858 for (i = 1; i < n; i++) {
859 if (read(current->fd, &buf[i], 1) != 1) {
860 return -1;
863 /* decode and return the character */
864 utf8_tounicode(buf, &c);
865 return c;
866 #else
867 return fd_read_char(current->fd, -1);
868 #endif
873 * Stores the current cursor column in '*cols'.
874 * Returns 1 if OK, or 0 if failed to determine cursor pos.
876 static int queryCursor(struct current *current, int* cols)
878 struct esc_parser parser;
879 int ch;
881 /* Should not be buffering this output, it needs to go immediately */
882 assert(current->output == NULL);
884 /* control sequence - report cursor location */
885 outputChars(current, "\x1b[6n", -1);
887 /* Parse the response: ESC [ rows ; cols R */
888 initParseEscapeSeq(&parser, 'R');
889 while ((ch = fd_read_char(current->fd, 100)) > 0) {
890 switch (parseEscapeSequence(&parser, ch)) {
891 default:
892 continue;
893 case EP_END:
894 if (parser.numprops == 2 && parser.props[1] < 1000) {
895 *cols = parser.props[1];
896 return 1;
898 break;
899 case EP_ERROR:
900 break;
902 /* failed */
903 break;
905 return 0;
909 * Updates current->cols with the current window size (width)
911 static int getWindowSize(struct current *current)
913 struct winsize ws;
915 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
916 current->cols = ws.ws_col;
917 return 0;
920 /* Failed to query the window size. Perhaps we are on a serial terminal.
921 * Try to query the width by sending the cursor as far to the right
922 * and reading back the cursor position.
923 * Note that this is only done once per call to linenoise rather than
924 * every time the line is refreshed for efficiency reasons.
926 * In more detail, we:
927 * (a) request current cursor position,
928 * (b) move cursor far right,
929 * (c) request cursor position again,
930 * (d) at last move back to the old position.
931 * This gives us the width without messing with the externally
932 * visible cursor position.
935 if (current->cols == 0) {
936 int here;
938 /* If anything fails => default 80 */
939 current->cols = 80;
941 /* (a) */
942 if (queryCursor (current, &here)) {
943 /* (b) */
944 setCursorPos(current, 999);
946 /* (c). Note: If (a) succeeded, then (c) should as well.
947 * For paranoia we still check and have a fallback action
948 * for (d) in case of failure..
950 if (queryCursor (current, &current->cols)) {
951 /* (d) Reset the cursor back to the original location. */
952 if (current->cols > here) {
953 setCursorPos(current, here);
959 return 0;
963 * If CHAR_ESCAPE was received, reads subsequent
964 * chars to determine if this is a known special key.
966 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
968 * If no additional char is received within a short time,
969 * CHAR_ESCAPE is returned.
971 static int check_special(int fd)
973 int c = fd_read_char(fd, 50);
974 int c2;
976 if (c < 0) {
977 return CHAR_ESCAPE;
980 c2 = fd_read_char(fd, 50);
981 if (c2 < 0) {
982 return c2;
984 if (c == '[' || c == 'O') {
985 /* Potential arrow key */
986 switch (c2) {
987 case 'A':
988 return SPECIAL_UP;
989 case 'B':
990 return SPECIAL_DOWN;
991 case 'C':
992 return SPECIAL_RIGHT;
993 case 'D':
994 return SPECIAL_LEFT;
995 case 'F':
996 return SPECIAL_END;
997 case 'H':
998 return SPECIAL_HOME;
1001 if (c == '[' && c2 >= '1' && c2 <= '8') {
1002 /* extended escape */
1003 c = fd_read_char(fd, 50);
1004 if (c == '~') {
1005 switch (c2) {
1006 case '2':
1007 return SPECIAL_INSERT;
1008 case '3':
1009 return SPECIAL_DELETE;
1010 case '5':
1011 return SPECIAL_PAGE_UP;
1012 case '6':
1013 return SPECIAL_PAGE_DOWN;
1014 case '7':
1015 return SPECIAL_HOME;
1016 case '8':
1017 return SPECIAL_END;
1020 while (c != -1 && c != '~') {
1021 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
1022 c = fd_read_char(fd, 50);
1026 return SPECIAL_NONE;
1028 #endif
1030 static void clearOutputHighlight(struct current *current)
1032 int nohighlight = 0;
1033 setOutputHighlight(current, &nohighlight, 1);
1036 static void outputControlChar(struct current *current, char ch)
1038 int reverse = 7;
1039 setOutputHighlight(current, &reverse, 1);
1040 outputChars(current, "^", 1);
1041 outputChars(current, &ch, 1);
1042 clearOutputHighlight(current);
1045 #ifndef utf8_getchars
1046 static int utf8_getchars(char *buf, int c)
1048 #ifdef USE_UTF8
1049 return utf8_fromunicode(buf, c);
1050 #else
1051 *buf = c;
1052 return 1;
1053 #endif
1055 #endif
1058 * Returns the unicode character at the given offset,
1059 * or -1 if none.
1061 static int get_char(struct current *current, int pos)
1063 if (pos >= 0 && pos < sb_chars(current->buf)) {
1064 int c;
1065 int i = utf8_index(sb_str(current->buf), pos);
1066 (void)utf8_tounicode(sb_str(current->buf) + i, &c);
1067 return c;
1069 return -1;
1072 static int char_display_width(int ch)
1074 if (ch < ' ') {
1075 /* control chars take two positions */
1076 return 2;
1078 else {
1079 return utf8_width(ch);
1083 #ifndef NO_COMPLETION
1084 static linenoiseCompletionCallback *completionCallback = NULL;
1085 static void *completionUserdata = NULL;
1086 static int showhints = 1;
1087 static linenoiseHintsCallback *hintsCallback = NULL;
1088 static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
1089 static void *hintsUserdata = NULL;
1091 static void beep() {
1092 #ifdef USE_TERMIOS
1093 fprintf(stderr, "\x7");
1094 fflush(stderr);
1095 #endif
1098 static void freeCompletions(linenoiseCompletions *lc) {
1099 size_t i;
1100 for (i = 0; i < lc->len; i++)
1101 free(lc->cvec[i]);
1102 free(lc->cvec);
1105 static int completeLine(struct current *current) {
1106 linenoiseCompletions lc = { 0, NULL };
1107 int c = 0;
1109 completionCallback(sb_str(current->buf),&lc,completionUserdata);
1110 if (lc.len == 0) {
1111 beep();
1112 } else {
1113 size_t stop = 0, i = 0;
1115 while(!stop) {
1116 /* Show completion or original buffer */
1117 if (i < lc.len) {
1118 int chars = utf8_strlen(lc.cvec[i], -1);
1119 refreshLineAlt(current, current->prompt, lc.cvec[i], chars);
1120 } else {
1121 refreshLine(current);
1124 c = fd_read(current);
1125 if (c == -1) {
1126 break;
1129 switch(c) {
1130 case '\t': /* tab */
1131 i = (i+1) % (lc.len+1);
1132 if (i == lc.len) beep();
1133 break;
1134 case CHAR_ESCAPE: /* escape */
1135 /* Re-show original buffer */
1136 if (i < lc.len) {
1137 refreshLine(current);
1139 stop = 1;
1140 break;
1141 default:
1142 /* Update buffer and return */
1143 if (i < lc.len) {
1144 set_current(current,lc.cvec[i]);
1146 stop = 1;
1147 break;
1152 freeCompletions(&lc);
1153 return c; /* Return last read character */
1156 /* Register a callback function to be called for tab-completion.
1157 Returns the prior callback so that the caller may (if needed)
1158 restore it when done. */
1159 linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
1160 linenoiseCompletionCallback * old = completionCallback;
1161 completionCallback = fn;
1162 completionUserdata = userdata;
1163 return old;
1166 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1167 lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1168 lc->cvec[lc->len++] = strdup(str);
1171 void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
1173 hintsCallback = callback;
1174 hintsUserdata = userdata;
1177 void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
1179 freeHintsCallback = callback;
1182 #endif
1185 static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
1187 /* We have availcols columns available.
1188 * If necessary, strip chars off the front of buf until *cursor_pos
1189 * fits within availcols
1191 int needcols = 0;
1192 int pos = 0;
1193 int new_cursor_pos = *cursor_pos;
1194 const char *pt = buf;
1196 DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);
1198 while (*pt) {
1199 int ch;
1200 int n = utf8_tounicode(pt, &ch);
1201 pt += n;
1203 needcols += char_display_width(ch);
1205 /* If we need too many cols, strip
1206 * chars off the front of buf to make it fit.
1207 * We keep 3 extra cols to the right of the cursor.
1208 * 2 for possible wide chars, 1 for the last column that
1209 * can't be used.
1211 while (needcols >= availcols - 3) {
1212 n = utf8_tounicode(buf, &ch);
1213 buf += n;
1214 needcols -= char_display_width(ch);
1215 DRL_CHAR(ch);
1217 /* and adjust the apparent cursor position */
1218 new_cursor_pos--;
1220 if (buf == pt) {
1221 /* can't remove more than this */
1222 break;
1226 if (pos++ == *cursor_pos) {
1227 break;
1231 DRL("<snip>");
1232 DRL_STR(buf);
1233 DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);
1235 /* Done, now new_cursor_pos contains the adjusted cursor position
1236 * and buf points to he adjusted start
1238 *cursor_pos = new_cursor_pos;
1239 return buf;
1242 static int mlmode = 0;
1244 void linenoiseSetMultiLine(int enableml)
1246 mlmode = enableml;
1249 /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
1250 * to the right of the prompt.
1251 * Returns 1 if a hint was shown, or 0 if not
1252 * If 'display' is 0, does no output. Just returns the appropriate return code.
1254 static int refreshShowHints(struct current *current, const char *buf, int availcols, int display)
1256 int rc = 0;
1257 if (showhints && hintsCallback && availcols > 0) {
1258 int bold = 0;
1259 int color = -1;
1260 char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
1261 if (hint) {
1262 rc = 1;
1263 if (display) {
1264 const char *pt;
1265 if (bold == 1 && color == -1) color = 37;
1266 if (bold || color > 0) {
1267 int props[3] = { bold, color, 49 }; /* bold, color, fgnormal */
1268 setOutputHighlight(current, props, 3);
1270 DRL("<hint bold=%d,color=%d>", bold, color);
1271 pt = hint;
1272 while (*pt) {
1273 int ch;
1274 int n = utf8_tounicode(pt, &ch);
1275 int width = char_display_width(ch);
1277 if (width >= availcols) {
1278 DRL("<hinteol>");
1279 break;
1281 DRL_CHAR(ch);
1283 availcols -= width;
1284 outputChars(current, pt, n);
1285 pt += n;
1287 if (bold || color > 0) {
1288 clearOutputHighlight(current);
1290 /* Call the function to free the hint returned. */
1291 if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
1295 return rc;
1298 #ifdef USE_TERMIOS
1299 static void refreshStart(struct current *current)
1301 /* We accumulate all output here */
1302 assert(current->output == NULL);
1303 current->output = sb_alloc();
1306 static void refreshEnd(struct current *current)
1308 /* Output everything at once */
1309 IGNORE_RC(write(current->fd, sb_str(current->output), sb_len(current->output)));
1310 sb_free(current->output);
1311 current->output = NULL;
1314 static void refreshStartChars(struct current *current)
1318 static void refreshNewline(struct current *current)
1320 DRL("<nl>");
1321 outputChars(current, "\n", 1);
1324 static void refreshEndChars(struct current *current)
1327 #endif
1329 static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
1331 int i;
1332 const char *pt;
1333 int displaycol;
1334 int displayrow;
1335 int visible;
1336 int currentpos;
1337 int notecursor;
1338 int cursorcol = 0;
1339 int cursorrow = 0;
1340 int hint;
1341 struct esc_parser parser;
1343 #ifdef DEBUG_REFRESHLINE
1344 dfh = fopen("linenoise.debuglog", "a");
1345 #endif
1347 /* Should intercept SIGWINCH. For now, just get the size every time */
1348 getWindowSize(current);
1350 refreshStart(current);
1352 DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);
1354 /* Here is the plan:
1355 * (a) move the the bottom row, going down the appropriate number of lines
1356 * (b) move to beginning of line and erase the current line
1357 * (c) go up one line and do the same, until we have erased up to the first row
1358 * (d) output the prompt, counting cols and rows, taking into account escape sequences
1359 * (e) output the buffer, counting cols and rows
1360 * (e') when we hit the current pos, save the cursor position
1361 * (f) move the cursor to the saved cursor position
1362 * (g) save the current cursor row and number of rows
1365 /* (a) - The cursor is currently at row rpos */
1366 cursorDown(current, current->nrows - current->rpos - 1);
1367 DRL("<cud=%d>", current->nrows - current->rpos - 1);
1369 /* (b), (c) - Erase lines upwards until we get to the first row */
1370 for (i = 0; i < current->nrows; i++) {
1371 if (i) {
1372 DRL("<cup>");
1373 cursorUp(current, 1);
1375 DRL("<clearline>");
1376 cursorToLeft(current);
1377 eraseEol(current);
1379 DRL("\n");
1381 /* (d) First output the prompt. control sequences don't take up display space */
1382 pt = prompt;
1383 displaycol = 0; /* current display column */
1384 displayrow = 0; /* current display row */
1385 visible = 1;
1387 refreshStartChars(current);
1389 while (*pt) {
1390 int width;
1391 int ch;
1392 int n = utf8_tounicode(pt, &ch);
1394 if (visible && ch == CHAR_ESCAPE) {
1395 /* The start of an escape sequence, so not visible */
1396 visible = 0;
1397 initParseEscapeSeq(&parser, 'm');
1398 DRL("<esc-seq-start>");
1401 if (ch == '\n' || ch == '\r') {
1402 /* treat both CR and NL the same and force wrap */
1403 refreshNewline(current);
1404 displaycol = 0;
1405 displayrow++;
1407 else {
1408 width = visible * utf8_width(ch);
1410 displaycol += width;
1411 if (displaycol >= current->cols) {
1412 /* need to wrap to the next line because of newline or if it doesn't fit
1413 * XXX this is a problem in single line mode
1415 refreshNewline(current);
1416 displaycol = width;
1417 displayrow++;
1420 DRL_CHAR(ch);
1421 #ifdef USE_WINCONSOLE
1422 if (visible) {
1423 outputChars(current, pt, n);
1425 #else
1426 outputChars(current, pt, n);
1427 #endif
1429 pt += n;
1431 if (!visible) {
1432 switch (parseEscapeSequence(&parser, ch)) {
1433 case EP_END:
1434 visible = 1;
1435 setOutputHighlight(current, parser.props, parser.numprops);
1436 DRL("<esc-seq-end,numprops=%d>", parser.numprops);
1437 break;
1438 case EP_ERROR:
1439 DRL("<esc-seq-err>");
1440 visible = 1;
1441 break;
1446 /* Now we are at the first line with all lines erased */
1447 DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);
1450 /* (e) output the buffer, counting cols and rows */
1451 if (mlmode == 0) {
1452 /* In this mode we may need to trim chars from the start of the buffer until the
1453 * cursor fits in the window.
1455 pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
1457 else {
1458 pt = buf;
1461 currentpos = 0;
1462 notecursor = -1;
1464 while (*pt) {
1465 int ch;
1466 int n = utf8_tounicode(pt, &ch);
1467 int width = char_display_width(ch);
1469 if (currentpos == cursor_pos) {
1470 /* (e') wherever we output this character is where we want the cursor */
1471 notecursor = 1;
1474 if (displaycol + width >= current->cols) {
1475 if (mlmode == 0) {
1476 /* In single line mode stop once we print as much as we can on one line */
1477 DRL("<slmode>");
1478 break;
1480 /* need to wrap to the next line since it doesn't fit */
1481 refreshNewline(current);
1482 displaycol = 0;
1483 displayrow++;
1486 if (notecursor == 1) {
1487 /* (e') Save this position as the current cursor position */
1488 cursorcol = displaycol;
1489 cursorrow = displayrow;
1490 notecursor = 0;
1491 DRL("<cursor>");
1494 displaycol += width;
1496 if (ch < ' ') {
1497 outputControlChar(current, ch + '@');
1499 else {
1500 outputChars(current, pt, n);
1502 DRL_CHAR(ch);
1503 if (width != 1) {
1504 DRL("<w=%d>", width);
1507 pt += n;
1508 currentpos++;
1511 /* If we didn't see the cursor, it is at the current location */
1512 if (notecursor) {
1513 DRL("<cursor>");
1514 cursorcol = displaycol;
1515 cursorrow = displayrow;
1518 DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n", displaycol, displayrow, cursorcol, cursorrow);
1520 /* (f) show hints */
1521 hint = refreshShowHints(current, buf, current->cols - displaycol, 1);
1523 /* Remember how many many cols are available for insert optimisation */
1524 if (prompt == current->prompt && hint == 0) {
1525 current->colsright = current->cols - displaycol;
1526 current->colsleft = displaycol;
1528 else {
1529 /* Can't optimise */
1530 current->colsright = 0;
1531 current->colsleft = 0;
1533 DRL("\nafter hints: colsleft=%d, colsright=%d\n\n", current->colsleft, current->colsright);
1535 refreshEndChars(current);
1537 /* (g) move the cursor to the correct place */
1538 cursorUp(current, displayrow - cursorrow);
1539 setCursorPos(current, cursorcol);
1541 /* (h) Update the number of rows if larger, but never reduce this */
1542 if (displayrow >= current->nrows) {
1543 current->nrows = displayrow + 1;
1545 /* And remember the row that the cursor is on */
1546 current->rpos = cursorrow;
1548 refreshEnd(current);
1550 #ifdef DEBUG_REFRESHLINE
1551 fclose(dfh);
1552 #endif
1555 static void refreshLine(struct current *current)
1557 refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
1560 static void set_current(struct current *current, const char *str)
1562 sb_clear(current->buf);
1563 sb_append(current->buf, str);
1564 current->pos = sb_chars(current->buf);
1568 * Removes the char at 'pos'.
1570 * Returns 1 if the line needs to be refreshed, 2 if not
1571 * and 0 if nothing was removed
1573 static int remove_char(struct current *current, int pos)
1575 if (pos >= 0 && pos < sb_chars(current->buf)) {
1576 int offset = utf8_index(sb_str(current->buf), pos);
1577 int nbytes = utf8_index(sb_str(current->buf) + offset, 1);
1578 int rc = 1;
1580 /* Now we try to optimise in the simple but very common case that:
1581 * - we are remove the char at EOL
1582 * - the buffer is not empty
1583 * - there are columns available to the left
1584 * - the char being deleted is not a wide or utf-8 character
1585 * - no hints are being shown
1587 if (current->pos == pos + 1 && current->pos == sb_chars(current->buf) && pos > 0) {
1588 #ifdef USE_UTF8
1589 /* Could implement utf8_prev_len() but simplest just to not optimise this case */
1590 char last = sb_str(current->buf)[offset];
1591 #else
1592 char last = 0;
1593 #endif
1594 if (current->colsleft > 0 && (last & 0x80) == 0) {
1595 /* Have cols on the left and not a UTF-8 char or continuation */
1596 /* Yes, can optimise */
1597 current->colsleft--;
1598 current->colsright++;
1599 rc = 2;
1603 sb_delete(current->buf, offset, nbytes);
1605 if (current->pos > pos) {
1606 current->pos--;
1608 if (rc == 2) {
1609 if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
1610 /* A hint needs to be shown, so can't optimise after all */
1611 rc = 1;
1613 else {
1614 /* optimised output */
1615 outputChars(current, "\b \b", 3);
1618 return rc;
1619 return 1;
1621 return 0;
1625 * Insert 'ch' at position 'pos'
1627 * Returns 1 if the line needs to be refreshed, 2 if not
1628 * and 0 if nothing was inserted (no room)
1630 static int insert_char(struct current *current, int pos, int ch)
1632 if (pos >= 0 && pos <= sb_chars(current->buf)) {
1633 char buf[MAX_UTF8_LEN + 1];
1634 int offset = utf8_index(sb_str(current->buf), pos);
1635 int n = utf8_getchars(buf, ch);
1636 int rc = 1;
1638 /* null terminate since sb_insert() requires it */
1639 buf[n] = 0;
1641 /* Now we try to optimise in the simple but very common case that:
1642 * - we are inserting at EOL
1643 * - there are enough columns available
1644 * - no hints are being shown
1646 if (pos == current->pos && pos == sb_chars(current->buf)) {
1647 int width = char_display_width(ch);
1648 if (current->colsright > width) {
1649 /* Yes, can optimise */
1650 current->colsright -= width;
1651 current->colsleft -= width;
1652 rc = 2;
1655 sb_insert(current->buf, offset, buf);
1656 if (current->pos >= pos) {
1657 current->pos++;
1659 if (rc == 2) {
1660 if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
1661 /* A hint needs to be shown, so can't optimise after all */
1662 rc = 1;
1664 else {
1665 /* optimised output */
1666 outputChars(current, buf, n);
1669 return rc;
1671 return 0;
1675 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
1677 * This replaces any existing characters in the cut buffer.
1679 static void capture_chars(struct current *current, int pos, int nchars)
1681 if (pos >= 0 && (pos + nchars - 1) < sb_chars(current->buf)) {
1682 int offset = utf8_index(sb_str(current->buf), pos);
1683 int nbytes = utf8_index(sb_str(current->buf) + offset, nchars);
1685 if (nbytes > 0) {
1686 if (current->capture) {
1687 sb_clear(current->capture);
1689 else {
1690 current->capture = sb_alloc();
1692 sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
1698 * Removes up to 'n' characters at cursor position 'pos'.
1700 * Returns 0 if no chars were removed or non-zero otherwise.
1702 static int remove_chars(struct current *current, int pos, int n)
1704 int removed = 0;
1706 /* First save any chars which will be removed */
1707 capture_chars(current, pos, n);
1709 while (n-- && remove_char(current, pos)) {
1710 removed++;
1712 return removed;
1715 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
1717 * Returns 0 if no chars were inserted or non-zero otherwise.
1719 static int insert_chars(struct current *current, int pos, const char *chars)
1721 int inserted = 0;
1723 while (*chars) {
1724 int ch;
1725 int n = utf8_tounicode(chars, &ch);
1726 if (insert_char(current, pos, ch) == 0) {
1727 break;
1729 inserted++;
1730 pos++;
1731 chars += n;
1733 return inserted;
1737 * Returns the keycode to process, or 0 if none.
1739 static int reverseIncrementalSearch(struct current *current)
1741 /* Display the reverse-i-search prompt and process chars */
1742 char rbuf[50];
1743 char rprompt[80];
1744 int rchars = 0;
1745 int rlen = 0;
1746 int searchpos = history_len - 1;
1747 int c;
1749 rbuf[0] = 0;
1750 while (1) {
1751 int n = 0;
1752 const char *p = NULL;
1753 int skipsame = 0;
1754 int searchdir = -1;
1756 snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1757 refreshLineAlt(current, rprompt, sb_str(current->buf), current->pos);
1758 c = fd_read(current);
1759 if (c == ctrl('H') || c == CHAR_DELETE) {
1760 if (rchars) {
1761 int p = utf8_index(rbuf, --rchars);
1762 rbuf[p] = 0;
1763 rlen = strlen(rbuf);
1765 continue;
1767 #ifdef USE_TERMIOS
1768 if (c == CHAR_ESCAPE) {
1769 c = check_special(current->fd);
1771 #endif
1772 if (c == ctrl('P') || c == SPECIAL_UP) {
1773 /* Search for the previous (earlier) match */
1774 if (searchpos > 0) {
1775 searchpos--;
1777 skipsame = 1;
1779 else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1780 /* Search for the next (later) match */
1781 if (searchpos < history_len) {
1782 searchpos++;
1784 searchdir = 1;
1785 skipsame = 1;
1787 else if (c >= ' ') {
1788 /* >= here to allow for null terminator */
1789 if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
1790 continue;
1793 n = utf8_getchars(rbuf + rlen, c);
1794 rlen += n;
1795 rchars++;
1796 rbuf[rlen] = 0;
1798 /* Adding a new char resets the search location */
1799 searchpos = history_len - 1;
1801 else {
1802 /* Exit from incremental search mode */
1803 break;
1806 /* Now search through the history for a match */
1807 for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1808 p = strstr(history[searchpos], rbuf);
1809 if (p) {
1810 /* Found a match */
1811 if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
1812 /* But it is identical, so skip it */
1813 continue;
1815 /* Copy the matching line and set the cursor position */
1816 set_current(current,history[searchpos]);
1817 current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1818 break;
1821 if (!p && n) {
1822 /* No match, so don't add it */
1823 rchars--;
1824 rlen -= n;
1825 rbuf[rlen] = 0;
1828 if (c == ctrl('G') || c == ctrl('C')) {
1829 /* ctrl-g terminates the search with no effect */
1830 set_current(current, "");
1831 c = 0;
1833 else if (c == ctrl('J')) {
1834 /* ctrl-j terminates the search leaving the buffer in place */
1835 c = 0;
1838 /* Go process the char normally */
1839 refreshLine(current);
1840 return c;
1843 static int linenoiseEdit(struct current *current) {
1844 int history_index = 0;
1846 /* The latest history entry is always our current buffer, that
1847 * initially is just an empty string. */
1848 linenoiseHistoryAdd("");
1850 set_current(current, "");
1851 refreshLine(current);
1853 while(1) {
1854 int dir = -1;
1855 int c = fd_read(current);
1857 #ifndef NO_COMPLETION
1858 /* Only autocomplete when the callback is set. It returns < 0 when
1859 * there was an error reading from fd. Otherwise it will return the
1860 * character that should be handled next. */
1861 if (c == '\t' && current->pos == sb_chars(current->buf) && completionCallback != NULL) {
1862 c = completeLine(current);
1864 #endif
1865 if (c == ctrl('R')) {
1866 /* reverse incremental search will provide an alternative keycode or 0 for none */
1867 c = reverseIncrementalSearch(current);
1868 /* go on to process the returned char normally */
1871 #ifdef USE_TERMIOS
1872 if (c == CHAR_ESCAPE) { /* escape sequence */
1873 c = check_special(current->fd);
1875 #endif
1876 if (c == -1) {
1877 /* Return on errors */
1878 return sb_len(current->buf);
1881 switch(c) {
1882 case SPECIAL_NONE:
1883 break;
1884 case '\r': /* enter */
1885 history_len--;
1886 free(history[history_len]);
1887 current->pos = sb_chars(current->buf);
1888 if (mlmode || hintsCallback) {
1889 showhints = 0;
1890 refreshLine(current);
1891 showhints = 1;
1893 return sb_len(current->buf);
1894 case ctrl('C'): /* ctrl-c */
1895 errno = EAGAIN;
1896 return -1;
1897 case ctrl('Z'): /* ctrl-z */
1898 #ifdef SIGTSTP
1899 /* send ourselves SIGSUSP */
1900 disableRawMode(current);
1901 raise(SIGTSTP);
1902 /* and resume */
1903 enableRawMode(current);
1904 refreshLine(current);
1905 #endif
1906 continue;
1907 case CHAR_DELETE: /* backspace */
1908 case ctrl('H'):
1909 if (remove_char(current, current->pos - 1) == 1) {
1910 refreshLine(current);
1912 break;
1913 case ctrl('D'): /* ctrl-d */
1914 if (sb_len(current->buf) == 0) {
1915 /* Empty line, so EOF */
1916 history_len--;
1917 free(history[history_len]);
1918 return -1;
1920 /* Otherwise fall through to delete char to right of cursor */
1921 case SPECIAL_DELETE:
1922 if (remove_char(current, current->pos) == 1) {
1923 refreshLine(current);
1925 break;
1926 case SPECIAL_INSERT:
1927 /* Ignore. Expansion Hook.
1928 * Future possibility: Toggle Insert/Overwrite Modes
1930 break;
1931 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1932 /* eat any spaces on the left */
1934 int pos = current->pos;
1935 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1936 pos--;
1939 /* now eat any non-spaces on the left */
1940 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1941 pos--;
1944 if (remove_chars(current, pos, current->pos - pos)) {
1945 refreshLine(current);
1948 break;
1949 case ctrl('T'): /* ctrl-t */
1950 if (current->pos > 0 && current->pos <= sb_chars(current->buf)) {
1951 /* If cursor is at end, transpose the previous two chars */
1952 int fixer = (current->pos == sb_chars(current->buf));
1953 c = get_char(current, current->pos - fixer);
1954 remove_char(current, current->pos - fixer);
1955 insert_char(current, current->pos - 1, c);
1956 refreshLine(current);
1958 break;
1959 case ctrl('V'): /* ctrl-v */
1960 /* Insert the ^V first */
1961 if (insert_char(current, current->pos, c)) {
1962 refreshLine(current);
1963 /* Now wait for the next char. Can insert anything except \0 */
1964 c = fd_read(current);
1966 /* Remove the ^V first */
1967 remove_char(current, current->pos - 1);
1968 if (c > 0) {
1969 /* Insert the actual char, can't be error or null */
1970 insert_char(current, current->pos, c);
1972 refreshLine(current);
1974 break;
1975 case ctrl('B'):
1976 case SPECIAL_LEFT:
1977 if (current->pos > 0) {
1978 current->pos--;
1979 refreshLine(current);
1981 break;
1982 case ctrl('F'):
1983 case SPECIAL_RIGHT:
1984 if (current->pos < sb_chars(current->buf)) {
1985 current->pos++;
1986 refreshLine(current);
1988 break;
1989 case SPECIAL_PAGE_UP:
1990 dir = history_len - history_index - 1; /* move to start of history */
1991 goto history_navigation;
1992 case SPECIAL_PAGE_DOWN:
1993 dir = -history_index; /* move to 0 == end of history, i.e. current */
1994 goto history_navigation;
1995 case ctrl('P'):
1996 case SPECIAL_UP:
1997 dir = 1;
1998 goto history_navigation;
1999 case ctrl('N'):
2000 case SPECIAL_DOWN:
2001 history_navigation:
2002 if (history_len > 1) {
2003 /* Update the current history entry before to
2004 * overwrite it with tne next one. */
2005 free(history[history_len - 1 - history_index]);
2006 history[history_len - 1 - history_index] = strdup(sb_str(current->buf));
2007 /* Show the new entry */
2008 history_index += dir;
2009 if (history_index < 0) {
2010 history_index = 0;
2011 break;
2012 } else if (history_index >= history_len) {
2013 history_index = history_len - 1;
2014 break;
2016 set_current(current, history[history_len - 1 - history_index]);
2017 refreshLine(current);
2019 break;
2020 case ctrl('A'): /* Ctrl+a, go to the start of the line */
2021 case SPECIAL_HOME:
2022 current->pos = 0;
2023 refreshLine(current);
2024 break;
2025 case ctrl('E'): /* ctrl+e, go to the end of the line */
2026 case SPECIAL_END:
2027 current->pos = sb_chars(current->buf);
2028 refreshLine(current);
2029 break;
2030 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
2031 if (remove_chars(current, 0, current->pos)) {
2032 refreshLine(current);
2034 break;
2035 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
2036 if (remove_chars(current, current->pos, sb_chars(current->buf) - current->pos)) {
2037 refreshLine(current);
2039 break;
2040 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
2041 if (current->capture && insert_chars(current, current->pos, sb_str(current->capture))) {
2042 refreshLine(current);
2044 break;
2045 case ctrl('L'): /* Ctrl+L, clear screen */
2046 linenoiseClearScreen();
2047 /* Force recalc of window size for serial terminals */
2048 current->cols = 0;
2049 current->rpos = 0;
2050 refreshLine(current);
2051 break;
2052 default:
2053 /* Only tab is allowed without ^V */
2054 if (c == '\t' || c >= ' ') {
2055 if (insert_char(current, current->pos, c) == 1) {
2056 refreshLine(current);
2059 break;
2062 return sb_len(current->buf);
2065 int linenoiseColumns(void)
2067 struct current current;
2068 current.output = NULL;
2069 enableRawMode (&current);
2070 getWindowSize (&current);
2071 disableRawMode (&current);
2072 return current.cols;
2076 * Reads a line from the file handle (without the trailing NL or CRNL)
2077 * and returns it in a stringbuf.
2078 * Returns NULL if no characters are read before EOF or error.
2080 * Note that the character count will *not* be correct for lines containing
2081 * utf8 sequences. Do not rely on the character count.
2083 static stringbuf *sb_getline(FILE *fh)
2085 stringbuf *sb = sb_alloc();
2086 int c;
2087 int n = 0;
2089 while ((c = getc(fh)) != EOF) {
2090 char ch;
2091 n++;
2092 if (c == '\r') {
2093 /* CRLF -> LF */
2094 continue;
2096 if (c == '\n' || c == '\r') {
2097 break;
2099 ch = c;
2100 /* ignore the effect of character count for partial utf8 sequences */
2101 sb_append_len(sb, &ch, 1);
2103 if (n == 0) {
2104 sb_free(sb);
2105 return NULL;
2107 return sb;
2110 char *linenoise(const char *prompt)
2112 int count;
2113 struct current current;
2114 stringbuf *sb;
2116 memset(&current, 0, sizeof(current));
2118 if (enableRawMode(&current) == -1) {
2119 printf("%s", prompt);
2120 fflush(stdout);
2121 sb = sb_getline(stdin);
2123 else {
2124 current.buf = sb_alloc();
2125 current.pos = 0;
2126 current.nrows = 1;
2127 current.prompt = prompt;
2129 count = linenoiseEdit(&current);
2131 disableRawMode(&current);
2132 printf("\n");
2134 sb_free(current.capture);
2135 if (count == -1) {
2136 sb_free(current.buf);
2137 return NULL;
2139 sb = current.buf;
2141 return sb ? sb_to_string(sb) : NULL;
2144 /* Using a circular buffer is smarter, but a bit more complex to handle. */
2145 int linenoiseHistoryAddAllocated(char *line) {
2147 if (history_max_len == 0) {
2148 notinserted:
2149 free(line);
2150 return 0;
2152 if (history == NULL) {
2153 history = (char **)calloc(sizeof(char*), history_max_len);
2156 /* do not insert duplicate lines into history */
2157 if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
2158 goto notinserted;
2161 if (history_len == history_max_len) {
2162 free(history[0]);
2163 memmove(history,history+1,sizeof(char*)*(history_max_len-1));
2164 history_len--;
2166 history[history_len] = line;
2167 history_len++;
2168 return 1;
2171 int linenoiseHistoryAdd(const char *line) {
2172 return linenoiseHistoryAddAllocated(strdup(line));
2175 int linenoiseHistoryGetMaxLen(void) {
2176 return history_max_len;
2179 int linenoiseHistorySetMaxLen(int len) {
2180 char **newHistory;
2182 if (len < 1) return 0;
2183 if (history) {
2184 int tocopy = history_len;
2186 newHistory = (char **)calloc(sizeof(char*), len);
2188 /* If we can't copy everything, free the elements we'll not use. */
2189 if (len < tocopy) {
2190 int j;
2192 for (j = 0; j < tocopy-len; j++) free(history[j]);
2193 tocopy = len;
2195 memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
2196 free(history);
2197 history = newHistory;
2199 history_max_len = len;
2200 if (history_len > history_max_len)
2201 history_len = history_max_len;
2202 return 1;
2205 /* Save the history in the specified file. On success 0 is returned
2206 * otherwise -1 is returned. */
2207 int linenoiseHistorySave(const char *filename) {
2208 FILE *fp = fopen(filename,"w");
2209 int j;
2211 if (fp == NULL) return -1;
2212 for (j = 0; j < history_len; j++) {
2213 const char *str = history[j];
2214 /* Need to encode backslash, nl and cr */
2215 while (*str) {
2216 if (*str == '\\') {
2217 fputs("\\\\", fp);
2219 else if (*str == '\n') {
2220 fputs("\\n", fp);
2222 else if (*str == '\r') {
2223 fputs("\\r", fp);
2225 else {
2226 fputc(*str, fp);
2228 str++;
2230 fputc('\n', fp);
2233 fclose(fp);
2234 return 0;
2237 /* Load the history from the specified file.
2239 * If the file does not exist or can't be opened, no operation is performed
2240 * and -1 is returned.
2241 * Otherwise 0 is returned.
2243 int linenoiseHistoryLoad(const char *filename) {
2244 FILE *fp = fopen(filename,"r");
2245 stringbuf *sb;
2247 if (fp == NULL) return -1;
2249 while ((sb = sb_getline(fp)) != NULL) {
2250 /* Take the stringbuf and decode backslash escaped values */
2251 char *buf = sb_to_string(sb);
2252 char *dest = buf;
2253 const char *src;
2255 for (src = buf; *src; src++) {
2256 char ch = *src;
2258 if (ch == '\\') {
2259 src++;
2260 if (*src == 'n') {
2261 ch = '\n';
2263 else if (*src == 'r') {
2264 ch = '\r';
2265 } else {
2266 ch = *src;
2269 *dest++ = ch;
2271 *dest = 0;
2273 linenoiseHistoryAddAllocated(buf);
2275 fclose(fp);
2276 return 0;
2279 /* Provide access to the history buffer.
2281 * If 'len' is not NULL, the length is stored in *len.
2283 char **linenoiseHistory(int *len) {
2284 if (len) {
2285 *len = history_len;
2287 return history;