1 /* linenoise.c -- guerrilla line editing library against the idea that a
2 * line editing lib needs to be 20,000 lines of C code.
4 * You can find the latest source code at:
6 * http://github.com/msteveb/linenoise
7 * (forked from http://github.com/antirez/linenoise)
9 * Does a number of crazy assumptions that happen to be true in 99.9999% of
10 * the 2010 UNIX computers around.
12 * ------------------------------------------------------------------------
14 * Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
15 * Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
16 * Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
18 * All rights reserved.
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions are
24 * * Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
27 * * Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 * ------------------------------------------------------------------------
46 * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47 * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
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
100 * If __MINGW32__ is defined, the win32 console API is used.
101 * This could probably be made to work for the msvc compiler too.
102 * This support based in part on work by Jon Griffiths.
108 #define USE_WINCONSOLE
111 #include <sys/ioctl.h>
112 #include <sys/poll.h>
123 #include <sys/types.h>
126 #include "linenoise.h"
128 #include "jim-config.h"
134 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
135 #define LINENOISE_MAX_LINE 4096
137 #define ctrl(C) ((C) - '@')
139 /* Use -ve numbers here to co-exist with normal unicode chars */
146 SPECIAL_DELETE
= -24,
151 static int history_max_len
= LINENOISE_DEFAULT_HISTORY_MAX_LEN
;
152 static int history_len
= 0;
153 static char **history
= NULL
;
155 /* Structure to contain the status of the current (being edited) line */
157 char *buf
; /* Current buffer. Always null terminated */
158 int bufmax
; /* Size of the buffer, including space for the null termination */
159 int len
; /* Number of bytes in 'buf' */
160 int chars
; /* Number of chars in 'buf' (utf-8 chars) */
161 int pos
; /* Cursor position, measured in chars */
162 int cols
; /* Size of the window, in chars */
164 #if defined(USE_TERMIOS)
165 int fd
; /* Terminal fd */
166 #elif defined(USE_WINCONSOLE)
167 HANDLE outh
; /* Console output handle */
168 HANDLE inh
; /* Console input handle */
169 int rows
; /* Screen rows */
170 int x
; /* Current column during output */
171 int y
; /* Current row */
175 static int fd_read(struct current
*current
);
176 static int getWindowSize(struct current
*current
);
178 void linenoiseHistoryFree(void) {
182 for (j
= 0; j
< history_len
; j
++)
189 #if defined(USE_TERMIOS)
190 static void linenoiseAtExit(void);
191 static struct termios orig_termios
; /* in order to restore at exit */
192 static int rawmode
= 0; /* for atexit() function to check if restore is needed*/
193 static int atexit_registered
= 0; /* register atexit just 1 time */
195 static const char *unsupported_term
[] = {"dumb","cons25",NULL
};
197 static int isUnsupportedTerm(void) {
198 char *term
= getenv("TERM");
202 for (j
= 0; unsupported_term
[j
]; j
++) {
203 if (strcasecmp(term
, unsupported_term
[j
]) == 0) {
211 static int enableRawMode(struct current
*current
) {
214 current
->fd
= STDIN_FILENO
;
216 if (!isatty(current
->fd
) || isUnsupportedTerm() ||
217 tcgetattr(current
->fd
, &orig_termios
) == -1) {
223 if (!atexit_registered
) {
224 atexit(linenoiseAtExit
);
225 atexit_registered
= 1;
228 raw
= orig_termios
; /* modify the original mode */
229 /* input modes: no break, no CR to NL, no parity check, no strip char,
230 * no start/stop output control. */
231 raw
.c_iflag
&= ~(BRKINT
| ICRNL
| INPCK
| ISTRIP
| IXON
);
232 /* output modes - disable post processing */
233 raw
.c_oflag
&= ~(OPOST
);
234 /* control modes - set 8 bit chars */
235 raw
.c_cflag
|= (CS8
);
236 /* local modes - choing off, canonical off, no extended functions,
237 * no signal chars (^Z,^C) */
238 raw
.c_lflag
&= ~(ECHO
| ICANON
| IEXTEN
| ISIG
);
239 /* control chars - set return condition: min number of bytes and timer.
240 * We want read to return every single byte, without timeout. */
241 raw
.c_cc
[VMIN
] = 1; raw
.c_cc
[VTIME
] = 0; /* 1 byte, no timer */
243 /* put terminal in raw mode after flushing */
244 if (tcsetattr(current
->fd
,TCSADRAIN
,&raw
) < 0) {
253 static void disableRawMode(struct current
*current
) {
254 /* Don't even check the return value as it's too late. */
255 if (rawmode
&& tcsetattr(current
->fd
,TCSADRAIN
,&orig_termios
) != -1)
259 /* At exit we'll try to fix the terminal to the initial conditions. */
260 static void linenoiseAtExit(void) {
262 tcsetattr(STDIN_FILENO
, TCSADRAIN
, &orig_termios
);
264 linenoiseHistoryFree();
267 /* gcc/glibc insists that we care about the return code of write! */
268 #define IGNORE_RC(EXPR) if (EXPR) {}
270 /* This is fdprintf() on some systems, but use a different
271 * name to avoid conflicts
273 static void fd_printf(int fd
, const char *format
, ...)
279 va_start(args
, format
);
280 n
= vsnprintf(buf
, sizeof(buf
), format
, args
);
282 IGNORE_RC(write(fd
, buf
, n
));
285 static void clearScreen(struct current
*current
)
287 fd_printf(current
->fd
, "\x1b[H\x1b[2J");
290 static void cursorToLeft(struct current
*current
)
292 fd_printf(current
->fd
, "\x1b[1G");
295 static int outputChars(struct current
*current
, const char *buf
, int len
)
297 return write(current
->fd
, buf
, len
);
300 static void outputControlChar(struct current
*current
, char ch
)
302 fd_printf(current
->fd
, "\033[7m^%c\033[0m", ch
);
305 static void eraseEol(struct current
*current
)
307 fd_printf(current
->fd
, "\x1b[0K");
310 static void setCursorPos(struct current
*current
, int x
)
312 fd_printf(current
->fd
, "\x1b[1G\x1b[%dC", x
);
316 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
318 * A timeout of -1 means to wait forever.
320 * Returns -1 if no char is received within the time or an error occurs.
322 static int fd_read_char(int fd
, int timeout
)
330 if (poll(&p
, 1, timeout
) == 0) {
334 if (read(fd
, &c
, 1) != 1) {
341 * Reads a complete utf-8 character
342 * and returns the unicode value, or -1 on error.
344 static int fd_read(struct current
*current
)
352 if (read(current
->fd
, &buf
[0], 1) != 1) {
355 n
= utf8_charlen(buf
[0]);
356 if (n
< 1 || n
> 3) {
359 for (i
= 1; i
< n
; i
++) {
360 if (read(current
->fd
, &buf
[i
], 1) != 1) {
365 /* decode and return the character */
366 utf8_tounicode(buf
, &c
);
369 return fd_read_char(current
->fd
, -1);
373 static int getWindowSize(struct current
*current
)
377 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) == 0 && ws
.ws_col
!= 0) {
378 current
->cols
= ws
.ws_col
;
382 /* Failed to query the window size. Perhaps we are on a serial terminal.
383 * Try to query the width by sending the cursor as far to the right
384 * and reading back the cursor position.
385 * Note that this is only done once per call to linenoise rather than
386 * every time the line is refreshed for efficiency reasons.
388 if (current
->cols
== 0) {
391 /* Move cursor far right and report cursor position */
392 fd_printf(current
->fd
, "\x1b[999G" "\x1b[6n");
394 /* Parse the response: ESC [ rows ; cols R */
395 if (fd_read_char(current
->fd
, 100) == 0x1b && fd_read_char(current
->fd
, 100) == '[') {
398 int ch
= fd_read_char(current
->fd
, 100);
403 else if (ch
== 'R') {
405 if (n
!= 0 && n
< 1000) {
410 else if (ch
>= 0 && ch
<= '9') {
411 n
= n
* 10 + ch
- '0';
423 * If escape (27) was received, reads subsequent
424 * chars to determine if this is a known special key.
426 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
428 * If no additional char is received within a short time,
431 static int check_special(int fd
)
433 int c
= fd_read_char(fd
, 50);
440 c2
= fd_read_char(fd
, 50);
444 if (c
== '[' || c
== 'O') {
445 /* Potential arrow key */
452 return SPECIAL_RIGHT
;
461 if (c
== '[' && c2
>= '1' && c2
<= '8') {
462 /* extended escape */
463 c
= fd_read_char(fd
, 50);
467 return SPECIAL_DELETE
;
474 while (c
!= -1 && c
!= '~') {
475 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
476 c
= fd_read_char(fd
, 50);
482 #elif defined(USE_WINCONSOLE)
484 static DWORD orig_consolemode
= 0;
486 static int enableRawMode(struct current
*current
) {
490 current
->outh
= GetStdHandle(STD_OUTPUT_HANDLE
);
491 current
->inh
= GetStdHandle(STD_INPUT_HANDLE
);
493 if (!PeekConsoleInput(current
->inh
, &irec
, 1, &n
)) {
496 if (getWindowSize(current
) != 0) {
499 if (GetConsoleMode(current
->inh
, &orig_consolemode
)) {
500 SetConsoleMode(current
->inh
, ENABLE_PROCESSED_INPUT
);
505 static void disableRawMode(struct current
*current
)
507 SetConsoleMode(current
->inh
, orig_consolemode
);
510 static void clearScreen(struct current
*current
)
512 COORD topleft
= { 0, 0 };
515 FillConsoleOutputCharacter(current
->outh
, ' ',
516 current
->cols
* current
->rows
, topleft
, &n
);
517 FillConsoleOutputAttribute(current
->outh
,
518 FOREGROUND_RED
| FOREGROUND_BLUE
| FOREGROUND_GREEN
,
519 current
->cols
* current
->rows
, topleft
, &n
);
520 SetConsoleCursorPosition(current
->outh
, topleft
);
523 static void cursorToLeft(struct current
*current
)
525 COORD pos
= { 0, current
->y
};
528 FillConsoleOutputAttribute(current
->outh
,
529 FOREGROUND_RED
| FOREGROUND_BLUE
| FOREGROUND_GREEN
, current
->cols
, pos
, &n
);
533 static int outputChars(struct current
*current
, const char *buf
, int len
)
535 COORD pos
= { current
->x
, current
->y
};
536 WriteConsoleOutputCharacter(current
->outh
, buf
, len
, pos
, 0);
541 static void outputControlChar(struct current
*current
, char ch
)
543 COORD pos
= { current
->x
, current
->y
};
546 FillConsoleOutputAttribute(current
->outh
, BACKGROUND_INTENSITY
, 2, pos
, &n
);
547 outputChars(current
, "^", 1);
548 outputChars(current
, &ch
, 1);
551 static void eraseEol(struct current
*current
)
553 COORD pos
= { current
->x
, current
->y
};
556 FillConsoleOutputCharacter(current
->outh
, ' ', current
->cols
- current
->x
, pos
, &n
);
559 static void setCursorPos(struct current
*current
, int x
)
561 COORD pos
= { x
, current
->y
};
563 SetConsoleCursorPosition(current
->outh
, pos
);
567 static int fd_read(struct current
*current
)
572 if (WaitForSingleObject(current
->inh
, INFINITE
) != WAIT_OBJECT_0
) {
575 if (!ReadConsoleInput (current
->inh
, &irec
, 1, &n
)) {
578 if (irec
.EventType
== KEY_EVENT
&& irec
.Event
.KeyEvent
.bKeyDown
) {
579 KEY_EVENT_RECORD
*k
= &irec
.Event
.KeyEvent
;
580 if (k
->dwControlKeyState
& ENHANCED_KEY
) {
581 switch (k
->wVirtualKeyCode
) {
585 return SPECIAL_RIGHT
;
591 return SPECIAL_DELETE
;
598 /* Note that control characters are already translated in AsciiChar */
601 return k
->uChar
.UnicodeChar
;
603 return k
->uChar
.AsciiChar
;
611 static int getWindowSize(struct current
*current
)
613 CONSOLE_SCREEN_BUFFER_INFO info
;
614 if (!GetConsoleScreenBufferInfo(current
->outh
, &info
)) {
617 current
->cols
= info
.dwSize
.X
;
618 current
->rows
= info
.dwSize
.Y
;
619 if (current
->cols
<= 0 || current
->rows
<= 0) {
623 current
->y
= info
.dwCursorPosition
.Y
;
624 current
->x
= info
.dwCursorPosition
.X
;
629 static int utf8_getchars(char *buf
, int c
)
632 return utf8_fromunicode(buf
, c
);
640 * Returns the unicode character at the given offset,
643 static int get_char(struct current
*current
, int pos
)
645 if (pos
>= 0 && pos
< current
->chars
) {
647 int i
= utf8_index(current
->buf
, pos
);
648 (void)utf8_tounicode(current
->buf
+ i
, &c
);
654 static void refreshLine(const char *prompt
, struct current
*current
)
660 const char *buf
= current
->buf
;
661 int chars
= current
->chars
;
662 int pos
= current
->pos
;
667 /* Should intercept SIGWINCH. For now, just get the size every time */
668 getWindowSize(current
);
670 plen
= strlen(prompt
);
671 pchars
= utf8_strlen(prompt
, plen
);
673 /* Account for a line which is too long to fit in the window.
674 * Note that control chars require an extra column
677 /* How many cols are required to the left of 'pos'?
678 * The prompt, plus one extra for each control char
680 n
= pchars
+ utf8_strlen(buf
, current
->len
);
682 for (i
= 0; i
< pos
; i
++) {
683 b
+= utf8_tounicode(buf
+ b
, &ch
);
689 /* If too many are need, strip chars off the front of 'buf'
690 * until it fits. Note that if the current char is a control character,
691 * we need one extra col.
693 if (current
->pos
< current
->chars
&& get_char(current
, current
->pos
) < ' ') {
697 while (n
>= current
->cols
) {
698 b
= utf8_tounicode(buf
, &ch
);
708 /* Cursor to left edge, then the prompt */
709 cursorToLeft(current
);
710 outputChars(current
, prompt
, plen
);
712 /* Now the current buffer content */
714 /* Need special handling for control characters.
715 * If we hit 'cols', stop.
717 b
= 0; /* unwritted bytes */
718 n
= 0; /* How many control chars were written */
719 for (i
= 0; i
< chars
; i
++) {
721 int w
= utf8_tounicode(buf
+ b
, &ch
);
725 if (pchars
+ i
+ n
>= current
->cols
) {
729 /* A control character, so write the buffer so far */
730 outputChars(current
, buf
, b
);
733 outputControlChar(current
, ch
+ '@');
742 outputChars(current
, buf
, b
);
744 /* Erase to right, move cursor to original position */
746 setCursorPos(current
, pos
+ pchars
+ backup
);
749 static void set_current(struct current
*current
, const char *str
)
751 strncpy(current
->buf
, str
, current
->bufmax
);
752 current
->buf
[current
->bufmax
- 1] = 0;
753 current
->len
= strlen(current
->buf
);
754 current
->pos
= current
->chars
= utf8_strlen(current
->buf
, current
->len
);
757 static int has_room(struct current
*current
, int bytes
)
759 return current
->len
+ bytes
< current
->bufmax
- 1;
763 * Removes the char at 'pos'.
765 * Returns 1 if the line needs to be refreshed, 2 if not
766 * and 0 if nothing was removed
768 static int remove_char(struct current
*current
, int pos
)
770 if (pos
>= 0 && pos
< current
->chars
) {
773 p1
= utf8_index(current
->buf
, pos
);
774 p2
= p1
+ utf8_index(current
->buf
+ p1
, 1);
777 /* optimise remove char in the case of removing the last char */
778 if (current
->pos
== pos
+ 1 && current
->pos
== current
->chars
) {
779 if (current
->buf
[pos
] >= ' ' && utf8_strlen(current
->prompt
, -1) + utf8_strlen(current
->buf
, current
->len
) < current
->cols
- 1) {
781 fd_printf(current
->fd
, "\b \b");
786 /* Move the null char too */
787 memmove(current
->buf
+ p1
, current
->buf
+ p2
, current
->len
- p2
+ 1);
788 current
->len
-= (p2
- p1
);
791 if (current
->pos
> pos
) {
800 * Insert 'ch' at position 'pos'
802 * Returns 1 if the line needs to be refreshed, 2 if not
803 * and 0 if nothing was inserted (no room)
805 static int insert_char(struct current
*current
, int pos
, int ch
)
808 int n
= utf8_getchars(buf
, ch
);
810 if (has_room(current
, n
) && pos
>= 0 && pos
<= current
->chars
) {
813 p1
= utf8_index(current
->buf
, pos
);
817 /* optimise the case where adding a single char to the end and no scrolling is needed */
818 if (current
->pos
== pos
&& current
->chars
== pos
) {
819 if (ch
>= ' ' && utf8_strlen(current
->prompt
, -1) + utf8_strlen(current
->buf
, current
->len
) < current
->cols
- 1) {
820 IGNORE_RC(write(current
->fd
, buf
, n
));
826 memmove(current
->buf
+ p2
, current
->buf
+ p1
, current
->len
- p1
);
827 memcpy(current
->buf
+ p1
, buf
, n
);
831 if (current
->pos
>= pos
) {
840 * Returns 0 if no chars were removed or non-zero otherwise.
842 static int remove_chars(struct current
*current
, int pos
, int n
)
845 while (n
-- && remove_char(current
, pos
)) {
851 #ifndef NO_COMPLETION
852 static linenoiseCompletionCallback
*completionCallback
= NULL
;
856 fprintf(stderr
, "\x7");
861 static void freeCompletions(linenoiseCompletions
*lc
) {
863 for (i
= 0; i
< lc
->len
; i
++)
868 static int completeLine(struct current
*current
) {
869 linenoiseCompletions lc
= { 0, NULL
};
872 completionCallback(current
->buf
,&lc
);
876 size_t stop
= 0, i
= 0;
879 /* Show completion or original buffer */
881 struct current tmp
= *current
;
882 tmp
.buf
= lc
.cvec
[i
];
883 tmp
.pos
= tmp
.len
= strlen(tmp
.buf
);
884 tmp
.chars
= utf8_strlen(tmp
.buf
, tmp
.len
);
885 refreshLine(current
->prompt
, &tmp
);
887 refreshLine(current
->prompt
, current
);
890 c
= fd_read(current
);
897 i
= (i
+1) % (lc
.len
+1);
898 if (i
== lc
.len
) beep();
900 case 27: /* escape */
901 /* Re-show original buffer */
903 refreshLine(current
->prompt
, current
);
908 /* Update buffer and return */
910 set_current(current
,lc
.cvec
[i
]);
918 freeCompletions(&lc
);
919 return c
; /* Return last read character */
922 /* Register a callback function to be called for tab-completion. */
923 void linenoiseSetCompletionCallback(linenoiseCompletionCallback
*fn
) {
924 completionCallback
= fn
;
927 void linenoiseAddCompletion(linenoiseCompletions
*lc
, const char *str
) {
928 lc
->cvec
= (char **)realloc(lc
->cvec
,sizeof(char*)*(lc
->len
+1));
929 lc
->cvec
[lc
->len
++] = strdup(str
);
934 static int linenoisePrompt(struct current
*current
) {
935 int history_index
= 0;
937 /* The latest history entry is always our current buffer, that
938 * initially is just an empty string. */
939 linenoiseHistoryAdd("");
941 set_current(current
, "");
942 refreshLine(current
->prompt
, current
);
946 int c
= fd_read(current
);
948 #ifndef NO_COMPLETION
949 /* Only autocomplete when the callback is set. It returns < 0 when
950 * there was an error reading from fd. Otherwise it will return the
951 * character that should be handled next. */
952 if (c
== 9 && completionCallback
!= NULL
) {
953 c
= completeLine(current
);
954 /* Return on errors */
955 if (c
< 0) return current
->len
;
956 /* Read next character when 0 */
957 if (c
== 0) continue;
962 if (c
== -1) return current
->len
;
964 if (c
== 27) { /* escape sequence */
965 c
= check_special(current
->fd
);
969 case '\r': /* enter */
971 free(history
[history_len
]);
973 case ctrl('C'): /* ctrl-c */
976 case 127: /* backspace */
978 if (remove_char(current
, current
->pos
- 1) == 1) {
979 refreshLine(current
->prompt
, current
);
982 case ctrl('D'): /* ctrl-d */
983 if (current
->len
== 0) {
984 /* Empty line, so EOF */
986 free(history
[history_len
]);
989 /* Otherwise fall through to delete char to right of cursor */
991 if (remove_char(current
, current
->pos
) == 1) {
992 refreshLine(current
->prompt
, current
);
995 case ctrl('W'): /* ctrl-w */
996 /* eat any spaces on the left */
998 int pos
= current
->pos
;
999 while (pos
> 0 && get_char(current
, pos
- 1) == ' ') {
1003 /* now eat any non-spaces on the left */
1004 while (pos
> 0 && get_char(current
, pos
- 1) != ' ') {
1008 if (remove_chars(current
, pos
, current
->pos
- pos
)) {
1009 refreshLine(current
->prompt
, current
);
1013 case ctrl('R'): /* ctrl-r */
1015 /* Display the reverse-i-search prompt and process chars */
1020 int searchpos
= history_len
- 1;
1025 const char *p
= NULL
;
1029 snprintf(rprompt
, sizeof(rprompt
), "(reverse-i-search)'%s': ", rbuf
);
1030 refreshLine(rprompt
, current
);
1031 c
= fd_read(current
);
1032 if (c
== ctrl('H') || c
== 127) {
1034 int p
= utf8_index(rbuf
, --rchars
);
1036 rlen
= strlen(rbuf
);
1042 c
= check_special(current
->fd
);
1045 if (c
== ctrl('P') || c
== SPECIAL_UP
) {
1046 /* Search for the previous (earlier) match */
1047 if (searchpos
> 0) {
1052 else if (c
== ctrl('N') || c
== SPECIAL_DOWN
) {
1053 /* Search for the next (later) match */
1054 if (searchpos
< history_len
) {
1060 else if (c
>= ' ') {
1061 if (rlen
>= (int)sizeof(rbuf
) + 3) {
1065 n
= utf8_getchars(rbuf
+ rlen
, c
);
1070 /* Adding a new char resets the search location */
1071 searchpos
= history_len
- 1;
1074 /* Exit from incremental search mode */
1078 /* Now search through the history for a match */
1079 for (; searchpos
>= 0 && searchpos
< history_len
; searchpos
+= searchdir
) {
1080 p
= strstr(history
[searchpos
], rbuf
);
1083 if (skipsame
&& strcmp(history
[searchpos
], current
->buf
) == 0) {
1084 /* But it is identical, so skip it */
1087 /* Copy the matching line and set the cursor position */
1088 set_current(current
,history
[searchpos
]);
1089 current
->pos
= utf8_strlen(history
[searchpos
], p
- history
[searchpos
]);
1094 /* No match, so don't add it */
1100 if (c
== ctrl('G') || c
== ctrl('C')) {
1101 /* ctrl-g terminates the search with no effect */
1102 set_current(current
, "");
1105 else if (c
== ctrl('J')) {
1106 /* ctrl-j terminates the search leaving the buffer in place */
1109 /* Go process the char normally */
1110 refreshLine(current
->prompt
, current
);
1114 case ctrl('T'): /* ctrl-t */
1115 if (current
->pos
> 0 && current
->pos
< current
->chars
) {
1116 c
= get_char(current
, current
->pos
);
1117 remove_char(current
, current
->pos
);
1118 insert_char(current
, current
->pos
- 1, c
);
1119 refreshLine(current
->prompt
, current
);
1122 case ctrl('V'): /* ctrl-v */
1123 if (has_room(current
, 3)) {
1124 /* Insert the ^V first */
1125 if (insert_char(current
, current
->pos
, c
)) {
1126 refreshLine(current
->prompt
, current
);
1127 /* Now wait for the next char. Can insert anything except \0 */
1128 c
= fd_read(current
);
1130 /* Remove the ^V first */
1131 remove_char(current
, current
->pos
- 1);
1133 /* Insert the actual char */
1134 insert_char(current
, current
->pos
, c
);
1136 refreshLine(current
->prompt
, current
);
1142 if (current
->pos
> 0) {
1144 refreshLine(current
->prompt
, current
);
1149 if (current
->pos
< current
->chars
) {
1151 refreshLine(current
->prompt
, current
);
1159 if (history_len
> 1) {
1160 /* Update the current history entry before to
1161 * overwrite it with tne next one. */
1162 free(history
[history_len
-1-history_index
]);
1163 history
[history_len
-1-history_index
] = strdup(current
->buf
);
1164 /* Show the new entry */
1165 history_index
+= dir
;
1166 if (history_index
< 0) {
1169 } else if (history_index
>= history_len
) {
1170 history_index
= history_len
-1;
1173 set_current(current
, history
[history_len
-1-history_index
]);
1174 refreshLine(current
->prompt
, current
);
1177 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1180 refreshLine(current
->prompt
, current
);
1182 case ctrl('E'): /* ctrl+e, go to the end of the line */
1184 current
->pos
= current
->chars
;
1185 refreshLine(current
->prompt
, current
);
1187 case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1188 if (remove_chars(current
, 0, current
->pos
)) {
1189 refreshLine(current
->prompt
, current
);
1192 case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1193 if (remove_chars(current
, current
->pos
, current
->chars
- current
->pos
)) {
1194 refreshLine(current
->prompt
, current
);
1197 case ctrl('L'): /* Ctrl+L, clear screen */
1198 clearScreen(current
);
1199 /* Force recalc of window size for serial terminals */
1201 refreshLine(current
->prompt
, current
);
1204 /* Only tab is allowed without ^V */
1205 if (c
== '\t' || c
>= ' ') {
1206 if (insert_char(current
, current
->pos
, c
) == 1) {
1207 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
));
1264 /* do not insert duplicate lines into history */
1265 if (history_len
> 0 && strcmp(line
, history
[history_len
- 1]) == 0) {
1269 linecopy
= strdup(line
);
1270 if (!linecopy
) return 0;
1271 if (history_len
== history_max_len
) {
1273 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
1276 history
[history_len
] = linecopy
;
1281 int linenoiseHistorySetMaxLen(int len
) {
1284 if (len
< 1) return 0;
1286 int tocopy
= history_len
;
1288 newHistory
= (char **)malloc(sizeof(char*)*len
);
1289 if (newHistory
== NULL
) return 0;
1290 if (len
< tocopy
) tocopy
= len
;
1291 memcpy(newHistory
,history
+(history_max_len
-tocopy
), sizeof(char*)*tocopy
);
1293 history
= newHistory
;
1295 history_max_len
= len
;
1296 if (history_len
> history_max_len
)
1297 history_len
= history_max_len
;
1301 /* Save the history in the specified file. On success 0 is returned
1302 * otherwise -1 is returned. */
1303 int linenoiseHistorySave(const char *filename
) {
1304 FILE *fp
= fopen(filename
,"w");
1307 if (fp
== NULL
) return -1;
1308 for (j
= 0; j
< history_len
; j
++) {
1309 const char *str
= history
[j
];
1310 /* Need to encode backslash, nl and cr */
1315 else if (*str
== '\n') {
1318 else if (*str
== '\r') {
1333 /* Load the history from the specified file. If the file does not exist
1334 * zero is returned and no operation is performed.
1336 * If the file exists and the operation succeeded 0 is returned, otherwise
1337 * on error -1 is returned. */
1338 int linenoiseHistoryLoad(const char *filename
) {
1339 FILE *fp
= fopen(filename
,"r");
1340 char buf
[LINENOISE_MAX_LINE
];
1342 if (fp
== NULL
) return -1;
1344 while (fgets(buf
,LINENOISE_MAX_LINE
,fp
) != NULL
) {
1347 /* Decode backslash escaped values */
1348 for (src
= dest
= buf
; *src
; src
++) {
1356 else if (*src
== 'r') {
1364 /* Remove trailing newline */
1365 if (dest
!= buf
&& (dest
[-1] == '\n' || dest
[-1] == '\r')) {
1370 linenoiseHistoryAdd(buf
);
1376 /* Provide access to the history buffer.
1378 * If 'len' is not NULL, the length is stored in *len.
1380 char **linenoiseHistory(int *len
) {