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.
61 * Effect: if n is 0 or missing, clear from cursor to end of line
62 * Effect: if n is 1, clear from beginning of line to cursor
63 * Effect: if n is 2, clear entire line
65 * CUF (CUrsor Forward)
67 * Effect: moves cursor forward of n chars
69 * CR (Carriage Return)
71 * Effect: moves cursor to column 1
73 * The following are used to clear the screen: ESC [ H ESC [ 2 J
74 * This is actually composed of two sequences:
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.
105 #ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
108 #define USE_WINCONSOLE
110 #define HAVE_UNISTD_H
112 /* Microsoft headers don't like old POSIX names */
113 #define strdup _strdup
114 #define snprintf _snprintf
118 #include <sys/ioctl.h>
119 #include <sys/poll.h>
121 #define HAVE_UNISTD_H
133 #include <sys/types.h>
135 #include "linenoise.h"
137 #include "jim-config.h"
143 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
144 #define LINENOISE_MAX_LINE 4096
146 #define ctrl(C) ((C) - '@')
148 /* Use -ve numbers here to co-exist with normal unicode chars */
155 SPECIAL_DELETE
= -24,
158 SPECIAL_INSERT
= -27,
159 SPECIAL_PAGE_UP
= -28,
160 SPECIAL_PAGE_DOWN
= -29
163 static int history_max_len
= LINENOISE_DEFAULT_HISTORY_MAX_LEN
;
164 static int history_len
= 0;
165 static char **history
= NULL
;
167 /* Structure to contain the status of the current (being edited) line */
169 char *buf
; /* Current buffer. Always null terminated */
170 int bufmax
; /* Size of the buffer, including space for the null termination */
171 int len
; /* Number of bytes in 'buf' */
172 int chars
; /* Number of chars in 'buf' (utf-8 chars) */
173 int pos
; /* Cursor position, measured in chars */
174 int cols
; /* Size of the window, in chars */
176 char *capture
; /* Allocated capture buffer, or NULL for none. Always null terminated */
177 #if defined(USE_TERMIOS)
178 int fd
; /* Terminal fd */
179 #elif defined(USE_WINCONSOLE)
180 HANDLE outh
; /* Console output handle */
181 HANDLE inh
; /* Console input handle */
182 int rows
; /* Screen rows */
183 int x
; /* Current column during output */
184 int y
; /* Current row */
188 static int fd_read(struct current
*current
);
189 static int getWindowSize(struct current
*current
);
191 void linenoiseHistoryFree(void) {
195 for (j
= 0; j
< history_len
; j
++)
203 #if defined(USE_TERMIOS)
204 static void linenoiseAtExit(void);
205 static struct termios orig_termios
; /* in order to restore at exit */
206 static int rawmode
= 0; /* for atexit() function to check if restore is needed*/
207 static int atexit_registered
= 0; /* register atexit just 1 time */
209 static const char *unsupported_term
[] = {"dumb","cons25",NULL
};
211 static int isUnsupportedTerm(void) {
212 char *term
= getenv("TERM");
216 for (j
= 0; unsupported_term
[j
]; j
++) {
217 if (strcmp(term
, unsupported_term
[j
]) == 0) {
225 static int enableRawMode(struct current
*current
) {
228 current
->fd
= STDIN_FILENO
;
230 if (!isatty(current
->fd
) || isUnsupportedTerm() ||
231 tcgetattr(current
->fd
, &orig_termios
) == -1) {
237 if (!atexit_registered
) {
238 atexit(linenoiseAtExit
);
239 atexit_registered
= 1;
242 raw
= orig_termios
; /* modify the original mode */
243 /* input modes: no break, no CR to NL, no parity check, no strip char,
244 * no start/stop output control. */
245 raw
.c_iflag
&= ~(BRKINT
| ICRNL
| INPCK
| ISTRIP
| IXON
);
246 /* output modes - disable post processing */
247 raw
.c_oflag
&= ~(OPOST
);
248 /* control modes - set 8 bit chars */
249 raw
.c_cflag
|= (CS8
);
250 /* local modes - choing off, canonical off, no extended functions,
251 * no signal chars (^Z,^C) */
252 raw
.c_lflag
&= ~(ECHO
| ICANON
| IEXTEN
| ISIG
);
253 /* control chars - set return condition: min number of bytes and timer.
254 * We want read to return every single byte, without timeout. */
255 raw
.c_cc
[VMIN
] = 1; raw
.c_cc
[VTIME
] = 0; /* 1 byte, no timer */
257 /* put terminal in raw mode after flushing */
258 if (tcsetattr(current
->fd
,TCSADRAIN
,&raw
) < 0) {
267 static void disableRawMode(struct current
*current
) {
268 /* Don't even check the return value as it's too late. */
269 if (rawmode
&& tcsetattr(current
->fd
,TCSADRAIN
,&orig_termios
) != -1)
273 /* At exit we'll try to fix the terminal to the initial conditions. */
274 static void linenoiseAtExit(void) {
276 tcsetattr(STDIN_FILENO
, TCSADRAIN
, &orig_termios
);
278 linenoiseHistoryFree();
281 /* gcc/glibc insists that we care about the return code of write!
282 * Clarification: This means that a void-cast like "(void) (EXPR)"
285 #define IGNORE_RC(EXPR) if (EXPR) {}
287 /* This is fdprintf() on some systems, but use a different
288 * name to avoid conflicts
290 static void fd_printf(int fd
, const char *format
, ...)
296 va_start(args
, format
);
297 n
= vsnprintf(buf
, sizeof(buf
), format
, args
);
299 IGNORE_RC(write(fd
, buf
, n
));
302 static void clearScreen(struct current
*current
)
304 fd_printf(current
->fd
, "\x1b[H\x1b[2J");
307 static void cursorToLeft(struct current
*current
)
309 fd_printf(current
->fd
, "\r");
312 static int outputChars(struct current
*current
, const char *buf
, int len
)
314 return write(current
->fd
, buf
, len
);
317 static void outputControlChar(struct current
*current
, char ch
)
319 fd_printf(current
->fd
, "\x1b[7m^%c\x1b[0m", ch
);
322 static void eraseEol(struct current
*current
)
324 fd_printf(current
->fd
, "\x1b[0K");
327 static void setCursorPos(struct current
*current
, int x
)
329 fd_printf(current
->fd
, "\r\x1b[%dC", x
);
333 * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
335 * A timeout of -1 means to wait forever.
337 * Returns -1 if no char is received within the time or an error occurs.
339 static int fd_read_char(int fd
, int timeout
)
347 if (poll(&p
, 1, timeout
) == 0) {
351 if (read(fd
, &c
, 1) != 1) {
358 * Reads a complete utf-8 character
359 * and returns the unicode value, or -1 on error.
361 static int fd_read(struct current
*current
)
369 if (read(current
->fd
, &buf
[0], 1) != 1) {
372 n
= utf8_charlen(buf
[0]);
373 if (n
< 1 || n
> 3) {
376 for (i
= 1; i
< n
; i
++) {
377 if (read(current
->fd
, &buf
[i
], 1) != 1) {
382 /* decode and return the character */
383 utf8_tounicode(buf
, &c
);
386 return fd_read_char(current
->fd
, -1);
390 static int countColorControlChars(const char* prompt
, int plen
)
392 /* ANSI color control sequences have the form:
393 * "\x1b" "[" [0-9;]+ "m"
394 * We parse them with a simple state machine.
402 } state
= search_esc
;
406 /* XXX: Strictly we should be checking utf8 chars rather than
407 * bytes in case of the extremely unlikely scenario where
408 * an ANSI sequence is part of a utf8 sequence.
410 for (; plen
; plen
--, prompt
++) {
417 state
= expect_bracket
;
423 state
= expect_inner
;
430 if (ch
>= '0' && ch
<= '9') {
432 state
= expect_trail
;
442 } else if ((ch
!= ';') && ((ch
< '0') || (ch
> '9'))) {
445 /* 0-9, or semicolon */
454 static int getWindowSize(struct current
*current
)
458 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) == 0 && ws
.ws_col
!= 0) {
459 current
->cols
= ws
.ws_col
;
463 /* Failed to query the window size. Perhaps we are on a serial terminal.
464 * Try to query the width by sending the cursor as far to the right
465 * and reading back the cursor position.
466 * Note that this is only done once per call to linenoise rather than
467 * every time the line is refreshed for efficiency reasons.
469 if (current
->cols
== 0) {
472 /* Move cursor far right and report cursor position, then back to the left */
473 fd_printf(current
->fd
, "\x1b[999C" "\x1b[6n");
475 /* Parse the response: ESC [ rows ; cols R */
476 if (fd_read_char(current
->fd
, 100) == 0x1b && fd_read_char(current
->fd
, 100) == '[') {
479 int ch
= fd_read_char(current
->fd
, 100);
484 else if (ch
== 'R') {
486 if (n
!= 0 && n
< 1000) {
491 else if (ch
>= 0 && ch
<= '9') {
492 n
= n
* 10 + ch
- '0';
504 * If escape (27) was received, reads subsequent
505 * chars to determine if this is a known special key.
507 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
509 * If no additional char is received within a short time,
512 static int check_special(int fd
)
514 int c
= fd_read_char(fd
, 50);
521 c2
= fd_read_char(fd
, 50);
525 if (c
== '[' || c
== 'O') {
526 /* Potential arrow key */
533 return SPECIAL_RIGHT
;
542 if (c
== '[' && c2
>= '1' && c2
<= '8') {
543 /* extended escape */
544 c
= fd_read_char(fd
, 50);
548 return SPECIAL_INSERT
;
550 return SPECIAL_DELETE
;
552 return SPECIAL_PAGE_UP
;
554 return SPECIAL_PAGE_DOWN
;
561 while (c
!= -1 && c
!= '~') {
562 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
563 c
= fd_read_char(fd
, 50);
569 #elif defined(USE_WINCONSOLE)
571 static DWORD orig_consolemode
= 0;
573 static int enableRawMode(struct current
*current
) {
577 current
->outh
= GetStdHandle(STD_OUTPUT_HANDLE
);
578 current
->inh
= GetStdHandle(STD_INPUT_HANDLE
);
580 if (!PeekConsoleInput(current
->inh
, &irec
, 1, &n
)) {
583 if (getWindowSize(current
) != 0) {
586 if (GetConsoleMode(current
->inh
, &orig_consolemode
)) {
587 SetConsoleMode(current
->inh
, ENABLE_PROCESSED_INPUT
);
592 static void disableRawMode(struct current
*current
)
594 SetConsoleMode(current
->inh
, orig_consolemode
);
597 static void clearScreen(struct current
*current
)
599 COORD topleft
= { 0, 0 };
602 FillConsoleOutputCharacter(current
->outh
, ' ',
603 current
->cols
* current
->rows
, topleft
, &n
);
604 FillConsoleOutputAttribute(current
->outh
,
605 FOREGROUND_RED
| FOREGROUND_BLUE
| FOREGROUND_GREEN
,
606 current
->cols
* current
->rows
, topleft
, &n
);
607 SetConsoleCursorPosition(current
->outh
, topleft
);
610 static void cursorToLeft(struct current
*current
)
612 COORD pos
= { 0, (SHORT
)current
->y
};
615 FillConsoleOutputAttribute(current
->outh
,
616 FOREGROUND_RED
| FOREGROUND_BLUE
| FOREGROUND_GREEN
, current
->cols
, pos
, &n
);
620 static int outputChars(struct current
*current
, const char *buf
, int len
)
622 COORD pos
= { (SHORT
)current
->x
, (SHORT
)current
->y
};
625 WriteConsoleOutputCharacter(current
->outh
, buf
, len
, pos
, &n
);
630 static void outputControlChar(struct current
*current
, char ch
)
632 COORD pos
= { (SHORT
)current
->x
, (SHORT
)current
->y
};
635 FillConsoleOutputAttribute(current
->outh
, BACKGROUND_INTENSITY
, 2, pos
, &n
);
636 outputChars(current
, "^", 1);
637 outputChars(current
, &ch
, 1);
640 static void eraseEol(struct current
*current
)
642 COORD pos
= { (SHORT
)current
->x
, (SHORT
)current
->y
};
645 FillConsoleOutputCharacter(current
->outh
, ' ', current
->cols
- current
->x
, pos
, &n
);
648 static void setCursorPos(struct current
*current
, int x
)
650 COORD pos
= { (SHORT
)x
, (SHORT
)current
->y
};
652 SetConsoleCursorPosition(current
->outh
, pos
);
656 static int fd_read(struct current
*current
)
661 if (WaitForSingleObject(current
->inh
, INFINITE
) != WAIT_OBJECT_0
) {
664 if (!ReadConsoleInput (current
->inh
, &irec
, 1, &n
)) {
667 if (irec
.EventType
== KEY_EVENT
&& irec
.Event
.KeyEvent
.bKeyDown
) {
668 KEY_EVENT_RECORD
*k
= &irec
.Event
.KeyEvent
;
669 if (k
->dwControlKeyState
& ENHANCED_KEY
) {
670 switch (k
->wVirtualKeyCode
) {
674 return SPECIAL_RIGHT
;
680 return SPECIAL_INSERT
;
682 return SPECIAL_DELETE
;
688 return SPECIAL_PAGE_UP
;
690 return SPECIAL_PAGE_DOWN
;
693 /* Note that control characters are already translated in AsciiChar */
696 return k
->uChar
.UnicodeChar
;
698 return k
->uChar
.AsciiChar
;
706 static int countColorControlChars(char* prompt
, int plen
)
708 /* For windows we assume that there are no embedded ansi color
714 static int getWindowSize(struct current
*current
)
716 CONSOLE_SCREEN_BUFFER_INFO info
;
717 if (!GetConsoleScreenBufferInfo(current
->outh
, &info
)) {
720 current
->cols
= info
.dwSize
.X
;
721 current
->rows
= info
.dwSize
.Y
;
722 if (current
->cols
<= 0 || current
->rows
<= 0) {
726 current
->y
= info
.dwCursorPosition
.Y
;
727 current
->x
= info
.dwCursorPosition
.X
;
732 static int utf8_getchars(char *buf
, int c
)
735 return utf8_fromunicode(buf
, c
);
743 * Returns the unicode character at the given offset,
746 static int get_char(struct current
*current
, int pos
)
748 if (pos
>= 0 && pos
< current
->chars
) {
750 int i
= utf8_index(current
->buf
, pos
);
751 (void)utf8_tounicode(current
->buf
+ i
, &c
);
757 static void refreshLine(const char *prompt
, struct current
*current
)
763 const char *buf
= current
->buf
;
764 int chars
= current
->chars
;
765 int pos
= current
->pos
;
770 /* Should intercept SIGWINCH. For now, just get the size every time */
771 getWindowSize(current
);
773 plen
= strlen(prompt
);
774 pchars
= utf8_strlen(prompt
, plen
);
776 /* Scan the prompt for embedded ansi color control sequences and
777 * discount them as characters/columns.
779 pchars
-= countColorControlChars(prompt
, plen
);
781 /* Account for a line which is too long to fit in the window.
782 * Note that control chars require an extra column
785 /* How many cols are required to the left of 'pos'?
786 * The prompt, plus one extra for each control char
788 n
= pchars
+ utf8_strlen(buf
, current
->len
);
790 for (i
= 0; i
< pos
; i
++) {
791 b
+= utf8_tounicode(buf
+ b
, &ch
);
797 /* If too many are needed, strip chars off the front of 'buf'
798 * until it fits. Note that if the current char is a control character,
799 * we need one extra col.
801 if (current
->pos
< current
->chars
&& get_char(current
, current
->pos
) < ' ') {
805 while (n
>= current
->cols
&& pos
> 0) {
806 b
= utf8_tounicode(buf
, &ch
);
816 /* Cursor to left edge, then the prompt */
817 cursorToLeft(current
);
818 outputChars(current
, prompt
, plen
);
820 /* Now the current buffer content */
822 /* Need special handling for control characters.
823 * If we hit 'cols', stop.
825 b
= 0; /* unwritted bytes */
826 n
= 0; /* How many control chars were written */
827 for (i
= 0; i
< chars
; i
++) {
829 int w
= utf8_tounicode(buf
+ b
, &ch
);
833 if (pchars
+ i
+ n
>= current
->cols
) {
837 /* A control character, so write the buffer so far */
838 outputChars(current
, buf
, b
);
841 outputControlChar(current
, ch
+ '@');
850 outputChars(current
, buf
, b
);
852 /* Erase to right, move cursor to original position */
854 setCursorPos(current
, pos
+ pchars
+ backup
);
857 static void set_current(struct current
*current
, const char *str
)
859 strncpy(current
->buf
, str
, current
->bufmax
);
860 current
->buf
[current
->bufmax
- 1] = 0;
861 current
->len
= strlen(current
->buf
);
862 current
->pos
= current
->chars
= utf8_strlen(current
->buf
, current
->len
);
865 static int has_room(struct current
*current
, int bytes
)
867 return current
->len
+ bytes
< current
->bufmax
- 1;
871 * Removes the char at 'pos'.
873 * Returns 1 if the line needs to be refreshed, 2 if not
874 * and 0 if nothing was removed
876 static int remove_char(struct current
*current
, int pos
)
878 if (pos
>= 0 && pos
< current
->chars
) {
881 p1
= utf8_index(current
->buf
, pos
);
882 p2
= p1
+ utf8_index(current
->buf
+ p1
, 1);
885 /* optimise remove char in the case of removing the last char */
886 if (current
->pos
== pos
+ 1 && current
->pos
== current
->chars
) {
887 if (current
->buf
[pos
] >= ' ' && utf8_strlen(current
->prompt
, -1) + utf8_strlen(current
->buf
, current
->len
) < current
->cols
- 1) {
889 fd_printf(current
->fd
, "\b \b");
894 /* Move the null char too */
895 memmove(current
->buf
+ p1
, current
->buf
+ p2
, current
->len
- p2
+ 1);
896 current
->len
-= (p2
- p1
);
899 if (current
->pos
> pos
) {
908 * Insert 'ch' at position 'pos'
910 * Returns 1 if the line needs to be refreshed, 2 if not
911 * and 0 if nothing was inserted (no room)
913 static int insert_char(struct current
*current
, int pos
, int ch
)
916 int n
= utf8_getchars(buf
, ch
);
918 if (has_room(current
, n
) && pos
>= 0 && pos
<= current
->chars
) {
921 p1
= utf8_index(current
->buf
, pos
);
925 /* optimise the case where adding a single char to the end and no scrolling is needed */
926 if (current
->pos
== pos
&& current
->chars
== pos
) {
927 if (ch
>= ' ' && utf8_strlen(current
->prompt
, -1) + utf8_strlen(current
->buf
, current
->len
) < current
->cols
- 1) {
928 IGNORE_RC(write(current
->fd
, buf
, n
));
934 memmove(current
->buf
+ p2
, current
->buf
+ p1
, current
->len
- p1
);
935 memcpy(current
->buf
+ p1
, buf
, n
);
939 if (current
->pos
>= pos
) {
948 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
950 * This replaces any existing characters in the cut buffer.
952 static void capture_chars(struct current
*current
, int pos
, int n
)
954 if (pos
>= 0 && (pos
+ n
- 1) < current
->chars
) {
955 int p1
= utf8_index(current
->buf
, pos
);
956 int nbytes
= utf8_index(current
->buf
+ p1
, n
);
959 free(current
->capture
);
960 /* Include space for the null terminator */
961 current
->capture
= (char *)malloc(nbytes
+ 1);
962 memcpy(current
->capture
, current
->buf
+ p1
, nbytes
);
963 current
->capture
[nbytes
] = '\0';
969 * Removes up to 'n' characters at cursor position 'pos'.
971 * Returns 0 if no chars were removed or non-zero otherwise.
973 static int remove_chars(struct current
*current
, int pos
, int n
)
977 /* First save any chars which will be removed */
978 capture_chars(current
, pos
, n
);
980 while (n
-- && remove_char(current
, pos
)) {
986 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
988 * Returns 0 if no chars were inserted or non-zero otherwise.
990 static int insert_chars(struct current
*current
, int pos
, const char *chars
)
996 int n
= utf8_tounicode(chars
, &ch
);
997 if (insert_char(current
, pos
, ch
) == 0) {
1007 #ifndef NO_COMPLETION
1008 static linenoiseCompletionCallback
*completionCallback
= NULL
;
1010 static void beep() {
1012 fprintf(stderr
, "\x7");
1017 static void freeCompletions(linenoiseCompletions
*lc
) {
1019 for (i
= 0; i
< lc
->len
; i
++)
1024 static int completeLine(struct current
*current
) {
1025 linenoiseCompletions lc
= { 0, NULL
};
1028 completionCallback(current
->buf
,&lc
);
1032 size_t stop
= 0, i
= 0;
1035 /* Show completion or original buffer */
1037 struct current tmp
= *current
;
1038 tmp
.buf
= lc
.cvec
[i
];
1039 tmp
.pos
= tmp
.len
= strlen(tmp
.buf
);
1040 tmp
.chars
= utf8_strlen(tmp
.buf
, tmp
.len
);
1041 refreshLine(current
->prompt
, &tmp
);
1043 refreshLine(current
->prompt
, current
);
1046 c
= fd_read(current
);
1052 case '\t': /* tab */
1053 i
= (i
+1) % (lc
.len
+1);
1054 if (i
== lc
.len
) beep();
1056 case 27: /* escape */
1057 /* Re-show original buffer */
1059 refreshLine(current
->prompt
, current
);
1064 /* Update buffer and return */
1066 set_current(current
,lc
.cvec
[i
]);
1074 freeCompletions(&lc
);
1075 return c
; /* Return last read character */
1078 /* Register a callback function to be called for tab-completion. */
1079 void linenoiseSetCompletionCallback(linenoiseCompletionCallback
*fn
) {
1080 completionCallback
= fn
;
1083 void linenoiseAddCompletion(linenoiseCompletions
*lc
, const char *str
) {
1084 lc
->cvec
= (char **)realloc(lc
->cvec
,sizeof(char*)*(lc
->len
+1));
1085 lc
->cvec
[lc
->len
++] = strdup(str
);
1090 static int linenoiseEdit(struct current
*current
) {
1091 int history_index
= 0;
1093 /* The latest history entry is always our current buffer, that
1094 * initially is just an empty string. */
1095 linenoiseHistoryAdd("");
1097 set_current(current
, "");
1098 refreshLine(current
->prompt
, current
);
1102 int c
= fd_read(current
);
1104 #ifndef NO_COMPLETION
1105 /* Only autocomplete when the callback is set. It returns < 0 when
1106 * there was an error reading from fd. Otherwise it will return the
1107 * character that should be handled next. */
1108 if (c
== '\t' && current
->pos
== current
->chars
&& completionCallback
!= NULL
) {
1109 c
= completeLine(current
);
1110 /* Return on errors */
1111 if (c
< 0) return current
->len
;
1112 /* Read next character when 0 */
1113 if (c
== 0) continue;
1118 if (c
== -1) return current
->len
;
1120 if (c
== 27) { /* escape sequence */
1121 c
= check_special(current
->fd
);
1125 case '\r': /* enter */
1127 free(history
[history_len
]);
1128 return current
->len
;
1129 case ctrl('C'): /* ctrl-c */
1132 case 127: /* backspace */
1134 if (remove_char(current
, current
->pos
- 1) == 1) {
1135 refreshLine(current
->prompt
, current
);
1138 case ctrl('D'): /* ctrl-d */
1139 if (current
->len
== 0) {
1140 /* Empty line, so EOF */
1142 free(history
[history_len
]);
1145 /* Otherwise fall through to delete char to right of cursor */
1146 case SPECIAL_DELETE
:
1147 if (remove_char(current
, current
->pos
) == 1) {
1148 refreshLine(current
->prompt
, current
);
1151 case SPECIAL_INSERT
:
1152 /* Ignore. Expansion Hook.
1153 * Future possibility: Toggle Insert/Overwrite Modes
1156 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1157 /* eat any spaces on the left */
1159 int pos
= current
->pos
;
1160 while (pos
> 0 && get_char(current
, pos
- 1) == ' ') {
1164 /* now eat any non-spaces on the left */
1165 while (pos
> 0 && get_char(current
, pos
- 1) != ' ') {
1169 if (remove_chars(current
, pos
, current
->pos
- pos
)) {
1170 refreshLine(current
->prompt
, current
);
1174 case ctrl('R'): /* ctrl-r */
1176 /* Display the reverse-i-search prompt and process chars */
1181 int searchpos
= history_len
- 1;
1186 const char *p
= NULL
;
1190 snprintf(rprompt
, sizeof(rprompt
), "(reverse-i-search)'%s': ", rbuf
);
1191 refreshLine(rprompt
, current
);
1192 c
= fd_read(current
);
1193 if (c
== ctrl('H') || c
== 127) {
1195 int p
= utf8_index(rbuf
, --rchars
);
1197 rlen
= strlen(rbuf
);
1203 c
= check_special(current
->fd
);
1206 if (c
== ctrl('P') || c
== SPECIAL_UP
) {
1207 /* Search for the previous (earlier) match */
1208 if (searchpos
> 0) {
1213 else if (c
== ctrl('N') || c
== SPECIAL_DOWN
) {
1214 /* Search for the next (later) match */
1215 if (searchpos
< history_len
) {
1221 else if (c
>= ' ') {
1222 if (rlen
>= (int)sizeof(rbuf
) + 3) {
1226 n
= utf8_getchars(rbuf
+ rlen
, c
);
1231 /* Adding a new char resets the search location */
1232 searchpos
= history_len
- 1;
1235 /* Exit from incremental search mode */
1239 /* Now search through the history for a match */
1240 for (; searchpos
>= 0 && searchpos
< history_len
; searchpos
+= searchdir
) {
1241 p
= strstr(history
[searchpos
], rbuf
);
1244 if (skipsame
&& strcmp(history
[searchpos
], current
->buf
) == 0) {
1245 /* But it is identical, so skip it */
1248 /* Copy the matching line and set the cursor position */
1249 set_current(current
,history
[searchpos
]);
1250 current
->pos
= utf8_strlen(history
[searchpos
], p
- history
[searchpos
]);
1255 /* No match, so don't add it */
1261 if (c
== ctrl('G') || c
== ctrl('C')) {
1262 /* ctrl-g terminates the search with no effect */
1263 set_current(current
, "");
1266 else if (c
== ctrl('J')) {
1267 /* ctrl-j terminates the search leaving the buffer in place */
1270 /* Go process the char normally */
1271 refreshLine(current
->prompt
, current
);
1275 case ctrl('T'): /* ctrl-t */
1276 if (current
->pos
> 0 && current
->pos
<= current
->chars
) {
1277 /* If cursor is at end, transpose the previous two chars */
1278 int fixer
= (current
->pos
== current
->chars
);
1279 c
= get_char(current
, current
->pos
- fixer
);
1280 remove_char(current
, current
->pos
- fixer
);
1281 insert_char(current
, current
->pos
- 1, c
);
1282 refreshLine(current
->prompt
, current
);
1285 case ctrl('V'): /* ctrl-v */
1286 if (has_room(current
, 3)) {
1287 /* Insert the ^V first */
1288 if (insert_char(current
, current
->pos
, c
)) {
1289 refreshLine(current
->prompt
, current
);
1290 /* Now wait for the next char. Can insert anything except \0 */
1291 c
= fd_read(current
);
1293 /* Remove the ^V first */
1294 remove_char(current
, current
->pos
- 1);
1296 /* Insert the actual char */
1297 insert_char(current
, current
->pos
, c
);
1299 refreshLine(current
->prompt
, current
);
1305 if (current
->pos
> 0) {
1307 refreshLine(current
->prompt
, current
);
1312 if (current
->pos
< current
->chars
) {
1314 refreshLine(current
->prompt
, current
);
1317 case SPECIAL_PAGE_UP
:
1318 dir
= history_len
- history_index
- 1; /* move to start of history */
1319 goto history_navigation
;
1320 case SPECIAL_PAGE_DOWN
:
1321 dir
= -history_index
; /* move to 0 == end of history, i.e. current */
1322 goto history_navigation
;
1326 goto history_navigation
;
1330 if (history_len
> 1) {
1331 /* Update the current history entry before to
1332 * overwrite it with tne next one. */
1333 free(history
[history_len
- 1 - history_index
]);
1334 history
[history_len
- 1 - history_index
] = strdup(current
->buf
);
1335 /* Show the new entry */
1336 history_index
+= dir
;
1337 if (history_index
< 0) {
1340 } else if (history_index
>= history_len
) {
1341 history_index
= history_len
- 1;
1344 set_current(current
, history
[history_len
- 1 - history_index
]);
1345 refreshLine(current
->prompt
, current
);
1348 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1351 refreshLine(current
->prompt
, current
);
1353 case ctrl('E'): /* ctrl+e, go to the end of the line */
1355 current
->pos
= current
->chars
;
1356 refreshLine(current
->prompt
, current
);
1358 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1359 if (remove_chars(current
, 0, current
->pos
)) {
1360 refreshLine(current
->prompt
, current
);
1363 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1364 if (remove_chars(current
, current
->pos
, current
->chars
- current
->pos
)) {
1365 refreshLine(current
->prompt
, current
);
1368 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1369 if (current
->capture
&& insert_chars(current
, current
->pos
, current
->capture
)) {
1370 refreshLine(current
->prompt
, current
);
1373 case ctrl('L'): /* Ctrl+L, clear screen */
1374 clearScreen(current
);
1375 /* Force recalc of window size for serial terminals */
1377 refreshLine(current
->prompt
, current
);
1380 /* Only tab is allowed without ^V */
1381 if (c
== '\t' || c
>= ' ') {
1382 if (insert_char(current
, current
->pos
, c
) == 1) {
1383 refreshLine(current
->prompt
, current
);
1389 return current
->len
;
1392 int linenoiseColumns(void)
1394 struct current current
;
1395 enableRawMode (¤t
);
1396 getWindowSize (¤t
);
1397 disableRawMode (¤t
);
1398 return current
.cols
;
1401 char *linenoise(const char *prompt
)
1404 struct current current
;
1405 char buf
[LINENOISE_MAX_LINE
];
1407 if (enableRawMode(¤t
) == -1) {
1408 printf("%s", prompt
);
1410 if (fgets(buf
, sizeof(buf
), stdin
) == NULL
) {
1413 count
= strlen(buf
);
1414 if (count
&& buf
[count
-1] == '\n') {
1422 current
.bufmax
= sizeof(buf
);
1426 current
.prompt
= prompt
;
1427 current
.capture
= NULL
;
1429 count
= linenoiseEdit(¤t
);
1431 disableRawMode(¤t
);
1434 free(current
.capture
);
1442 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1443 int linenoiseHistoryAdd(const char *line
) {
1446 if (history_max_len
== 0) return 0;
1447 if (history
== NULL
) {
1448 history
= (char **)malloc(sizeof(char*)*history_max_len
);
1449 if (history
== NULL
) return 0;
1450 memset(history
,0,(sizeof(char*)*history_max_len
));
1453 /* do not insert duplicate lines into history */
1454 if (history_len
> 0 && strcmp(line
, history
[history_len
- 1]) == 0) {
1458 linecopy
= strdup(line
);
1459 if (!linecopy
) return 0;
1460 if (history_len
== history_max_len
) {
1462 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
1465 history
[history_len
] = linecopy
;
1470 int linenoiseHistoryGetMaxLen(void) {
1471 return history_max_len
;
1474 int linenoiseHistorySetMaxLen(int len
) {
1477 if (len
< 1) return 0;
1479 int tocopy
= history_len
;
1481 newHistory
= (char **)malloc(sizeof(char*)*len
);
1482 if (newHistory
== NULL
) return 0;
1484 /* If we can't copy everything, free the elements we'll not use. */
1488 for (j
= 0; j
< tocopy
-len
; j
++) free(history
[j
]);
1491 memset(newHistory
,0,sizeof(char*)*len
);
1492 memcpy(newHistory
,history
+(history_len
-tocopy
), sizeof(char*)*tocopy
);
1494 history
= newHistory
;
1496 history_max_len
= len
;
1497 if (history_len
> history_max_len
)
1498 history_len
= history_max_len
;
1502 /* Save the history in the specified file. On success 0 is returned
1503 * otherwise -1 is returned. */
1504 int linenoiseHistorySave(const char *filename
) {
1505 FILE *fp
= fopen(filename
,"w");
1508 if (fp
== NULL
) return -1;
1509 for (j
= 0; j
< history_len
; j
++) {
1510 const char *str
= history
[j
];
1511 /* Need to encode backslash, nl and cr */
1516 else if (*str
== '\n') {
1519 else if (*str
== '\r') {
1534 /* Load the history from the specified file. If the file does not exist
1535 * zero is returned and no operation is performed.
1537 * If the file exists and the operation succeeded 0 is returned, otherwise
1538 * on error -1 is returned. */
1539 int linenoiseHistoryLoad(const char *filename
) {
1540 FILE *fp
= fopen(filename
,"r");
1541 char buf
[LINENOISE_MAX_LINE
];
1543 if (fp
== NULL
) return -1;
1545 while (fgets(buf
,LINENOISE_MAX_LINE
,fp
) != NULL
) {
1548 /* Decode backslash escaped values */
1549 for (src
= dest
= buf
; *src
; src
++) {
1557 else if (*src
== 'r') {
1565 /* Remove trailing newline */
1566 if (dest
!= buf
&& (dest
[-1] == '\n' || dest
[-1] == '\r')) {
1571 linenoiseHistoryAdd(buf
);
1577 /* Provide access to the history buffer.
1579 * If 'len' is not NULL, the length is stored in *len.
1581 char **linenoiseHistory(int *len
) {