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
)
392 /* ANSI color control sequences have the form:
393 * "\x1b" "[" [0-9;]* "m"
394 * We parse them with a simple state machine.
401 } state
= search_esc
;
402 int len
= 0, found
= 0;
405 /* XXX: Strictly we should be checking utf8 chars rather than
406 * bytes in case of the extremely unlikely scenario where
407 * an ANSI sequence is part of a utf8 sequence.
409 while ((ch
= *prompt
++) != 0) {
413 state
= expect_bracket
;
418 state
= expect_trail
;
419 /* 3 for "\e[ ... m" */
426 if ((ch
== ';') || ((ch
>= '0' && ch
<= '9'))) {
427 /* 0-9, or semicolon */
442 static int getWindowSize(struct current
*current
)
446 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) == 0 && ws
.ws_col
!= 0) {
447 current
->cols
= ws
.ws_col
;
451 /* Failed to query the window size. Perhaps we are on a serial terminal.
452 * Try to query the width by sending the cursor as far to the right
453 * and reading back the cursor position.
454 * Note that this is only done once per call to linenoise rather than
455 * every time the line is refreshed for efficiency reasons.
457 if (current
->cols
== 0) {
460 /* Move cursor far right and report cursor position, then back to the left */
461 fd_printf(current
->fd
, "\x1b[999C" "\x1b[6n");
463 /* Parse the response: ESC [ rows ; cols R */
464 if (fd_read_char(current
->fd
, 100) == 0x1b && fd_read_char(current
->fd
, 100) == '[') {
467 int ch
= fd_read_char(current
->fd
, 100);
472 else if (ch
== 'R') {
474 if (n
!= 0 && n
< 1000) {
479 else if (ch
>= 0 && ch
<= '9') {
480 n
= n
* 10 + ch
- '0';
492 * If escape (27) was received, reads subsequent
493 * chars to determine if this is a known special key.
495 * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
497 * If no additional char is received within a short time,
500 static int check_special(int fd
)
502 int c
= fd_read_char(fd
, 50);
509 c2
= fd_read_char(fd
, 50);
513 if (c
== '[' || c
== 'O') {
514 /* Potential arrow key */
521 return SPECIAL_RIGHT
;
530 if (c
== '[' && c2
>= '1' && c2
<= '8') {
531 /* extended escape */
532 c
= fd_read_char(fd
, 50);
536 return SPECIAL_INSERT
;
538 return SPECIAL_DELETE
;
540 return SPECIAL_PAGE_UP
;
542 return SPECIAL_PAGE_DOWN
;
549 while (c
!= -1 && c
!= '~') {
550 /* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
551 c
= fd_read_char(fd
, 50);
557 #elif defined(USE_WINCONSOLE)
559 static DWORD orig_consolemode
= 0;
561 static int enableRawMode(struct current
*current
) {
565 current
->outh
= GetStdHandle(STD_OUTPUT_HANDLE
);
566 current
->inh
= GetStdHandle(STD_INPUT_HANDLE
);
568 if (!PeekConsoleInput(current
->inh
, &irec
, 1, &n
)) {
571 if (getWindowSize(current
) != 0) {
574 if (GetConsoleMode(current
->inh
, &orig_consolemode
)) {
575 SetConsoleMode(current
->inh
, ENABLE_PROCESSED_INPUT
);
580 static void disableRawMode(struct current
*current
)
582 SetConsoleMode(current
->inh
, orig_consolemode
);
585 static void clearScreen(struct current
*current
)
587 COORD topleft
= { 0, 0 };
590 FillConsoleOutputCharacter(current
->outh
, ' ',
591 current
->cols
* current
->rows
, topleft
, &n
);
592 FillConsoleOutputAttribute(current
->outh
,
593 FOREGROUND_RED
| FOREGROUND_BLUE
| FOREGROUND_GREEN
,
594 current
->cols
* current
->rows
, topleft
, &n
);
595 SetConsoleCursorPosition(current
->outh
, topleft
);
598 static void cursorToLeft(struct current
*current
)
600 COORD pos
= { 0, (SHORT
)current
->y
};
603 FillConsoleOutputAttribute(current
->outh
,
604 FOREGROUND_RED
| FOREGROUND_BLUE
| FOREGROUND_GREEN
, current
->cols
, pos
, &n
);
608 static int outputChars(struct current
*current
, const char *buf
, int len
)
610 COORD pos
= { (SHORT
)current
->x
, (SHORT
)current
->y
};
613 WriteConsoleOutputCharacter(current
->outh
, buf
, len
, pos
, &n
);
618 static void outputControlChar(struct current
*current
, char ch
)
620 COORD pos
= { (SHORT
)current
->x
, (SHORT
)current
->y
};
623 FillConsoleOutputAttribute(current
->outh
, BACKGROUND_INTENSITY
, 2, pos
, &n
);
624 outputChars(current
, "^", 1);
625 outputChars(current
, &ch
, 1);
628 static void eraseEol(struct current
*current
)
630 COORD pos
= { (SHORT
)current
->x
, (SHORT
)current
->y
};
633 FillConsoleOutputCharacter(current
->outh
, ' ', current
->cols
- current
->x
, pos
, &n
);
636 static void setCursorPos(struct current
*current
, int x
)
638 COORD pos
= { (SHORT
)x
, (SHORT
)current
->y
};
640 SetConsoleCursorPosition(current
->outh
, pos
);
644 static int fd_read(struct current
*current
)
649 if (WaitForSingleObject(current
->inh
, INFINITE
) != WAIT_OBJECT_0
) {
652 if (!ReadConsoleInput (current
->inh
, &irec
, 1, &n
)) {
655 if (irec
.EventType
== KEY_EVENT
&& irec
.Event
.KeyEvent
.bKeyDown
) {
656 KEY_EVENT_RECORD
*k
= &irec
.Event
.KeyEvent
;
657 if (k
->dwControlKeyState
& ENHANCED_KEY
) {
658 switch (k
->wVirtualKeyCode
) {
662 return SPECIAL_RIGHT
;
668 return SPECIAL_INSERT
;
670 return SPECIAL_DELETE
;
676 return SPECIAL_PAGE_UP
;
678 return SPECIAL_PAGE_DOWN
;
681 /* Note that control characters are already translated in AsciiChar */
684 return k
->uChar
.UnicodeChar
;
686 return k
->uChar
.AsciiChar
;
694 static int countColorControlChars(const char* prompt
)
696 /* For windows we assume that there are no embedded ansi color
702 static int getWindowSize(struct current
*current
)
704 CONSOLE_SCREEN_BUFFER_INFO info
;
705 if (!GetConsoleScreenBufferInfo(current
->outh
, &info
)) {
708 current
->cols
= info
.dwSize
.X
;
709 current
->rows
= info
.dwSize
.Y
;
710 if (current
->cols
<= 0 || current
->rows
<= 0) {
714 current
->y
= info
.dwCursorPosition
.Y
;
715 current
->x
= info
.dwCursorPosition
.X
;
721 * Returns the unicode character at the given offset,
724 static int get_char(struct current
*current
, int pos
)
726 if (pos
>= 0 && pos
< current
->chars
) {
728 int i
= utf8_index(current
->buf
, pos
);
729 (void)utf8_tounicode(current
->buf
+ i
, &c
);
735 static void refreshLine(const char *prompt
, struct current
*current
)
741 const char *buf
= current
->buf
;
742 int chars
= current
->chars
;
743 int pos
= current
->pos
;
748 /* Should intercept SIGWINCH. For now, just get the size every time */
749 getWindowSize(current
);
751 plen
= strlen(prompt
);
752 pchars
= utf8_strlen(prompt
, plen
);
754 /* Scan the prompt for embedded ansi color control sequences and
755 * discount them as characters/columns.
757 pchars
-= countColorControlChars(prompt
);
759 /* Account for a line which is too long to fit in the window.
760 * Note that control chars require an extra column
763 /* How many cols are required to the left of 'pos'?
764 * The prompt, plus one extra for each control char
766 n
= pchars
+ utf8_strlen(buf
, current
->len
);
768 for (i
= 0; i
< pos
; i
++) {
769 b
+= utf8_tounicode(buf
+ b
, &ch
);
775 /* If too many are needed, strip chars off the front of 'buf'
776 * until it fits. Note that if the current char is a control character,
777 * we need one extra col.
779 if (current
->pos
< current
->chars
&& get_char(current
, current
->pos
) < ' ') {
783 while (n
>= current
->cols
&& pos
> 0) {
784 b
= utf8_tounicode(buf
, &ch
);
794 /* Cursor to left edge, then the prompt */
795 cursorToLeft(current
);
796 outputChars(current
, prompt
, plen
);
798 /* Now the current buffer content */
800 /* Need special handling for control characters.
801 * If we hit 'cols', stop.
803 b
= 0; /* unwritted bytes */
804 n
= 0; /* How many control chars were written */
805 for (i
= 0; i
< chars
; i
++) {
807 int w
= utf8_tounicode(buf
+ b
, &ch
);
811 if (pchars
+ i
+ n
>= current
->cols
) {
815 /* A control character, so write the buffer so far */
816 outputChars(current
, buf
, b
);
819 outputControlChar(current
, ch
+ '@');
828 outputChars(current
, buf
, b
);
830 /* Erase to right, move cursor to original position */
832 setCursorPos(current
, pos
+ pchars
+ backup
);
835 static void set_current(struct current
*current
, const char *str
)
837 strncpy(current
->buf
, str
, current
->bufmax
);
838 current
->buf
[current
->bufmax
- 1] = 0;
839 current
->len
= strlen(current
->buf
);
840 current
->pos
= current
->chars
= utf8_strlen(current
->buf
, current
->len
);
843 static int has_room(struct current
*current
, int bytes
)
845 return current
->len
+ bytes
< current
->bufmax
- 1;
849 * Removes the char at 'pos'.
851 * Returns 1 if the line needs to be refreshed, 2 if not
852 * and 0 if nothing was removed
854 static int remove_char(struct current
*current
, int pos
)
856 if (pos
>= 0 && pos
< current
->chars
) {
859 p1
= utf8_index(current
->buf
, pos
);
860 p2
= p1
+ utf8_index(current
->buf
+ p1
, 1);
863 /* optimise remove char in the case of removing the last char */
864 if (current
->pos
== pos
+ 1 && current
->pos
== current
->chars
) {
865 if (current
->buf
[pos
] >= ' ' && utf8_strlen(current
->prompt
, -1) + utf8_strlen(current
->buf
, current
->len
) < current
->cols
- 1) {
867 fd_printf(current
->fd
, "\b \b");
872 /* Move the null char too */
873 memmove(current
->buf
+ p1
, current
->buf
+ p2
, current
->len
- p2
+ 1);
874 current
->len
-= (p2
- p1
);
877 if (current
->pos
> pos
) {
886 * Insert 'ch' at position 'pos'
888 * Returns 1 if the line needs to be refreshed, 2 if not
889 * and 0 if nothing was inserted (no room)
891 static int insert_char(struct current
*current
, int pos
, int ch
)
894 int n
= utf8_getchars(buf
, ch
);
896 if (has_room(current
, n
) && pos
>= 0 && pos
<= current
->chars
) {
899 p1
= utf8_index(current
->buf
, pos
);
903 /* optimise the case where adding a single char to the end and no scrolling is needed */
904 if (current
->pos
== pos
&& current
->chars
== pos
) {
905 if (ch
>= ' ' && utf8_strlen(current
->prompt
, -1) + utf8_strlen(current
->buf
, current
->len
) < current
->cols
- 1) {
906 IGNORE_RC(write(current
->fd
, buf
, n
));
912 memmove(current
->buf
+ p2
, current
->buf
+ p1
, current
->len
- p1
);
913 memcpy(current
->buf
+ p1
, buf
, n
);
917 if (current
->pos
>= pos
) {
926 * Captures up to 'n' characters starting at 'pos' for the cut buffer.
928 * This replaces any existing characters in the cut buffer.
930 static void capture_chars(struct current
*current
, int pos
, int n
)
932 if (pos
>= 0 && (pos
+ n
- 1) < current
->chars
) {
933 int p1
= utf8_index(current
->buf
, pos
);
934 int nbytes
= utf8_index(current
->buf
+ p1
, n
);
937 free(current
->capture
);
938 /* Include space for the null terminator */
939 current
->capture
= (char *)malloc(nbytes
+ 1);
940 memcpy(current
->capture
, current
->buf
+ p1
, nbytes
);
941 current
->capture
[nbytes
] = '\0';
947 * Removes up to 'n' characters at cursor position 'pos'.
949 * Returns 0 if no chars were removed or non-zero otherwise.
951 static int remove_chars(struct current
*current
, int pos
, int n
)
955 /* First save any chars which will be removed */
956 capture_chars(current
, pos
, n
);
958 while (n
-- && remove_char(current
, pos
)) {
964 * Inserts the characters (string) 'chars' at the cursor position 'pos'.
966 * Returns 0 if no chars were inserted or non-zero otherwise.
968 static int insert_chars(struct current
*current
, int pos
, const char *chars
)
974 int n
= utf8_tounicode(chars
, &ch
);
975 if (insert_char(current
, pos
, ch
) == 0) {
985 #ifndef NO_COMPLETION
986 static linenoiseCompletionCallback
*completionCallback
= NULL
;
990 fprintf(stderr
, "\x7");
995 static void freeCompletions(linenoiseCompletions
*lc
) {
997 for (i
= 0; i
< lc
->len
; i
++)
1002 static int completeLine(struct current
*current
) {
1003 linenoiseCompletions lc
= { 0, NULL
};
1006 completionCallback(current
->buf
,&lc
);
1010 size_t stop
= 0, i
= 0;
1013 /* Show completion or original buffer */
1015 struct current tmp
= *current
;
1016 tmp
.buf
= lc
.cvec
[i
];
1017 tmp
.pos
= tmp
.len
= strlen(tmp
.buf
);
1018 tmp
.chars
= utf8_strlen(tmp
.buf
, tmp
.len
);
1019 refreshLine(current
->prompt
, &tmp
);
1021 refreshLine(current
->prompt
, current
);
1024 c
= fd_read(current
);
1030 case '\t': /* tab */
1031 i
= (i
+1) % (lc
.len
+1);
1032 if (i
== lc
.len
) beep();
1034 case 27: /* escape */
1035 /* Re-show original buffer */
1037 refreshLine(current
->prompt
, current
);
1042 /* Update buffer and return */
1044 set_current(current
,lc
.cvec
[i
]);
1052 freeCompletions(&lc
);
1053 return c
; /* Return last read character */
1056 /* Register a callback function to be called for tab-completion. */
1057 void linenoiseSetCompletionCallback(linenoiseCompletionCallback
*fn
) {
1058 completionCallback
= fn
;
1061 void linenoiseAddCompletion(linenoiseCompletions
*lc
, const char *str
) {
1062 lc
->cvec
= (char **)realloc(lc
->cvec
,sizeof(char*)*(lc
->len
+1));
1063 lc
->cvec
[lc
->len
++] = strdup(str
);
1068 static int linenoiseEdit(struct current
*current
) {
1069 int history_index
= 0;
1071 /* The latest history entry is always our current buffer, that
1072 * initially is just an empty string. */
1073 linenoiseHistoryAdd("");
1075 set_current(current
, "");
1076 refreshLine(current
->prompt
, current
);
1080 int c
= fd_read(current
);
1082 #ifndef NO_COMPLETION
1083 /* Only autocomplete when the callback is set. It returns < 0 when
1084 * there was an error reading from fd. Otherwise it will return the
1085 * character that should be handled next. */
1086 if (c
== '\t' && current
->pos
== current
->chars
&& completionCallback
!= NULL
) {
1087 c
= completeLine(current
);
1088 /* Return on errors */
1089 if (c
< 0) return current
->len
;
1090 /* Read next character when 0 */
1091 if (c
== 0) continue;
1096 if (c
== -1) return current
->len
;
1098 if (c
== 27) { /* escape sequence */
1099 c
= check_special(current
->fd
);
1103 case '\r': /* enter */
1105 free(history
[history_len
]);
1106 return current
->len
;
1107 case ctrl('C'): /* ctrl-c */
1110 case 127: /* backspace */
1112 if (remove_char(current
, current
->pos
- 1) == 1) {
1113 refreshLine(current
->prompt
, current
);
1116 case ctrl('D'): /* ctrl-d */
1117 if (current
->len
== 0) {
1118 /* Empty line, so EOF */
1120 free(history
[history_len
]);
1123 /* Otherwise fall through to delete char to right of cursor */
1124 case SPECIAL_DELETE
:
1125 if (remove_char(current
, current
->pos
) == 1) {
1126 refreshLine(current
->prompt
, current
);
1129 case SPECIAL_INSERT
:
1130 /* Ignore. Expansion Hook.
1131 * Future possibility: Toggle Insert/Overwrite Modes
1134 case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
1135 /* eat any spaces on the left */
1137 int pos
= current
->pos
;
1138 while (pos
> 0 && get_char(current
, pos
- 1) == ' ') {
1142 /* now eat any non-spaces on the left */
1143 while (pos
> 0 && get_char(current
, pos
- 1) != ' ') {
1147 if (remove_chars(current
, pos
, current
->pos
- pos
)) {
1148 refreshLine(current
->prompt
, current
);
1152 case ctrl('R'): /* ctrl-r */
1154 /* Display the reverse-i-search prompt and process chars */
1159 int searchpos
= history_len
- 1;
1164 const char *p
= NULL
;
1168 snprintf(rprompt
, sizeof(rprompt
), "(reverse-i-search)'%s': ", rbuf
);
1169 refreshLine(rprompt
, current
);
1170 c
= fd_read(current
);
1171 if (c
== ctrl('H') || c
== 127) {
1173 int p
= utf8_index(rbuf
, --rchars
);
1175 rlen
= strlen(rbuf
);
1181 c
= check_special(current
->fd
);
1184 if (c
== ctrl('P') || c
== SPECIAL_UP
) {
1185 /* Search for the previous (earlier) match */
1186 if (searchpos
> 0) {
1191 else if (c
== ctrl('N') || c
== SPECIAL_DOWN
) {
1192 /* Search for the next (later) match */
1193 if (searchpos
< history_len
) {
1199 else if (c
>= ' ') {
1200 if (rlen
>= (int)sizeof(rbuf
) + 3) {
1204 n
= utf8_getchars(rbuf
+ rlen
, c
);
1209 /* Adding a new char resets the search location */
1210 searchpos
= history_len
- 1;
1213 /* Exit from incremental search mode */
1217 /* Now search through the history for a match */
1218 for (; searchpos
>= 0 && searchpos
< history_len
; searchpos
+= searchdir
) {
1219 p
= strstr(history
[searchpos
], rbuf
);
1222 if (skipsame
&& strcmp(history
[searchpos
], current
->buf
) == 0) {
1223 /* But it is identical, so skip it */
1226 /* Copy the matching line and set the cursor position */
1227 set_current(current
,history
[searchpos
]);
1228 current
->pos
= utf8_strlen(history
[searchpos
], p
- history
[searchpos
]);
1233 /* No match, so don't add it */
1239 if (c
== ctrl('G') || c
== ctrl('C')) {
1240 /* ctrl-g terminates the search with no effect */
1241 set_current(current
, "");
1244 else if (c
== ctrl('J')) {
1245 /* ctrl-j terminates the search leaving the buffer in place */
1248 /* Go process the char normally */
1249 refreshLine(current
->prompt
, current
);
1253 case ctrl('T'): /* ctrl-t */
1254 if (current
->pos
> 0 && current
->pos
<= current
->chars
) {
1255 /* If cursor is at end, transpose the previous two chars */
1256 int fixer
= (current
->pos
== current
->chars
);
1257 c
= get_char(current
, current
->pos
- fixer
);
1258 remove_char(current
, current
->pos
- fixer
);
1259 insert_char(current
, current
->pos
- 1, c
);
1260 refreshLine(current
->prompt
, current
);
1263 case ctrl('V'): /* ctrl-v */
1264 if (has_room(current
, 3)) {
1265 /* Insert the ^V first */
1266 if (insert_char(current
, current
->pos
, c
)) {
1267 refreshLine(current
->prompt
, current
);
1268 /* Now wait for the next char. Can insert anything except \0 */
1269 c
= fd_read(current
);
1271 /* Remove the ^V first */
1272 remove_char(current
, current
->pos
- 1);
1274 /* Insert the actual char */
1275 insert_char(current
, current
->pos
, c
);
1277 refreshLine(current
->prompt
, current
);
1283 if (current
->pos
> 0) {
1285 refreshLine(current
->prompt
, current
);
1290 if (current
->pos
< current
->chars
) {
1292 refreshLine(current
->prompt
, current
);
1295 case SPECIAL_PAGE_UP
:
1296 dir
= history_len
- history_index
- 1; /* move to start of history */
1297 goto history_navigation
;
1298 case SPECIAL_PAGE_DOWN
:
1299 dir
= -history_index
; /* move to 0 == end of history, i.e. current */
1300 goto history_navigation
;
1304 goto history_navigation
;
1308 if (history_len
> 1) {
1309 /* Update the current history entry before to
1310 * overwrite it with tne next one. */
1311 free(history
[history_len
- 1 - history_index
]);
1312 history
[history_len
- 1 - history_index
] = strdup(current
->buf
);
1313 /* Show the new entry */
1314 history_index
+= dir
;
1315 if (history_index
< 0) {
1318 } else if (history_index
>= history_len
) {
1319 history_index
= history_len
- 1;
1322 set_current(current
, history
[history_len
- 1 - history_index
]);
1323 refreshLine(current
->prompt
, current
);
1326 case ctrl('A'): /* Ctrl+a, go to the start of the line */
1329 refreshLine(current
->prompt
, current
);
1331 case ctrl('E'): /* ctrl+e, go to the end of the line */
1333 current
->pos
= current
->chars
;
1334 refreshLine(current
->prompt
, current
);
1336 case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
1337 if (remove_chars(current
, 0, current
->pos
)) {
1338 refreshLine(current
->prompt
, current
);
1341 case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
1342 if (remove_chars(current
, current
->pos
, current
->chars
- current
->pos
)) {
1343 refreshLine(current
->prompt
, current
);
1346 case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
1347 if (current
->capture
&& insert_chars(current
, current
->pos
, current
->capture
)) {
1348 refreshLine(current
->prompt
, current
);
1351 case ctrl('L'): /* Ctrl+L, clear screen */
1352 clearScreen(current
);
1353 /* Force recalc of window size for serial terminals */
1355 refreshLine(current
->prompt
, current
);
1358 /* Only tab is allowed without ^V */
1359 if (c
== '\t' || c
>= ' ') {
1360 if (insert_char(current
, current
->pos
, c
) == 1) {
1361 refreshLine(current
->prompt
, current
);
1367 return current
->len
;
1370 int linenoiseColumns(void)
1372 struct current current
;
1373 enableRawMode (¤t
);
1374 getWindowSize (¤t
);
1375 disableRawMode (¤t
);
1376 return current
.cols
;
1379 char *linenoise(const char *prompt
)
1382 struct current current
;
1383 char buf
[LINENOISE_MAX_LINE
];
1385 if (enableRawMode(¤t
) == -1) {
1386 printf("%s", prompt
);
1388 if (fgets(buf
, sizeof(buf
), stdin
) == NULL
) {
1391 count
= strlen(buf
);
1392 if (count
&& buf
[count
-1] == '\n') {
1400 current
.bufmax
= sizeof(buf
);
1404 current
.prompt
= prompt
;
1405 current
.capture
= NULL
;
1407 count
= linenoiseEdit(¤t
);
1409 disableRawMode(¤t
);
1412 free(current
.capture
);
1420 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1421 int linenoiseHistoryAdd(const char *line
) {
1424 if (history_max_len
== 0) return 0;
1425 if (history
== NULL
) {
1426 history
= (char **)malloc(sizeof(char*)*history_max_len
);
1427 if (history
== NULL
) return 0;
1428 memset(history
,0,(sizeof(char*)*history_max_len
));
1431 /* do not insert duplicate lines into history */
1432 if (history_len
> 0 && strcmp(line
, history
[history_len
- 1]) == 0) {
1436 linecopy
= strdup(line
);
1437 if (!linecopy
) return 0;
1438 if (history_len
== history_max_len
) {
1440 memmove(history
,history
+1,sizeof(char*)*(history_max_len
-1));
1443 history
[history_len
] = linecopy
;
1448 int linenoiseHistoryGetMaxLen(void) {
1449 return history_max_len
;
1452 int linenoiseHistorySetMaxLen(int len
) {
1455 if (len
< 1) return 0;
1457 int tocopy
= history_len
;
1459 newHistory
= (char **)malloc(sizeof(char*)*len
);
1460 if (newHistory
== NULL
) return 0;
1462 /* If we can't copy everything, free the elements we'll not use. */
1466 for (j
= 0; j
< tocopy
-len
; j
++) free(history
[j
]);
1469 memset(newHistory
,0,sizeof(char*)*len
);
1470 memcpy(newHistory
,history
+(history_len
-tocopy
), sizeof(char*)*tocopy
);
1472 history
= newHistory
;
1474 history_max_len
= len
;
1475 if (history_len
> history_max_len
)
1476 history_len
= history_max_len
;
1480 /* Save the history in the specified file. On success 0 is returned
1481 * otherwise -1 is returned. */
1482 int linenoiseHistorySave(const char *filename
) {
1483 FILE *fp
= fopen(filename
,"w");
1486 if (fp
== NULL
) return -1;
1487 for (j
= 0; j
< history_len
; j
++) {
1488 const char *str
= history
[j
];
1489 /* Need to encode backslash, nl and cr */
1494 else if (*str
== '\n') {
1497 else if (*str
== '\r') {
1512 /* Load the history from the specified file. If the file does not exist
1513 * zero is returned and no operation is performed.
1515 * If the file exists and the operation succeeded 0 is returned, otherwise
1516 * on error -1 is returned. */
1517 int linenoiseHistoryLoad(const char *filename
) {
1518 FILE *fp
= fopen(filename
,"r");
1519 char buf
[LINENOISE_MAX_LINE
];
1521 if (fp
== NULL
) return -1;
1523 while (fgets(buf
,LINENOISE_MAX_LINE
,fp
) != NULL
) {
1526 /* Decode backslash escaped values */
1527 for (src
= dest
= buf
; *src
; src
++) {
1535 else if (*src
== 'r') {
1543 /* Remove trailing newline */
1544 if (dest
!= buf
&& (dest
[-1] == '\n' || dest
[-1] == '\r')) {
1549 linenoiseHistoryAdd(buf
);
1555 /* Provide access to the history buffer.
1557 * If 'len' is not NULL, the length is stored in *len.
1559 char **linenoiseHistory(int *len
) {