1 /* linenoise.c -- guerrilla line editing library against the idea that a
2 * line editing lib needs to be 20,000 lines of C code.
4 * You can find the latest source code at:
6 * http://github.com/antirez/linenoise
8 * Does a number of crazy assumptions that happen to be true in 99.9999% of
9 * the 2010 UNIX computers around.
11 * ------------------------------------------------------------------------
13 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
14 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16 * All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
22 * * Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
25 * * Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 * ------------------------------------------------------------------------
44 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
49 * - Save and load history containing newlines
54 * List of escape sequences used by this program, we do everything just
55 * a few sequences. In order to be so cheap we may have some
56 * flickering effect with some slow terminal, but the lesser sequences
57 * the more compatible.
59 * CHA (Cursor Horizontal Absolute)
61 * Effect: moves cursor to column n (1 based)
65 * Effect: if n is 0 or missing, clear from cursor to end of line
66 * Effect: if n is 1, clear from beginning of line to cursor
67 * Effect: if n is 2, clear entire line
69 * CUF (CUrsor Forward)
71 * Effect: moves cursor forward of n chars
73 * The following are used to clear the screen: ESC [ H ESC [ 2 J
74 * This is actually composed of two sequences:
78 * Effect: moves the cursor to upper left corner
80 * ED2 (Clear entire screen)
82 * Effect: clear the whole screen
84 * == For highlighting control characters, we also use the following two ==
87 * Effect: Uses some standout mode such as reverse video
91 * Effect: Exit standout mode
93 * == Only used if TIOCGWINSZ fails ==
94 * DSR/CPR (Report cursor position)
96 * Effect: reports current cursor position as ESC [ NNN ; MMM R
102 #define USE_WINCONSOLE
105 #include <sys/ioctl.h>
106 #include <sys/poll.h>
117 #include <sys/types.h>
120 #include "linenoise.h"
122 #include "jim-config.h"
128 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
129 #define LINENOISE_MAX_LINE 4096
131 #define ctrl(C) ((C) - '@')
133 /* Use -ve numbers here to co-exist with normal unicode chars */
140 SPECIAL_DELETE
= -24,
145 static int history_max_len
= LINENOISE_DEFAULT_HISTORY_MAX_LEN
;
146 static int history_len
= 0;
147 static char **history
= NULL
;
149 /* Structure to contain the status of the current (being edited) line */
151 char *buf
; /* Current buffer. Always null terminated */
152 int bufmax
; /* Size of the buffer, including space for the null termination */
153 int len
; /* Number of bytes in 'buf' */
154 int chars
; /* Number of chars in 'buf' (utf-8 chars) */
155 int pos
; /* Cursor position, measured in chars */
156 int cols
; /* Size of the window, in chars */
158 #if defined(USE_TERMIOS)
159 int fd
; /* Terminal fd */
160 #elif defined(USE_WINCONSOLE)
161 HANDLE outh
; /* Console output handle */
162 HANDLE inh
; /* Console input handle */
163 int rows
; /* Screen rows */
164 int x
; /* Current column during output */
165 int y
; /* Current row */
169 static int fd_read(struct current
*current
);
170 static int getWindowSize(struct current
*current
);
172 void linenoiseHistoryFree(void) {
176 for (j
= 0; j
< history_len
; j
++)
183 #if defined(USE_TERMIOS)
184 static void linenoiseAtExit(void);
185 static struct termios orig_termios
; /* in order to restore at exit */
186 static int rawmode
= 0; /* for atexit() function to check if restore is needed*/
187 static int atexit_registered
= 0; /* register atexit just 1 time */
189 static const char *unsupported_term
[] = {"dumb","cons25",NULL
};
191 static int isUnsupportedTerm(void) {
192 char *term
= getenv("TERM");
196 for (j
= 0; unsupported_term
[j
]; j
++) {
197 if (strcasecmp(term
, unsupported_term
[j
]) == 0) {
205 static int enableRawMode(struct current
*current
) {
208 current
->fd
= STDIN_FILENO
;
210 if (!isatty(current
->fd
) || isUnsupportedTerm() ||
211 tcgetattr(current
->fd
, &orig_termios
) == -1) {
217 if (!atexit_registered
) {
218 atexit(linenoiseAtExit
);
219 atexit_registered
= 1;
222 raw
= orig_termios
; /* modify the original mode */
223 /* input modes: no break, no CR to NL, no parity check, no strip char,
224 * no start/stop output control. */
225 raw
.c_iflag
&= ~(BRKINT
| ICRNL
| INPCK
| ISTRIP
| IXON
);
226 /* output modes - disable post processing */
227 raw
.c_oflag
&= ~(OPOST
);
228 /* control modes - set 8 bit chars */
229 raw
.c_cflag
|= (CS8
);
230 /* local modes - choing off, canonical off, no extended functions,
231 * no signal chars (^Z,^C) */
232 raw
.c_lflag
&= ~(ECHO
| ICANON
| IEXTEN
| ISIG
);
233 /* control chars - set return condition: min number of bytes and timer.
234 * We want read to return every single byte, without timeout. */
235 raw
.c_cc
[VMIN
] = 1; raw
.c_cc
[VTIME
] = 0; /* 1 byte, no timer */
237 /* put terminal in raw mode after flushing */
238 if (tcsetattr(current
->fd
,TCSADRAIN
,&raw
) < 0) {
247 static void disableRawMode(struct current
*current
) {
248 /* Don't even check the return value as it's too late. */
249 if (rawmode
&& tcsetattr(current
->fd
,TCSADRAIN
,&orig_termios
) != -1)
253 /* At exit we'll try to fix the terminal to the initial conditions. */
254 static void linenoiseAtExit(void) {
256 tcsetattr(STDIN_FILENO
, TCSADRAIN
, &orig_termios
);
258 linenoiseHistoryFree();
261 /* gcc/glibc insists that we care about the return code of write! */
262 #define IGNORE_RC(EXPR) if (EXPR) {}
264 /* This is fdprintf() on some systems, but use a different
265 * name to avoid conflicts
267 static void fd_printf(int fd
, const char *format
, ...)
273 va_start(args
, format
);
274 n
= vsnprintf(buf
, sizeof(buf
), format
, args
);
276 IGNORE_RC(write(fd
, buf
, n
));
279 static void clearScreen(struct current
*current
)
281 fd_printf(current
->fd
, "\x1b[H\x1b[2J");
284 static void cursorToLeft(struct current
*current
)
286 fd_printf(current
->fd
, "\x1b[1G");
289 static int outputChars(struct current
*current
, const char *buf
, int len
)
291 return write(current
->fd
, buf
, len
);
294 static void outputControlChar(struct current
*current
, char ch
)
296 fd_printf(current
->fd
, "\033[7m^%c\033[0m", ch
);
299 static void eraseEol(struct current
*current
)
301 fd_printf(current
->fd
, "\x1b[0K");
304 static void setCursorPos(struct current
*current
, int x
)
306 fd_printf(current
->fd
, "\x1b[1G\x1b[%dC", x
);
310 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
312 * A timeout of -1 means to wait forever.
314 * Returns -1 if no char is received within the time or an error occurs.
316 static int fd_read_char(int fd
, int timeout
)
324 if (poll(&p
, 1, timeout
) == 0) {
328 if (read(fd
, &c
, 1) != 1) {
335 * Reads a complete utf-8 character
336 * and returns the unicode value, or -1 on error.
338 static int fd_read(struct current
*current
)
346 if (read(current
->fd
, &buf
[0], 1) != 1) {
349 n
= utf8_charlen(buf
[0]);
350 if (n
< 1 || n
> 3) {
353 for (i
= 1; i
< n
; i
++) {
354 if (read(current
->fd
, &buf
[i
], 1) != 1) {
359 /* decode and return the character */
360 utf8_tounicode(buf
, &c
);
363 return fd_read_char(current
->fd
, -1);
367 static int getWindowSize(struct current
*current
)
371 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) == 0 && ws
.ws_col
!= 0) {
372 current
->cols
= ws
.ws_col
;
376 /* Failed to query the window size. Perhaps we are on a serial terminal.
377 * Try to query the width by sending the cursor as far to the right
378 * and reading back the cursor position.
379 * Note that this is only done once per call to linenoise rather than
380 * every time the line is refreshed for efficiency reasons.
382 if (current
->cols
== 0) {
385 /* Move cursor far right and report cursor position */
386 fd_printf(current
->fd
, "\x1b[999G" "\x1b[6n");
388 /* Parse the response: ESC [ rows ; cols R */
389 if (fd_read_char(current
->fd
, 100) == 0x1b && fd_read_char(current
->fd
, 100) == '[') {
392 int ch
= fd_read_char(current
->fd
, 100);
397 else if (ch
== 'R') {
399 if (n
!= 0 && n
< 1000) {
404 else if (ch
>= 0 && ch
<= '9') {
405 n
= n
* 10 + ch
- '0';
417 * If escape (27) was received, reads subsequent
418 * chars to determine if this is a known special key.
420 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
422 * If no additional char is received within a short time,
425 static int check_special(int fd
)
427 int c
= fd_read_char(fd
, 50);
434 c2
= fd_read_char(fd
, 50);
438 if (c
== '[' || c
== 'O') {
439 /* Potential arrow key */
446 return SPECIAL_RIGHT
;
455 if (c
== '[' && c2
>= '1' && c2
<= '6') {
456 /* extended escape */
457 int c3
= fd_read_char(fd
, 50);
458 if (c2
== '3' && c3
== '~') {
459 /* delete char under cursor */
460 return SPECIAL_DELETE
;
462 while (c3
!= -1 && c3
!= '~') {
463 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
464 c3
= fd_read_char(fd
, 50);
470 #elif defined(USE_WINCONSOLE)
472 static DWORD orig_consolemode
= 0;
474 static int enableRawMode(struct current
*current
) {
478 current
->outh
= GetStdHandle(STD_OUTPUT_HANDLE
);
479 current
->inh
= GetStdHandle(STD_INPUT_HANDLE
);
481 if (!PeekConsoleInput(current
->inh
, &irec
, 1, &n
)) {
484 if (getWindowSize(current
) != 0) {
487 if (GetConsoleMode(current
->inh
, &orig_consolemode
)) {
488 SetConsoleMode(current
->inh
, ENABLE_PROCESSED_INPUT
);
493 static void disableRawMode(struct current
*current
)
495 SetConsoleMode(current
->inh
, orig_consolemode
);
498 static void clearScreen(struct current
*current
)
500 COORD topleft
= { 0, 0 };
503 FillConsoleOutputCharacter(current
->outh
, ' ',
504 current
->cols
* current
->rows
, topleft
, &n
);
505 FillConsoleOutputAttribute(current
->outh
,
506 FOREGROUND_RED
| FOREGROUND_BLUE
| FOREGROUND_GREEN
,
507 current
->cols
* current
->rows
, topleft
, &n
);
508 SetConsoleCursorPosition(current
->outh
, topleft
);
511 static void cursorToLeft(struct current
*current
)
513 COORD pos
= { 0, current
->y
};
516 FillConsoleOutputAttribute(current
->outh
,
517 FOREGROUND_RED
| FOREGROUND_BLUE
| FOREGROUND_GREEN
, current
->cols
, pos
, &n
);
521 static int outputChars(struct current
*current
, const char *buf
, int len
)
523 COORD pos
= { current
->x
, current
->y
};
524 WriteConsoleOutputCharacter(current
->outh
, buf
, len
, pos
, 0);
529 static void outputControlChar(struct current
*current
, char ch
)
531 COORD pos
= { current
->x
, current
->y
};
534 FillConsoleOutputAttribute(current
->outh
, BACKGROUND_INTENSITY
, 2, pos
, &n
);
535 outputChars(current
, "^", 1);
536 outputChars(current
, &ch
, 1);
539 static void eraseEol(struct current
*current
)
541 COORD pos
= { current
->x
, current
->y
};
544 FillConsoleOutputCharacter(current
->outh
, ' ', current
->cols
- current
->x
, pos
, &n
);
547 static void setCursorPos(struct current
*current
, int x
)
549 COORD pos
= { x
, current
->y
};
551 SetConsoleCursorPosition(current
->outh
, pos
);
555 static int fd_read(struct current
*current
)
560 if (WaitForSingleObject(current
->inh
, INFINITE
) != WAIT_OBJECT_0
) {
563 if (!ReadConsoleInput (current
->inh
, &irec
, 1, &n
)) {
566 if (irec
.EventType
== KEY_EVENT
&& irec
.Event
.KeyEvent
.bKeyDown
) {
567 KEY_EVENT_RECORD
*k
= &irec
.Event
.KeyEvent
;
568 if (k
->dwControlKeyState
& ENHANCED_KEY
) {
569 switch (k
->wVirtualKeyCode
) {
573 return SPECIAL_RIGHT
;
579 return SPECIAL_DELETE
;
586 /* Note that control characters are already translated in AsciiChar */
589 return k
->uChar
.UnicodeChar
;
591 return k
->uChar
.AsciiChar
;
599 static int getWindowSize(struct current
*current
)
601 CONSOLE_SCREEN_BUFFER_INFO info
;
602 if (!GetConsoleScreenBufferInfo(current
->outh
, &info
)) {
605 current
->cols
= info
.dwSize
.X
;
606 current
->rows
= info
.dwSize
.Y
;
607 if (current
->cols
<= 0 || current
->rows
<= 0) {
611 current
->y
= info
.dwCursorPosition
.Y
;
612 current
->x
= info
.dwCursorPosition
.X
;
617 static int utf8_getchars(char *buf
, int c
)
620 return utf8_fromunicode(buf
, c
);
628 * Returns the unicode character at the given offset,
631 static int get_char(struct current
*current
, int pos
)
633 if (pos
>= 0 && pos
< current
->chars
) {
635 int i
= utf8_index(current
->buf
, pos
);
636 (void)utf8_tounicode(current
->buf
+ i
, &c
);
642 static void refreshLine(const char *prompt
, struct current
*current
)
648 const char *buf
= current
->buf
;
649 int chars
= current
->chars
;
650 int pos
= current
->pos
;
655 /* Should intercept SIGWINCH. For now, just get the size every time */
656 getWindowSize(current
);
658 plen
= strlen(prompt
);
659 pchars
= utf8_strlen(prompt
, plen
);
661 /* Account for a line which is too long to fit in the window.
662 * Note that control chars require an extra column
665 /* How many cols are required to the left of 'pos'?
666 * The prompt, plus one extra for each control char
668 n
= pchars
+ utf8_strlen(buf
, current
->len
);
670 for (i
= 0; i
< pos
; i
++) {
671 b
+= utf8_tounicode(buf
+ b
, &ch
);
677 /* If too many are need, strip chars off the front of 'buf'
678 * until it fits. Note that if the current char is a control character,
679 * we need one extra col.
681 if (current
->pos
< current
->chars
&& get_char(current
, current
->pos
) < ' ') {
685 while (n
>= current
->cols
) {
686 b
= utf8_tounicode(buf
, &ch
);
696 /* Cursor to left edge, then the prompt */
697 cursorToLeft(current
);
698 outputChars(current
, prompt
, plen
);
700 /* Now the current buffer content */
702 /* Need special handling for control characters.
703 * If we hit 'cols', stop.
705 b
= 0; /* unwritted bytes */
706 n
= 0; /* How many control chars were written */
707 for (i
= 0; i
< chars
; i
++) {
709 int w
= utf8_tounicode(buf
+ b
, &ch
);
713 if (pchars
+ i
+ n
>= current
->cols
) {
717 /* A control character, so write the buffer so far */
718 outputChars(current
, buf
, b
);
721 outputControlChar(current
, ch
+ '@');
730 outputChars(current
, buf
, b
);
732 /* Erase to right, move cursor to original position */
734 setCursorPos(current
, pos
+ pchars
+ backup
);
737 static void set_current(struct current
*current
, const char *str
)
739 strncpy(current
->buf
, str
, current
->bufmax
);
740 current
->buf
[current
->bufmax
- 1] = 0;
741 current
->len
= strlen(current
->buf
);
742 current
->pos
= current
->chars
= utf8_strlen(current
->buf
, current
->len
);
745 static int has_room(struct current
*current
, int bytes
)
747 return current
->len
+ bytes
< current
->bufmax
- 1;
751 * Removes the char at 'pos'.
753 * Returns 1 if the line needs to be refreshed, 2 if not
754 * and 0 if nothing was removed
756 static int remove_char(struct current
*current
, int pos
)
758 if (pos
>= 0 && pos
< current
->chars
) {
761 p1
= utf8_index(current
->buf
, pos
);
762 p2
= p1
+ utf8_index(current
->buf
+ p1
, 1);
765 /* optimise remove char in the case of removing the last char */
766 if (current
->pos
== pos
+ 1 && current
->pos
== current
->chars
) {
767 if (current
->buf
[pos
] >= ' ' && utf8_strlen(current
->prompt
, -1) + utf8_strlen(current
->buf
, current
->len
) < current
->cols
- 1) {
769 fd_printf(current
->fd
, "\b \b");
774 /* Move the null char too */
775 memmove(current
->buf
+ p1
, current
->buf
+ p2
, current
->len
- p2
+ 1);
776 current
->len
-= (p2
- p1
);
779 if (current
->pos
> pos
) {
788 * Insert 'ch' at position 'pos'
790 * Returns 1 if the line needs to be refreshed, 2 if not
791 * and 0 if nothing was inserted (no room)
793 static int insert_char(struct current
*current
, int pos
, int ch
)
796 int n
= utf8_getchars(buf
, ch
);
798 if (has_room(current
, n
) && pos
>= 0 && pos
<= current
->chars
) {
801 p1
= utf8_index(current
->buf
, pos
);
805 /* optimise the case where adding a single char to the end and no scrolling is needed */
806 if (current
->pos
== pos
&& current
->chars
== pos
) {
807 if (ch
>= ' ' && utf8_strlen(current
->prompt
, -1) + utf8_strlen(current
->buf
, current
->len
) < current
->cols
- 1) {
808 IGNORE_RC(write(current
->fd
, buf
, n
));
814 memmove(current
->buf
+ p2
, current
->buf
+ p1
, current
->len
- p1
);
815 memcpy(current
->buf
+ p1
, buf
, n
);
819 if (current
->pos
>= pos
) {
828 * Returns 0 if no chars were removed or non-zero otherwise.
830 static int remove_chars(struct current
*current
, int pos
, int n
)
833 while (n
-- && remove_char(current
, pos
)) {
839 #ifndef NO_COMPLETION
840 static linenoiseCompletionCallback
*completionCallback
= NULL
;
844 fprintf(stderr
, "\x7");
849 static void freeCompletions(linenoiseCompletions
*lc
) {
851 for (i
= 0; i
< lc
->len
; i
++)
856 static int completeLine(struct current
*current
) {
857 linenoiseCompletions lc
= { 0, NULL
};
860 completionCallback(current
->buf
,&lc
);
864 size_t stop
= 0, i
= 0;
867 /* Show completion or original buffer */
869 struct current tmp
= *current
;
870 tmp
.buf
= lc
.cvec
[i
];
871 tmp
.pos
= tmp
.len
= strlen(tmp
.buf
);
872 tmp
.chars
= utf8_strlen(tmp
.buf
, tmp
.len
);
873 refreshLine(current
->prompt
, &tmp
);
875 refreshLine(current
->prompt
, current
);
878 c
= fd_read(current
);
885 i
= (i
+1) % (lc
.len
+1);
886 if (i
== lc
.len
) beep();
888 case 27: /* escape */
889 /* Re-show original buffer */
891 refreshLine(current
->prompt
, current
);
896 /* Update buffer and return */
898 set_current(current
,lc
.cvec
[i
]);
906 freeCompletions(&lc
);
907 return c
; /* Return last read character */
910 /* Register a callback function to be called for tab-completion. */
911 void linenoiseSetCompletionCallback(linenoiseCompletionCallback
*fn
) {
912 completionCallback
= fn
;
915 void linenoiseAddCompletion(linenoiseCompletions
*lc
, const char *str
) {
916 lc
->cvec
= (char **)realloc(lc
->cvec
,sizeof(char*)*(lc
->len
+1));
917 lc
->cvec
[lc
->len
++] = strdup(str
);
922 static int linenoisePrompt(struct current
*current
) {
923 int history_index
= 0;
925 /* The latest history entry is always our current buffer, that
926 * initially is just an empty string. */
927 linenoiseHistoryAdd("");
929 set_current(current
, "");
930 refreshLine(current
->prompt
, current
);
934 int c
= fd_read(current
);
936 #ifndef NO_COMPLETION
937 /* Only autocomplete when the callback is set. It returns < 0 when
938 * there was an error reading from fd. Otherwise it will return the
939 * character that should be handled next. */
940 if (c
== 9 && completionCallback
!= NULL
) {
941 c
= completeLine(current
);
942 /* Return on errors */
943 if (c
< 0) return current
->len
;
944 /* Read next character when 0 */
945 if (c
== 0) continue;
950 if (c
== -1) return current
->len
;
952 if (c
== 27) { /* escape sequence */
953 c
= check_special(current
->fd
);
957 case '\r': /* enter */
959 free(history
[history_len
]);
961 case ctrl('C'): /* ctrl-c */
964 case 127: /* backspace */
966 if (remove_char(current
, current
->pos
- 1) == 1) {
967 refreshLine(current
->prompt
, current
);
970 case ctrl('D'): /* ctrl-d */
971 if (current
->len
== 0) {
972 /* Empty line, so EOF */
974 free(history
[history_len
]);
977 /* Otherwise delete char to right of cursor */
978 if (remove_char(current
, current
->pos
)) {
979 refreshLine(current
->prompt
, current
);
982 case ctrl('W'): /* ctrl-w */
983 /* eat any spaces on the left */
985 int pos
= current
->pos
;
986 while (pos
> 0 && get_char(current
, pos
- 1) == ' ') {
990 /* now eat any non-spaces on the left */
991 while (pos
> 0 && get_char(current
, pos
- 1) != ' ') {
995 if (remove_chars(current
, pos
, current
->pos
- pos
)) {
996 refreshLine(current
->prompt
, current
);
1000 case ctrl('R'): /* ctrl-r */
1002 /* Display the reverse-i-search prompt and process chars */
1007 int searchpos
= history_len
- 1;
1012 const char *p
= NULL
;
1016 snprintf(rprompt
, sizeof(rprompt
), "(reverse-i-search)'%s': ", rbuf
);
1017 refreshLine(rprompt
, current
);
1018 c
= fd_read(current
);
1019 if (c
== ctrl('H') || c
== 127) {
1021 int p
= utf8_index(rbuf
, --rchars
);
1023 rlen
= strlen(rbuf
);
1029 c
= check_special(current
->fd
);
1032 if (c
== ctrl('P') || c
== SPECIAL_UP
) {
1033 /* Search for the previous (earlier) match */
1034 if (searchpos
> 0) {
1039 else if (c
== ctrl('N') || c
== SPECIAL_DOWN
) {
1040 /* Search for the next (later) match */
1041 if (searchpos
< history_len
) {
1047 else if (c
>= ' ') {
1048 if (rlen
>= (int)sizeof(rbuf
) + 3) {
1052 n
= utf8_getchars(rbuf
+ rlen
, c
);
1057 /* Adding a new char resets the search location */
1058 searchpos
= history_len
- 1;
1061 /* Exit from incremental search mode */
1065 /* Now search through the history for a match */
1066 for (; searchpos
>= 0 && searchpos
< history_len
; searchpos
+= searchdir
) {
1067 p
= strstr(history
[searchpos
], rbuf
);
1070 if (skipsame
&& strcmp(history
[searchpos
], current
->buf
) == 0) {
1071 /* But it is identical, so skip it */
1074 /* Copy the matching line and set the cursor position */
1075 set_current(current
,history
[searchpos
]);
1076 current
->pos
= utf8_strlen(history
[searchpos
], p
- history
[searchpos
]);
1081 /* No match, so don't add it */
1087 if (c
== ctrl('G') || c
== ctrl('C')) {
1088 /* ctrl-g terminates the search with no effect */
1089 set_current(current
, "");
1092 else if (c
== ctrl('J')) {
1093 /* ctrl-j terminates the search leaving the buffer in place */
1096 /* Go process the char normally */
1097 refreshLine(current
->prompt
, current
);
1101 case ctrl('T'): /* ctrl-t */
1102 if (current
->pos
> 0 && current
->pos
< current
->chars
) {
1103 c
= get_char(current
, current
->pos
);
1104 remove_char(current
, current
->pos
);
1105 insert_char(current
, current
->pos
- 1, c
);
1106 refreshLine(current
->prompt
, current
);
1109 case ctrl('V'): /* ctrl-v */
1110 if (has_room(current
, 3)) {
1111 /* Insert the ^V first */
1112 if (insert_char(current
, current
->pos
, c
)) {
1113 refreshLine(current
->prompt
, current
);
1114 /* Now wait for the next char. Can insert anything except \0 */
1115 c
= fd_read(current
);
1117 /* Remove the ^V first */
1118 remove_char(current
, current
->pos
- 1);
1120 /* Insert the actual char */
1121 insert_char(current
, current
->pos
, c
);
1123 refreshLine(current
->prompt
, current
);
1129 if (current
->pos
> 0) {
1131 refreshLine(current
->prompt
, current
);
1136 if (current
->pos
< current
->chars
) {
1138 refreshLine(current
->prompt
, current
);
1146 if (history_len
> 1) {
1147 /* Update the current history entry before to
1148 * overwrite it with tne next one. */
1149 free(history
[history_len
-1-history_index
]);
1150 history
[history_len
-1-history_index
] = strdup(current
->buf
);
1151 /* Show the new entry */
1152 history_index
+= dir
;
1153 if (history_index
< 0) {
1156 } else if (history_index
>= history_len
) {
1157 history_index
= history_len
-1;
1160 set_current(current
, history
[history_len
-1-history_index
]);
1161 refreshLine(current
->prompt
, current
);
1165 case SPECIAL_DELETE
:
1166 if (remove_char(current
, current
->pos
) == 1) {
1167 refreshLine(current
->prompt
, current
);
1172 refreshLine(current
->prompt
, current
);
1175 current
->pos
= current
->chars
;
1176 refreshLine(current
->prompt
, current
);
1179 /* Only tab is allowed without ^V */
1180 if (c
== '\t' || c
>= ' ') {
1181 if (insert_char(current
, current
->pos
, c
) == 1) {
1182 refreshLine(current
->prompt
, current
);
1186 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1187 if (remove_chars(current
, 0, current
->pos
)) {
1188 refreshLine(current
->prompt
, current
);
1191 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1192 if (remove_chars(current
, current
->pos
, current
->chars
- current
->pos
)) {
1193 refreshLine(current
->prompt
, current
);
1196 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1198 refreshLine(current
->prompt
, current
);
1200 case ctrl('E'): /* ctrl+e, go to the end of the line */
1201 current
->pos
= current
->chars
;
1202 refreshLine(current
->prompt
, current
);
1204 case ctrl('L'): /* Ctrl+L, clear screen */
1206 clearScreen(current
);
1207 /* Force recalc of window size for serial terminals */
1209 refreshLine(current
->prompt
, current
);
1213 return current
->len
;
1216 char *linenoise(const char *prompt
)
1219 struct current current
;
1220 char buf
[LINENOISE_MAX_LINE
];
1222 if (enableRawMode(¤t
) == -1) {
1223 printf("%s", prompt
);
1225 if (fgets(buf
, sizeof(buf
), stdin
) == NULL
) {
1228 count
= strlen(buf
);
1229 if (count
&& buf
[count
-1] == '\n') {
1237 current
.bufmax
= sizeof(buf
);
1241 current
.prompt
= prompt
;
1243 count
= linenoisePrompt(¤t
);
1244 disableRawMode(¤t
);
1253 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1254 int linenoiseHistoryAdd(const char *line
) {
1257 if (history_max_len
== 0) return 0;
1258 if (history
== NULL
) {
1259 history
= (char**)malloc(sizeof(char*)*history_max_len
);
1260 if (history
== NULL
) return 0;
1261 memset(history
,0,(sizeof(char*)*history_max_len
));
1263 linecopy
= strdup(line
);
1264 if (!linecopy
) return 0;
1265 if (history_len
== history_max_len
) {
1267 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
1270 history
[history_len
] = linecopy
;
1275 int linenoiseHistorySetMaxLen(int len
) {
1278 if (len
< 1) return 0;
1280 int tocopy
= history_len
;
1282 newHistory
= (char**)malloc(sizeof(char*)*len
);
1283 if (newHistory
== NULL
) return 0;
1284 if (len
< tocopy
) tocopy
= len
;
1285 memcpy(newHistory
,history
+(history_max_len
-tocopy
), sizeof(char*)*tocopy
);
1287 history
= newHistory
;
1289 history_max_len
= len
;
1290 if (history_len
> history_max_len
)
1291 history_len
= history_max_len
;
1295 /* Save the history in the specified file. On success 0 is returned
1296 * otherwise -1 is returned. */
1297 int linenoiseHistorySave(const char *filename
) {
1298 FILE *fp
= fopen(filename
,"w");
1301 if (fp
== NULL
) return -1;
1302 for (j
= 0; j
< history_len
; j
++) {
1303 const char *str
= history
[j
];
1304 /* Need to encode backslash, nl and cr */
1309 else if (*str
== '\n') {
1312 else if (*str
== '\r') {
1327 /* Load the history from the specified file. If the file does not exist
1328 * zero is returned and no operation is performed.
1330 * If the file exists and the operation succeeded 0 is returned, otherwise
1331 * on error -1 is returned. */
1332 int linenoiseHistoryLoad(const char *filename
) {
1333 FILE *fp
= fopen(filename
,"r");
1334 char buf
[LINENOISE_MAX_LINE
];
1336 if (fp
== NULL
) return -1;
1338 while (fgets(buf
,LINENOISE_MAX_LINE
,fp
) != NULL
) {
1341 /* Decode backslash escaped values */
1342 for (src
= dest
= buf
; *src
; src
++) {
1350 else if (*src
== 'r') {
1358 /* Remove trailing newline */
1359 if (dest
!= buf
&& (dest
[-1] == '\n' || dest
[-1] == '\r')) {
1364 linenoiseHistoryAdd(buf
);
1370 /* Provide access to the history buffer.
1372 * If 'len' is not NULL, the length is stored in *len.
1374 char **linenoiseHistory(int *len
) {