]> git.lizzy.rs Git - linenoise.git/blob - linenoise.c
Fix a linenoise bug when moving off the left
[linenoise.git] / linenoise.c
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.
3  *
4  * You can find the latest source code at:
5  *
6  *   http://github.com/msteveb/linenoise
7  *   (forked from http://github.com/antirez/linenoise)
8  *
9  * Does a number of crazy assumptions that happen to be true in 99.9999% of
10  * the 2010 UNIX computers around.
11  *
12  * ------------------------------------------------------------------------
13  *
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>
17  *
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions are
22  * met:
23  *
24  *  *  Redistributions of source code must retain the above copyright
25  *     notice, this list of conditions and the following disclaimer.
26  *
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.
30  *
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.
42  *
43  * ------------------------------------------------------------------------
44  *
45  * References:
46  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48  *
49  * Bloat:
50  * - Completion?
51  *
52  * Unix/termios
53  * ------------
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.
58  *
59  * CHA (Cursor Horizontal Absolute)
60  *    Sequence: ESC [ n G
61  *    Effect: moves cursor to column n (1 based)
62  *
63  * EL (Erase Line)
64  *    Sequence: ESC [ n K
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
68  *
69  * CUF (CUrsor Forward)
70  *    Sequence: ESC [ n C
71  *    Effect: moves cursor forward of n chars
72  *
73  * The following are used to clear the screen: ESC [ H ESC [ 2 J
74  * This is actually composed of two sequences:
75  *
76  * cursorhome
77  *    Sequence: ESC [ H
78  *    Effect: moves the cursor to upper left corner
79  *
80  * ED2 (Clear entire screen)
81  *    Sequence: ESC [ 2 J
82  *    Effect: clear the whole screen
83  *
84  * == For highlighting control characters, we also use the following two ==
85  * SO (enter StandOut)
86  *    Sequence: ESC [ 7 m
87  *    Effect: Uses some standout mode such as reverse video
88  *
89  * SE (Standout End)
90  *    Sequence: ESC [ 0 m
91  *    Effect: Exit standout mode
92  *
93  * == Only used if TIOCGWINSZ fails ==
94  * DSR/CPR (Report cursor position)
95  *    Sequence: ESC [ 6 n
96  *    Effect: reports current cursor position as ESC [ NNN ; MMM R
97  *
98  * win32/console
99  * -------------
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.
103  */
104
105 #ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
106 #include <windows.h>
107 #include <fcntl.h>
108 #define USE_WINCONSOLE
109 #ifdef __MINGW32__
110 #define HAVE_UNISTD_H
111 #else
112 /* Microsoft headers don't like old POSIX names */
113 #define strdup _strdup
114 #define snprintf _snprintf
115 #endif
116 #else
117 #include <termios.h>
118 #include <sys/ioctl.h>
119 #include <sys/poll.h>
120 #define USE_TERMIOS
121 #define HAVE_UNISTD_H
122 #endif
123
124 #ifdef HAVE_UNISTD_H
125 #include <unistd.h>
126 #endif
127 #include <stdlib.h>
128 #include <stdarg.h>
129 #include <stdio.h>
130 #include <errno.h>
131 #include <string.h>
132 #include <stdlib.h>
133 #include <sys/types.h>
134
135 #include "linenoise.h"
136 #include "utf8.h"
137
138 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
139 #define LINENOISE_MAX_LINE 4096
140
141 #define ctrl(C) ((C) - '@')
142
143 /* Use -ve numbers here to co-exist with normal unicode chars */
144 enum {
145     SPECIAL_NONE,
146     SPECIAL_UP = -20,
147     SPECIAL_DOWN = -21,
148     SPECIAL_LEFT = -22,
149     SPECIAL_RIGHT = -23,
150     SPECIAL_DELETE = -24,
151     SPECIAL_HOME = -25,
152     SPECIAL_END = -26,
153 };
154
155 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
156 static int history_len = 0;
157 static char **history = NULL;
158
159 /* Structure to contain the status of the current (being edited) line */
160 struct current {
161     char *buf;  /* Current buffer. Always null terminated */
162     int bufmax; /* Size of the buffer, including space for the null termination */
163     int len;    /* Number of bytes in 'buf' */
164     int chars;  /* Number of chars in 'buf' (utf-8 chars) */
165     int pos;    /* Cursor position, measured in chars */
166     int cols;   /* Size of the window, in chars */
167     const char *prompt;
168 #if defined(USE_TERMIOS)
169     int fd;     /* Terminal fd */
170 #elif defined(USE_WINCONSOLE)
171     HANDLE outh; /* Console output handle */
172     HANDLE inh; /* Console input handle */
173     int rows;   /* Screen rows */
174     int x;      /* Current column during output */
175     int y;      /* Current row */
176 #endif
177 };
178
179 static int fd_read(struct current *current);
180 static int getWindowSize(struct current *current);
181
182 void linenoiseHistoryFree(void) {
183     if (history) {
184         int j;
185
186         for (j = 0; j < history_len; j++)
187             free(history[j]);
188         free(history);
189         history = NULL;
190     }
191 }
192
193 #if defined(USE_TERMIOS)
194 static void linenoiseAtExit(void);
195 static struct termios orig_termios; /* in order to restore at exit */
196 static int rawmode = 0; /* for atexit() function to check if restore is needed*/
197 static int atexit_registered = 0; /* register atexit just 1 time */
198
199 static const char *unsupported_term[] = {"dumb","cons25",NULL};
200
201 static int isUnsupportedTerm(void) {
202     char *term = getenv("TERM");
203
204     if (term) {
205         int j;
206         for (j = 0; unsupported_term[j]; j++) {
207             if (strcasecmp(term, unsupported_term[j]) == 0) {
208                 return 1;
209             }
210         }
211     }
212     return 0;
213 }
214
215 static int enableRawMode(struct current *current) {
216     struct termios raw;
217
218     current->fd = STDIN_FILENO;
219
220     if (!isatty(current->fd) || isUnsupportedTerm() ||
221         tcgetattr(current->fd, &orig_termios) == -1) {
222 fatal:
223         errno = ENOTTY;
224         return -1;
225     }
226
227     if (!atexit_registered) {
228         atexit(linenoiseAtExit);
229         atexit_registered = 1;
230     }
231
232     raw = orig_termios;  /* modify the original mode */
233     /* input modes: no break, no CR to NL, no parity check, no strip char,
234      * no start/stop output control. */
235     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
236     /* output modes - disable post processing */
237     raw.c_oflag &= ~(OPOST);
238     /* control modes - set 8 bit chars */
239     raw.c_cflag |= (CS8);
240     /* local modes - choing off, canonical off, no extended functions,
241      * no signal chars (^Z,^C) */
242     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
243     /* control chars - set return condition: min number of bytes and timer.
244      * We want read to return every single byte, without timeout. */
245     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
246
247     /* put terminal in raw mode after flushing */
248     if (tcsetattr(current->fd,TCSADRAIN,&raw) < 0) {
249         goto fatal;
250     }
251     rawmode = 1;
252
253     current->cols = 0;
254     return 0;
255 }
256
257 static void disableRawMode(struct current *current) {
258     /* Don't even check the return value as it's too late. */
259     if (rawmode && tcsetattr(current->fd,TCSADRAIN,&orig_termios) != -1)
260         rawmode = 0;
261 }
262
263 /* At exit we'll try to fix the terminal to the initial conditions. */
264 static void linenoiseAtExit(void) {
265     if (rawmode) {
266         tcsetattr(STDIN_FILENO, TCSADRAIN, &orig_termios);
267     }
268     linenoiseHistoryFree();
269 }
270
271 /* gcc/glibc insists that we care about the return code of write! */
272 #define IGNORE_RC(EXPR) if (EXPR) {}
273
274 /* This is fdprintf() on some systems, but use a different
275  * name to avoid conflicts
276  */
277 static void fd_printf(int fd, const char *format, ...)
278 {
279     va_list args;
280     char buf[64];
281     int n;
282
283     va_start(args, format);
284     n = vsnprintf(buf, sizeof(buf), format, args);
285     va_end(args);
286     IGNORE_RC(write(fd, buf, n));
287 }
288
289 static void clearScreen(struct current *current)
290 {
291     fd_printf(current->fd, "\x1b[H\x1b[2J");
292 }
293
294 static void cursorToLeft(struct current *current)
295 {
296     fd_printf(current->fd, "\x1b[1G");
297 }
298
299 static int outputChars(struct current *current, const char *buf, int len)
300 {
301     return write(current->fd, buf, len);
302 }
303
304 static void outputControlChar(struct current *current, char ch)
305 {
306     fd_printf(current->fd, "\033[7m^%c\033[0m", ch);
307 }
308
309 static void eraseEol(struct current *current)
310 {
311     fd_printf(current->fd, "\x1b[0K");
312 }
313
314 static void setCursorPos(struct current *current, int x)
315 {
316     fd_printf(current->fd, "\x1b[1G\x1b[%dC", x);
317 }
318
319 /**
320  * Reads a char from 'fd', waiting at most 'timeout' milliseconds.
321  *
322  * A timeout of -1 means to wait forever.
323  *
324  * Returns -1 if no char is received within the time or an error occurs.
325  */
326 static int fd_read_char(int fd, int timeout)
327 {
328     struct pollfd p;
329     unsigned char c;
330
331     p.fd = fd;
332     p.events = POLLIN;
333
334     if (poll(&p, 1, timeout) == 0) {
335         /* timeout */
336         return -1;
337     }
338     if (read(fd, &c, 1) != 1) {
339         return -1;
340     }
341     return c;
342 }
343
344 /**
345  * Reads a complete utf-8 character
346  * and returns the unicode value, or -1 on error.
347  */
348 static int fd_read(struct current *current)
349 {
350 #ifdef USE_UTF8
351     char buf[4];
352     int n;
353     int i;
354     int c;
355
356     if (read(current->fd, &buf[0], 1) != 1) {
357         return -1;
358     }
359     n = utf8_charlen(buf[0]);
360     if (n < 1 || n > 3) {
361         return -1;
362     }
363     for (i = 1; i < n; i++) {
364         if (read(current->fd, &buf[i], 1) != 1) {
365             return -1;
366         }
367     }
368     buf[n] = 0;
369     /* decode and return the character */
370     utf8_tounicode(buf, &c);
371     return c;
372 #else
373     return fd_read_char(current->fd, -1);
374 #endif
375 }
376
377 static int getWindowSize(struct current *current)
378 {
379     struct winsize ws;
380
381     if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
382         current->cols = ws.ws_col;
383         return 0;
384     }
385
386     /* Failed to query the window size. Perhaps we are on a serial terminal.
387      * Try to query the width by sending the cursor as far to the right
388      * and reading back the cursor position.
389      * Note that this is only done once per call to linenoise rather than
390      * every time the line is refreshed for efficiency reasons.
391      */
392     if (current->cols == 0) {
393         current->cols = 80;
394
395         /* Move cursor far right and report cursor position */
396         fd_printf(current->fd, "\x1b[999G" "\x1b[6n");
397
398         /* Parse the response: ESC [ rows ; cols R */
399         if (fd_read_char(current->fd, 100) == 0x1b && fd_read_char(current->fd, 100) == '[') {
400             int n = 0;
401             while (1) {
402                 int ch = fd_read_char(current->fd, 100);
403                 if (ch == ';') {
404                     /* Ignore rows */
405                     n = 0;
406                 }
407                 else if (ch == 'R') {
408                     /* Got cols */
409                     if (n != 0 && n < 1000) {
410                         current->cols = n;
411                     }
412                     break;
413                 }
414                 else if (ch >= 0 && ch <= '9') {
415                     n = n * 10 + ch - '0';
416                 }
417                 else {
418                     break;
419                 }
420             }
421         }
422     }
423     return 0;
424 }
425
426 /**
427  * If escape (27) was received, reads subsequent
428  * chars to determine if this is a known special key.
429  *
430  * Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
431  *
432  * If no additional char is received within a short time,
433  * 27 is returned.
434  */
435 static int check_special(int fd)
436 {
437     int c = fd_read_char(fd, 50);
438     int c2;
439
440     if (c < 0) {
441         return 27;
442     }
443
444     c2 = fd_read_char(fd, 50);
445     if (c2 < 0) {
446         return c2;
447     }
448     if (c == '[' || c == 'O') {
449         /* Potential arrow key */
450         switch (c2) {
451             case 'A':
452                 return SPECIAL_UP;
453             case 'B':
454                 return SPECIAL_DOWN;
455             case 'C':
456                 return SPECIAL_RIGHT;
457             case 'D':
458                 return SPECIAL_LEFT;
459             case 'F':
460                 return SPECIAL_END;
461             case 'H':
462                 return SPECIAL_HOME;
463         }
464     }
465     if (c == '[' && c2 >= '1' && c2 <= '8') {
466         /* extended escape */
467         c = fd_read_char(fd, 50);
468         if (c == '~') {
469             switch (c2) {
470                 case '3':
471                     return SPECIAL_DELETE;
472                 case '7':
473                     return SPECIAL_HOME;
474                 case '8':
475                     return SPECIAL_END;
476             }
477         }
478         while (c != -1 && c != '~') {
479             /* .e.g \e[12~ or '\e[11;2~   discard the complete sequence */
480             c = fd_read_char(fd, 50);
481         }
482     }
483
484     return SPECIAL_NONE;
485 }
486 #elif defined(USE_WINCONSOLE)
487
488 static DWORD orig_consolemode = 0;
489
490 static int enableRawMode(struct current *current) {
491     DWORD n;
492     INPUT_RECORD irec;
493
494     current->outh = GetStdHandle(STD_OUTPUT_HANDLE);
495     current->inh = GetStdHandle(STD_INPUT_HANDLE);
496
497     if (!PeekConsoleInput(current->inh, &irec, 1, &n)) {
498         return -1;
499     }
500     if (getWindowSize(current) != 0) {
501         return -1;
502     }
503     if (GetConsoleMode(current->inh, &orig_consolemode)) {
504         SetConsoleMode(current->inh, ENABLE_PROCESSED_INPUT);
505     }
506     return 0;
507 }
508
509 static void disableRawMode(struct current *current)
510 {
511     SetConsoleMode(current->inh, orig_consolemode);
512 }
513
514 static void clearScreen(struct current *current)
515 {
516     COORD topleft = { 0, 0 };
517     DWORD n;
518
519     FillConsoleOutputCharacter(current->outh, ' ',
520         current->cols * current->rows, topleft, &n);
521     FillConsoleOutputAttribute(current->outh,
522         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN,
523         current->cols * current->rows, topleft, &n);
524     SetConsoleCursorPosition(current->outh, topleft);
525 }
526
527 static void cursorToLeft(struct current *current)
528 {
529     COORD pos = { 0, (SHORT)current->y };
530     DWORD n;
531
532     FillConsoleOutputAttribute(current->outh,
533         FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN, current->cols, pos, &n);
534     current->x = 0;
535 }
536
537 static int outputChars(struct current *current, const char *buf, int len)
538 {
539     COORD pos = { (SHORT)current->x, (SHORT)current->y };
540     DWORD n;
541         
542     WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n);
543     current->x += len;
544     return 0;
545 }
546
547 static void outputControlChar(struct current *current, char ch)
548 {
549     COORD pos = { (SHORT)current->x, (SHORT)current->y };
550     DWORD n;
551
552     FillConsoleOutputAttribute(current->outh, BACKGROUND_INTENSITY, 2, pos, &n);
553     outputChars(current, "^", 1);
554     outputChars(current, &ch, 1);
555 }
556
557 static void eraseEol(struct current *current)
558 {
559     COORD pos = { (SHORT)current->x, (SHORT)current->y };
560     DWORD n;
561
562     FillConsoleOutputCharacter(current->outh, ' ', current->cols - current->x, pos, &n);
563 }
564
565 static void setCursorPos(struct current *current, int x)
566 {
567     COORD pos = { (SHORT)x, (SHORT)current->y };
568
569     SetConsoleCursorPosition(current->outh, pos);
570     current->x = x;
571 }
572
573 static int fd_read(struct current *current)
574 {
575     while (1) {
576         INPUT_RECORD irec;
577         DWORD n;
578         if (WaitForSingleObject(current->inh, INFINITE) != WAIT_OBJECT_0) {
579             break;
580         }
581         if (!ReadConsoleInput (current->inh, &irec, 1, &n)) {
582             break;
583         }
584         if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown) {
585             KEY_EVENT_RECORD *k = &irec.Event.KeyEvent;
586             if (k->dwControlKeyState & ENHANCED_KEY) {
587                 switch (k->wVirtualKeyCode) {
588                  case VK_LEFT:
589                     return SPECIAL_LEFT;
590                  case VK_RIGHT:
591                     return SPECIAL_RIGHT;
592                  case VK_UP:
593                     return SPECIAL_UP;
594                  case VK_DOWN:
595                     return SPECIAL_DOWN;
596                  case VK_DELETE:
597                     return SPECIAL_DELETE;
598                  case VK_HOME:
599                     return SPECIAL_HOME;
600                  case VK_END:
601                     return SPECIAL_END;
602                 }
603             }
604             /* Note that control characters are already translated in AsciiChar */
605             else {
606 #ifdef USE_UTF8
607                 return k->uChar.UnicodeChar;
608 #else
609                 return k->uChar.AsciiChar;
610 #endif
611             }
612         }
613     }
614     return -1;
615 }
616
617 static int getWindowSize(struct current *current)
618 {
619     CONSOLE_SCREEN_BUFFER_INFO info;
620     if (!GetConsoleScreenBufferInfo(current->outh, &info)) {
621         return -1;
622     }
623     current->cols = info.dwSize.X;
624     current->rows = info.dwSize.Y;
625     if (current->cols <= 0 || current->rows <= 0) {
626         current->cols = 80;
627         return -1;
628     }
629     current->y = info.dwCursorPosition.Y;
630     current->x = info.dwCursorPosition.X;
631     return 0;
632 }
633 #endif
634
635 static int utf8_getchars(char *buf, int c)
636 {
637 #ifdef USE_UTF8
638     return utf8_fromunicode(buf, c);
639 #else
640     *buf = c;
641     return 1;
642 #endif
643 }
644
645 /**
646  * Returns the unicode character at the given offset,
647  * or -1 if none.
648  */
649 static int get_char(struct current *current, int pos)
650 {
651     if (pos >= 0 && pos < current->chars) {
652         int c;
653         int i = utf8_index(current->buf, pos);
654         (void)utf8_tounicode(current->buf + i, &c);
655         return c;
656     }
657     return -1;
658 }
659
660 static void refreshLine(const char *prompt, struct current *current)
661 {
662     int plen;
663     int pchars;
664     int backup = 0;
665     int i;
666     const char *buf = current->buf;
667     int chars = current->chars;
668     int pos = current->pos;
669     int b;
670     int ch;
671     int n;
672
673     /* Should intercept SIGWINCH. For now, just get the size every time */
674     getWindowSize(current);
675
676     plen = strlen(prompt);
677     pchars = utf8_strlen(prompt, plen);
678
679     /* Account for a line which is too long to fit in the window.
680      * Note that control chars require an extra column
681      */
682
683     /* How many cols are required to the left of 'pos'?
684      * The prompt, plus one extra for each control char
685      */
686     n = pchars + utf8_strlen(buf, current->len);
687     b = 0;
688     for (i = 0; i < pos; i++) {
689         b += utf8_tounicode(buf + b, &ch);
690         if (ch < ' ') {
691             n++;
692         }
693     }
694
695     /* If too many are need, strip chars off the front of 'buf'
696      * until it fits. Note that if the current char is a control character,
697      * we need one extra col.
698      */
699     if (current->pos < current->chars && get_char(current, current->pos) < ' ') {
700         n++;
701     }
702
703     while (n >= current->cols && pos > 0) {
704         b = utf8_tounicode(buf, &ch);
705         if (ch < ' ') {
706             n--;
707         }
708         n--;
709         buf += b;
710         pos--;
711         chars--;
712     }
713
714     /* Cursor to left edge, then the prompt */
715     cursorToLeft(current);
716     outputChars(current, prompt, plen);
717
718     /* Now the current buffer content */
719
720     /* Need special handling for control characters.
721      * If we hit 'cols', stop.
722      */
723     b = 0; /* unwritted bytes */
724     n = 0; /* How many control chars were written */
725     for (i = 0; i < chars; i++) {
726         int ch;
727         int w = utf8_tounicode(buf + b, &ch);
728         if (ch < ' ') {
729             n++;
730         }
731         if (pchars + i + n >= current->cols) {
732             break;
733         }
734         if (ch < ' ') {
735             /* A control character, so write the buffer so far */
736             outputChars(current, buf, b);
737             buf += b + w;
738             b = 0;
739             outputControlChar(current, ch + '@');
740             if (i < pos) {
741                 backup++;
742             }
743         }
744         else {
745             b += w;
746         }
747     }
748     outputChars(current, buf, b);
749
750     /* Erase to right, move cursor to original position */
751     eraseEol(current);
752     setCursorPos(current, pos + pchars + backup);
753 }
754
755 static void set_current(struct current *current, const char *str)
756 {
757     strncpy(current->buf, str, current->bufmax);
758     current->buf[current->bufmax - 1] = 0;
759     current->len = strlen(current->buf);
760     current->pos = current->chars = utf8_strlen(current->buf, current->len);
761 }
762
763 static int has_room(struct current *current, int bytes)
764 {
765     return current->len + bytes < current->bufmax - 1;
766 }
767
768 /**
769  * Removes the char at 'pos'.
770  *
771  * Returns 1 if the line needs to be refreshed, 2 if not
772  * and 0 if nothing was removed
773  */
774 static int remove_char(struct current *current, int pos)
775 {
776     if (pos >= 0 && pos < current->chars) {
777         int p1, p2;
778         int ret = 1;
779         p1 = utf8_index(current->buf, pos);
780         p2 = p1 + utf8_index(current->buf + p1, 1);
781
782 #ifdef USE_TERMIOS
783         /* optimise remove char in the case of removing the last char */
784         if (current->pos == pos + 1 && current->pos == current->chars) {
785             if (current->buf[pos] >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
786                 ret = 2;
787                 fd_printf(current->fd, "\b \b");
788             }
789         }
790 #endif
791
792         /* Move the null char too */
793         memmove(current->buf + p1, current->buf + p2, current->len - p2 + 1);
794         current->len -= (p2 - p1);
795         current->chars--;
796
797         if (current->pos > pos) {
798             current->pos--;
799         }
800         return ret;
801     }
802     return 0;
803 }
804
805 /**
806  * Insert 'ch' at position 'pos'
807  *
808  * Returns 1 if the line needs to be refreshed, 2 if not
809  * and 0 if nothing was inserted (no room)
810  */
811 static int insert_char(struct current *current, int pos, int ch)
812 {
813     char buf[3];
814     int n = utf8_getchars(buf, ch);
815
816     if (has_room(current, n) && pos >= 0 && pos <= current->chars) {
817         int p1, p2;
818         int ret = 1;
819         p1 = utf8_index(current->buf, pos);
820         p2 = p1 + n;
821
822 #ifdef USE_TERMIOS
823         /* optimise the case where adding a single char to the end and no scrolling is needed */
824         if (current->pos == pos && current->chars == pos) {
825             if (ch >= ' ' && utf8_strlen(current->prompt, -1) + utf8_strlen(current->buf, current->len) < current->cols - 1) {
826                 IGNORE_RC(write(current->fd, buf, n));
827                 ret = 2;
828             }
829         }
830 #endif
831
832         memmove(current->buf + p2, current->buf + p1, current->len - p1);
833         memcpy(current->buf + p1, buf, n);
834         current->len += n;
835
836         current->chars++;
837         if (current->pos >= pos) {
838             current->pos++;
839         }
840         return ret;
841     }
842     return 0;
843 }
844
845 /**
846  * Returns 0 if no chars were removed or non-zero otherwise.
847  */
848 static int remove_chars(struct current *current, int pos, int n)
849 {
850     int removed = 0;
851     while (n-- && remove_char(current, pos)) {
852         removed++;
853     }
854     return removed;
855 }
856
857 #ifndef NO_COMPLETION
858 static linenoiseCompletionCallback *completionCallback = NULL;
859
860 static void beep() {
861 #ifdef USE_TERMIOS
862     fprintf(stderr, "\x7");
863     fflush(stderr);
864 #endif
865 }
866
867 static void freeCompletions(linenoiseCompletions *lc) {
868     size_t i;
869     for (i = 0; i < lc->len; i++)
870         free(lc->cvec[i]);
871     free(lc->cvec);
872 }
873
874 static int completeLine(struct current *current) {
875     linenoiseCompletions lc = { 0, NULL };
876     int c = 0;
877
878     completionCallback(current->buf,&lc);
879     if (lc.len == 0) {
880         beep();
881     } else {
882         size_t stop = 0, i = 0;
883
884         while(!stop) {
885             /* Show completion or original buffer */
886             if (i < lc.len) {
887                 struct current tmp = *current;
888                 tmp.buf = lc.cvec[i];
889                 tmp.pos = tmp.len = strlen(tmp.buf);
890                 tmp.chars = utf8_strlen(tmp.buf, tmp.len);
891                 refreshLine(current->prompt, &tmp);
892             } else {
893                 refreshLine(current->prompt, current);
894             }
895
896             c = fd_read(current);
897             if (c == -1) {
898                 break;
899             }
900
901             switch(c) {
902                 case '\t': /* tab */
903                     i = (i+1) % (lc.len+1);
904                     if (i == lc.len) beep();
905                     break;
906                 case 27: /* escape */
907                     /* Re-show original buffer */
908                     if (i < lc.len) {
909                         refreshLine(current->prompt, current);
910                     }
911                     stop = 1;
912                     break;
913                 default:
914                     /* Update buffer and return */
915                     if (i < lc.len) {
916                         set_current(current,lc.cvec[i]);
917                     }
918                     stop = 1;
919                     break;
920             }
921         }
922     }
923
924     freeCompletions(&lc);
925     return c; /* Return last read character */
926 }
927
928 /* Register a callback function to be called for tab-completion. */
929 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
930     completionCallback = fn;
931 }
932
933 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
934     lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
935     lc->cvec[lc->len++] = strdup(str);
936 }
937
938 #endif
939
940 static int linenoisePrompt(struct current *current) {
941     int history_index = 0;
942
943     /* The latest history entry is always our current buffer, that
944      * initially is just an empty string. */
945     linenoiseHistoryAdd("");
946
947     set_current(current, "");
948     refreshLine(current->prompt, current);
949
950     while(1) {
951         int dir = -1;
952         int c = fd_read(current);
953
954 #ifndef NO_COMPLETION
955         /* Only autocomplete when the callback is set. It returns < 0 when
956          * there was an error reading from fd. Otherwise it will return the
957          * character that should be handled next. */
958         if (c == 9 && completionCallback != NULL) {
959             c = completeLine(current);
960             /* Return on errors */
961             if (c < 0) return current->len;
962             /* Read next character when 0 */
963             if (c == 0) continue;
964         }
965 #endif
966
967 process_char:
968         if (c == -1) return current->len;
969 #ifdef USE_TERMIOS
970         if (c == 27) {   /* escape sequence */
971             c = check_special(current->fd);
972         }
973 #endif
974         switch(c) {
975         case '\r':    /* enter */
976             history_len--;
977             free(history[history_len]);
978             return current->len;
979         case ctrl('C'):     /* ctrl-c */
980             errno = EAGAIN;
981             return -1;
982         case 127:   /* backspace */
983         case ctrl('H'):
984             if (remove_char(current, current->pos - 1) == 1) {
985                 refreshLine(current->prompt, current);
986             }
987             break;
988         case ctrl('D'):     /* ctrl-d */
989             if (current->len == 0) {
990                 /* Empty line, so EOF */
991                 history_len--;
992                 free(history[history_len]);
993                 return -1;
994             }
995             /* Otherwise fall through to delete char to right of cursor */
996         case SPECIAL_DELETE:
997             if (remove_char(current, current->pos) == 1) {
998                 refreshLine(current->prompt, current);
999             }
1000             break;
1001         case ctrl('W'):    /* ctrl-w */
1002             /* eat any spaces on the left */
1003             {
1004                 int pos = current->pos;
1005                 while (pos > 0 && get_char(current, pos - 1) == ' ') {
1006                     pos--;
1007                 }
1008
1009                 /* now eat any non-spaces on the left */
1010                 while (pos > 0 && get_char(current, pos - 1) != ' ') {
1011                     pos--;
1012                 }
1013
1014                 if (remove_chars(current, pos, current->pos - pos)) {
1015                     refreshLine(current->prompt, current);
1016                 }
1017             }
1018             break;
1019         case ctrl('R'):    /* ctrl-r */
1020             {
1021                 /* Display the reverse-i-search prompt and process chars */
1022                 char rbuf[50];
1023                 char rprompt[80];
1024                 int rchars = 0;
1025                 int rlen = 0;
1026                 int searchpos = history_len - 1;
1027
1028                 rbuf[0] = 0;
1029                 while (1) {
1030                     int n = 0;
1031                     const char *p = NULL;
1032                     int skipsame = 0;
1033                     int searchdir = -1;
1034
1035                     snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
1036                     refreshLine(rprompt, current);
1037                     c = fd_read(current);
1038                     if (c == ctrl('H') || c == 127) {
1039                         if (rchars) {
1040                             int p = utf8_index(rbuf, --rchars);
1041                             rbuf[p] = 0;
1042                             rlen = strlen(rbuf);
1043                         }
1044                         continue;
1045                     }
1046 #ifdef USE_TERMIOS
1047                     if (c == 27) {
1048                         c = check_special(current->fd);
1049                     }
1050 #endif
1051                     if (c == ctrl('P') || c == SPECIAL_UP) {
1052                         /* Search for the previous (earlier) match */
1053                         if (searchpos > 0) {
1054                             searchpos--;
1055                         }
1056                         skipsame = 1;
1057                     }
1058                     else if (c == ctrl('N') || c == SPECIAL_DOWN) {
1059                         /* Search for the next (later) match */
1060                         if (searchpos < history_len) {
1061                             searchpos++;
1062                         }
1063                         searchdir = 1;
1064                         skipsame = 1;
1065                     }
1066                     else if (c >= ' ') {
1067                         if (rlen >= (int)sizeof(rbuf) + 3) {
1068                             continue;
1069                         }
1070
1071                         n = utf8_getchars(rbuf + rlen, c);
1072                         rlen += n;
1073                         rchars++;
1074                         rbuf[rlen] = 0;
1075
1076                         /* Adding a new char resets the search location */
1077                         searchpos = history_len - 1;
1078                     }
1079                     else {
1080                         /* Exit from incremental search mode */
1081                         break;
1082                     }
1083
1084                     /* Now search through the history for a match */
1085                     for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
1086                         p = strstr(history[searchpos], rbuf);
1087                         if (p) {
1088                             /* Found a match */
1089                             if (skipsame && strcmp(history[searchpos], current->buf) == 0) {
1090                                 /* But it is identical, so skip it */
1091                                 continue;
1092                             }
1093                             /* Copy the matching line and set the cursor position */
1094                             set_current(current,history[searchpos]);
1095                             current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
1096                             break;
1097                         }
1098                     }
1099                     if (!p && n) {
1100                         /* No match, so don't add it */
1101                         rchars--;
1102                         rlen -= n;
1103                         rbuf[rlen] = 0;
1104                     }
1105                 }
1106                 if (c == ctrl('G') || c == ctrl('C')) {
1107                     /* ctrl-g terminates the search with no effect */
1108                     set_current(current, "");
1109                     c = 0;
1110                 }
1111                 else if (c == ctrl('J')) {
1112                     /* ctrl-j terminates the search leaving the buffer in place */
1113                     c = 0;
1114                 }
1115                 /* Go process the char normally */
1116                 refreshLine(current->prompt, current);
1117                 goto process_char;
1118             }
1119             break;
1120         case ctrl('T'):    /* ctrl-t */
1121             if (current->pos > 0 && current->pos < current->chars) {
1122                 c = get_char(current, current->pos);
1123                 remove_char(current, current->pos);
1124                 insert_char(current, current->pos - 1, c);
1125                 refreshLine(current->prompt, current);
1126             }
1127             break;
1128         case ctrl('V'):    /* ctrl-v */
1129             if (has_room(current, 3)) {
1130                 /* Insert the ^V first */
1131                 if (insert_char(current, current->pos, c)) {
1132                     refreshLine(current->prompt, current);
1133                     /* Now wait for the next char. Can insert anything except \0 */
1134                     c = fd_read(current);
1135
1136                     /* Remove the ^V first */
1137                     remove_char(current, current->pos - 1);
1138                     if (c != -1) {
1139                         /* Insert the actual char */
1140                         insert_char(current, current->pos, c);
1141                     }
1142                     refreshLine(current->prompt, current);
1143                 }
1144             }
1145             break;
1146         case ctrl('B'):
1147         case SPECIAL_LEFT:
1148             if (current->pos > 0) {
1149                 current->pos--;
1150                 refreshLine(current->prompt, current);
1151             }
1152             break;
1153         case ctrl('F'):
1154         case SPECIAL_RIGHT:
1155             if (current->pos < current->chars) {
1156                 current->pos++;
1157                 refreshLine(current->prompt, current);
1158             }
1159             break;
1160         case ctrl('P'):
1161         case SPECIAL_UP:
1162             dir = 1;
1163         case ctrl('N'):
1164         case SPECIAL_DOWN:
1165             if (history_len > 1) {
1166                 /* Update the current history entry before to
1167                  * overwrite it with tne next one. */
1168                 free(history[history_len-1-history_index]);
1169                 history[history_len-1-history_index] = strdup(current->buf);
1170                 /* Show the new entry */
1171                 history_index += dir;
1172                 if (history_index < 0) {
1173                     history_index = 0;
1174                     break;
1175                 } else if (history_index >= history_len) {
1176                     history_index = history_len-1;
1177                     break;
1178                 }
1179                 set_current(current, history[history_len-1-history_index]);
1180                 refreshLine(current->prompt, current);
1181             }
1182             break;
1183         case ctrl('A'): /* Ctrl+a, go to the start of the line */
1184         case SPECIAL_HOME:
1185             current->pos = 0;
1186             refreshLine(current->prompt, current);
1187             break;
1188         case ctrl('E'): /* ctrl+e, go to the end of the line */
1189         case SPECIAL_END:
1190             current->pos = current->chars;
1191             refreshLine(current->prompt, current);
1192             break;
1193         case ctrl('U'): /* Ctrl+u, delete to beginning of line. */
1194             if (remove_chars(current, 0, current->pos)) {
1195                 refreshLine(current->prompt, current);
1196             }
1197             break;
1198         case ctrl('K'): /* Ctrl+k, delete from current to end of line. */
1199             if (remove_chars(current, current->pos, current->chars - current->pos)) {
1200                 refreshLine(current->prompt, current);
1201             }
1202             break;
1203         case ctrl('L'): /* Ctrl+L, clear screen */
1204             clearScreen(current);
1205             /* Force recalc of window size for serial terminals */
1206             current->cols = 0;
1207             refreshLine(current->prompt, current);
1208             break;
1209         default:
1210             /* Only tab is allowed without ^V */
1211             if (c == '\t' || c >= ' ') {
1212                 if (insert_char(current, current->pos, c) == 1) {
1213                     refreshLine(current->prompt, current);
1214                 }
1215             }
1216             break;
1217         }
1218     }
1219     return current->len;
1220 }
1221
1222 char *linenoise(const char *prompt)
1223 {
1224     int count;
1225     struct current current;
1226     char buf[LINENOISE_MAX_LINE];
1227
1228     if (enableRawMode(&current) == -1) {
1229         printf("%s", prompt);
1230         fflush(stdout);
1231         if (fgets(buf, sizeof(buf), stdin) == NULL) {
1232                 return NULL;
1233         }
1234         count = strlen(buf);
1235         if (count && buf[count-1] == '\n') {
1236             count--;
1237             buf[count] = '\0';
1238         }
1239     }
1240     else
1241     {
1242         current.buf = buf;
1243         current.bufmax = sizeof(buf);
1244         current.len = 0;
1245         current.chars = 0;
1246         current.pos = 0;
1247         current.prompt = prompt;
1248
1249         count = linenoisePrompt(&current);
1250         disableRawMode(&current);
1251         printf("\n");
1252         if (count == -1) {
1253             return NULL;
1254         }
1255     }
1256     return strdup(buf);
1257 }
1258
1259 /* Using a circular buffer is smarter, but a bit more complex to handle. */
1260 int linenoiseHistoryAdd(const char *line) {
1261     char *linecopy;
1262
1263     if (history_max_len == 0) return 0;
1264     if (history == NULL) {
1265         history = (char **)malloc(sizeof(char*)*history_max_len);
1266         if (history == NULL) return 0;
1267         memset(history,0,(sizeof(char*)*history_max_len));
1268     }
1269
1270     /* do not insert duplicate lines into history */
1271     if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
1272         return 0;
1273     }
1274
1275     linecopy = strdup(line);
1276     if (!linecopy) return 0;
1277     if (history_len == history_max_len) {
1278         free(history[0]);
1279         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1280         history_len--;
1281     }
1282     history[history_len] = linecopy;
1283     history_len++;
1284     return 1;
1285 }
1286
1287 int linenoiseHistorySetMaxLen(int len) {
1288     char **newHistory;
1289
1290     if (len < 1) return 0;
1291     if (history) {
1292         int tocopy = history_len;
1293
1294         newHistory = (char **)malloc(sizeof(char*)*len);
1295         if (newHistory == NULL) return 0;
1296         if (len < tocopy) tocopy = len;
1297         memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
1298         free(history);
1299         history = newHistory;
1300     }
1301     history_max_len = len;
1302     if (history_len > history_max_len)
1303         history_len = history_max_len;
1304     return 1;
1305 }
1306
1307 /* Save the history in the specified file. On success 0 is returned
1308  * otherwise -1 is returned. */
1309 int linenoiseHistorySave(const char *filename) {
1310     FILE *fp = fopen(filename,"w");
1311     int j;
1312
1313     if (fp == NULL) return -1;
1314     for (j = 0; j < history_len; j++) {
1315         const char *str = history[j];
1316         /* Need to encode backslash, nl and cr */
1317         while (*str) {
1318             if (*str == '\\') {
1319                 fputs("\\\\", fp);
1320             }
1321             else if (*str == '\n') {
1322                 fputs("\\n", fp);
1323             }
1324             else if (*str == '\r') {
1325                 fputs("\\r", fp);
1326             }
1327             else {
1328                 fputc(*str, fp);
1329             }
1330             str++;
1331         }
1332         fputc('\n', fp);
1333     }
1334
1335     fclose(fp);
1336     return 0;
1337 }
1338
1339 /* Load the history from the specified file. If the file does not exist
1340  * zero is returned and no operation is performed.
1341  *
1342  * If the file exists and the operation succeeded 0 is returned, otherwise
1343  * on error -1 is returned. */
1344 int linenoiseHistoryLoad(const char *filename) {
1345     FILE *fp = fopen(filename,"r");
1346     char buf[LINENOISE_MAX_LINE];
1347
1348     if (fp == NULL) return -1;
1349
1350     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1351         char *src, *dest;
1352
1353         /* Decode backslash escaped values */
1354         for (src = dest = buf; *src; src++) {
1355             char ch = *src;
1356
1357             if (ch == '\\') {
1358                 src++;
1359                 if (*src == 'n') {
1360                     ch = '\n';
1361                 }
1362                 else if (*src == 'r') {
1363                     ch = '\r';
1364                 } else {
1365                     ch = *src;
1366                 }
1367             }
1368             *dest++ = ch;
1369         }
1370         /* Remove trailing newline */
1371         if (dest != buf && (dest[-1] == '\n' || dest[-1] == '\r')) {
1372             dest--;
1373         }
1374         *dest = 0;
1375
1376         linenoiseHistoryAdd(buf);
1377     }
1378     fclose(fp);
1379     return 0;
1380 }
1381
1382 /* Provide access to the history buffer.
1383  *
1384  * If 'len' is not NULL, the length is stored in *len.
1385  */
1386 char **linenoiseHistory(int *len) {
1387     if (len) {
1388         *len = history_len;
1389     }
1390     return history;
1391 }