1*22028508SToomas Soome /* linenoise.c -- VERSION 1.0
2*22028508SToomas Soome  *
3*22028508SToomas Soome  * Guerrilla line editing library against the idea that a line editing lib
4*22028508SToomas Soome  * needs to be 20,000 lines of C code.
5*22028508SToomas Soome  *
6*22028508SToomas Soome  * You can find the latest source code at:
7*22028508SToomas Soome  *
8*22028508SToomas Soome  *   http://github.com/antirez/linenoise
9*22028508SToomas Soome  *
10*22028508SToomas Soome  * Does a number of crazy assumptions that happen to be true in 99.9999% of
11*22028508SToomas Soome  * the 2010 UNIX computers around.
12*22028508SToomas Soome  *
13*22028508SToomas Soome  * ------------------------------------------------------------------------
14*22028508SToomas Soome  *
15*22028508SToomas Soome  * Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
16*22028508SToomas Soome  * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
17*22028508SToomas Soome  *
18*22028508SToomas Soome  * All rights reserved.
19*22028508SToomas Soome  *
20*22028508SToomas Soome  * Redistribution and use in source and binary forms, with or without
21*22028508SToomas Soome  * modification, are permitted provided that the following conditions are
22*22028508SToomas Soome  * met:
23*22028508SToomas Soome  *
24*22028508SToomas Soome  *  *  Redistributions of source code must retain the above copyright
25*22028508SToomas Soome  *     notice, this list of conditions and the following disclaimer.
26*22028508SToomas Soome  *
27*22028508SToomas Soome  *  *  Redistributions in binary form must reproduce the above copyright
28*22028508SToomas Soome  *     notice, this list of conditions and the following disclaimer in the
29*22028508SToomas Soome  *     documentation and/or other materials provided with the distribution.
30*22028508SToomas Soome  *
31*22028508SToomas Soome  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32*22028508SToomas Soome  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33*22028508SToomas Soome  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34*22028508SToomas Soome  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35*22028508SToomas Soome  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36*22028508SToomas Soome  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37*22028508SToomas Soome  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38*22028508SToomas Soome  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39*22028508SToomas Soome  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40*22028508SToomas Soome  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41*22028508SToomas Soome  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42*22028508SToomas Soome  *
43*22028508SToomas Soome  * ------------------------------------------------------------------------
44*22028508SToomas Soome  *
45*22028508SToomas Soome  * References:
46*22028508SToomas Soome  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47*22028508SToomas Soome  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48*22028508SToomas Soome  *
49*22028508SToomas Soome  * Todo list:
50*22028508SToomas Soome  * - Filter bogus Ctrl+<char> combinations.
51*22028508SToomas Soome  * - Win32 support
52*22028508SToomas Soome  *
53*22028508SToomas Soome  * Bloat:
54*22028508SToomas Soome  * - History search like Ctrl+r in readline?
55*22028508SToomas Soome  *
56*22028508SToomas Soome  * List of escape sequences used by this program, we do everything just
57*22028508SToomas Soome  * with three sequences. In order to be so cheap we may have some
58*22028508SToomas Soome  * flickering effect with some slow terminal, but the lesser sequences
59*22028508SToomas Soome  * the more compatible.
60*22028508SToomas Soome  *
61*22028508SToomas Soome  * EL (Erase Line)
62*22028508SToomas Soome  *    Sequence: ESC [ n K
63*22028508SToomas Soome  *    Effect: if n is 0 or missing, clear from cursor to end of line
64*22028508SToomas Soome  *    Effect: if n is 1, clear from beginning of line to cursor
65*22028508SToomas Soome  *    Effect: if n is 2, clear entire line
66*22028508SToomas Soome  *
67*22028508SToomas Soome  * CUF (CUrsor Forward)
68*22028508SToomas Soome  *    Sequence: ESC [ n C
69*22028508SToomas Soome  *    Effect: moves cursor forward n chars
70*22028508SToomas Soome  *
71*22028508SToomas Soome  * CUB (CUrsor Backward)
72*22028508SToomas Soome  *    Sequence: ESC [ n D
73*22028508SToomas Soome  *    Effect: moves cursor backward n chars
74*22028508SToomas Soome  *
75*22028508SToomas Soome  * The following is used to get the terminal width if getting
76*22028508SToomas Soome  * the width with the TIOCGWINSZ ioctl fails
77*22028508SToomas Soome  *
78*22028508SToomas Soome  * DSR (Device Status Report)
79*22028508SToomas Soome  *    Sequence: ESC [ 6 n
80*22028508SToomas Soome  *    Effect: reports the current cusor position as ESC [ n ; m R
81*22028508SToomas Soome  *            where n is the row and m is the column
82*22028508SToomas Soome  *
83*22028508SToomas Soome  * When multi line mode is enabled, we also use an additional escape
84*22028508SToomas Soome  * sequence. However multi line editing is disabled by default.
85*22028508SToomas Soome  *
86*22028508SToomas Soome  * CUU (Cursor Up)
87*22028508SToomas Soome  *    Sequence: ESC [ n A
88*22028508SToomas Soome  *    Effect: moves cursor up of n chars.
89*22028508SToomas Soome  *
90*22028508SToomas Soome  * CUD (Cursor Down)
91*22028508SToomas Soome  *    Sequence: ESC [ n B
92*22028508SToomas Soome  *    Effect: moves cursor down of n chars.
93*22028508SToomas Soome  *
94*22028508SToomas Soome  * When linenoiseClearScreen() is called, two additional escape sequences
95*22028508SToomas Soome  * are used in order to clear the screen and position the cursor at home
96*22028508SToomas Soome  * position.
97*22028508SToomas Soome  *
98*22028508SToomas Soome  * CUP (Cursor position)
99*22028508SToomas Soome  *    Sequence: ESC [ H
100*22028508SToomas Soome  *    Effect: moves the cursor to upper left corner
101*22028508SToomas Soome  *
102*22028508SToomas Soome  * ED (Erase display)
103*22028508SToomas Soome  *    Sequence: ESC [ 2 J
104*22028508SToomas Soome  *    Effect: clear the whole screen
105*22028508SToomas Soome  *
106*22028508SToomas Soome  */
107*22028508SToomas Soome 
108*22028508SToomas Soome #include <stand.h>
109*22028508SToomas Soome #include "linenoise.h"
110*22028508SToomas Soome #include "bootstrap.h"
111*22028508SToomas Soome 
112*22028508SToomas Soome #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
113*22028508SToomas Soome #define LINENOISE_MAX_LINE 256
114*22028508SToomas Soome static linenoiseCompletionCallback *completionCallback = NULL;
115*22028508SToomas Soome 
116*22028508SToomas Soome static int mlmode = 1;  /* Multi line mode. Default is single line. */
117*22028508SToomas Soome static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
118*22028508SToomas Soome static int history_len = 0;
119*22028508SToomas Soome static char **history = NULL;
120*22028508SToomas Soome 
121*22028508SToomas Soome /* The linenoiseState structure represents the state during line editing.
122*22028508SToomas Soome  * We pass this state to functions implementing specific editing
123*22028508SToomas Soome  * functionalities. */
124*22028508SToomas Soome struct linenoiseState {
125*22028508SToomas Soome     char *buf;          /* Edited line buffer. */
126*22028508SToomas Soome     size_t buflen;      /* Edited line buffer size. */
127*22028508SToomas Soome     const char *prompt; /* Prompt to display. */
128*22028508SToomas Soome     size_t plen;        /* Prompt length. */
129*22028508SToomas Soome     size_t pos;         /* Current cursor position. */
130*22028508SToomas Soome     size_t oldpos;      /* Previous refresh cursor position. */
131*22028508SToomas Soome     size_t len;         /* Current edited line length. */
132*22028508SToomas Soome     size_t cols;        /* Number of columns in terminal. */
133*22028508SToomas Soome     size_t maxrows;     /* Maximum num of rows used so far (multiline mode) */
134*22028508SToomas Soome     int history_index;  /* The history index we are currently editing. */
135*22028508SToomas Soome };
136*22028508SToomas Soome 
137*22028508SToomas Soome enum KEY_ACTION{
138*22028508SToomas Soome 	KEY_NULL = 0,	    /* NULL */
139*22028508SToomas Soome 	CTRL_A = 1,         /* Ctrl+a */
140*22028508SToomas Soome 	CTRL_B = 2,         /* Ctrl-b */
141*22028508SToomas Soome 	CTRL_C = 3,         /* Ctrl-c */
142*22028508SToomas Soome 	CTRL_D = 4,         /* Ctrl-d */
143*22028508SToomas Soome 	CTRL_E = 5,         /* Ctrl-e */
144*22028508SToomas Soome 	CTRL_F = 6,         /* Ctrl-f */
145*22028508SToomas Soome 	CTRL_H = 8,         /* Ctrl-h */
146*22028508SToomas Soome 	TAB = 9,            /* Tab */
147*22028508SToomas Soome 	CTRL_K = 11,        /* Ctrl+k */
148*22028508SToomas Soome 	CTRL_L = 12,        /* Ctrl+l */
149*22028508SToomas Soome 	ENTER = 13,         /* Enter */
150*22028508SToomas Soome 	CTRL_N = 14,        /* Ctrl-n */
151*22028508SToomas Soome 	CTRL_P = 16,        /* Ctrl-p */
152*22028508SToomas Soome 	CTRL_T = 20,        /* Ctrl-t */
153*22028508SToomas Soome 	CTRL_U = 21,        /* Ctrl+u */
154*22028508SToomas Soome 	CTRL_W = 23,        /* Ctrl+w */
155*22028508SToomas Soome 	ESC = 27,           /* Escape */
156*22028508SToomas Soome 	BACKSPACE =  127    /* Backspace */
157*22028508SToomas Soome };
158*22028508SToomas Soome 
159*22028508SToomas Soome static void refreshLine(struct linenoiseState *l);
160*22028508SToomas Soome 
161*22028508SToomas Soome /* ======================= Low level terminal handling ====================== */
162*22028508SToomas Soome 
163*22028508SToomas Soome static int
put_bytes(const char * s,int len)164*22028508SToomas Soome put_bytes(const char *s, int len)
165*22028508SToomas Soome {
166*22028508SToomas Soome     int i;
167*22028508SToomas Soome     if (s == NULL)
168*22028508SToomas Soome 	return -1;
169*22028508SToomas Soome 
170*22028508SToomas Soome     for (i = 0; i < len; i++)
171*22028508SToomas Soome 	putchar(s[i]);
172*22028508SToomas Soome     return (i);
173*22028508SToomas Soome }
174*22028508SToomas Soome 
175*22028508SToomas Soome /* Set if to use or not the multi line mode. */
linenoiseSetMultiLine(int ml)176*22028508SToomas Soome void linenoiseSetMultiLine(int ml) {
177*22028508SToomas Soome     mlmode = ml;
178*22028508SToomas Soome }
179*22028508SToomas Soome 
180*22028508SToomas Soome /* Clear the screen. Used to handle ctrl+l */
linenoiseClearScreen(void)181*22028508SToomas Soome void linenoiseClearScreen(void) {
182*22028508SToomas Soome     if (put_bytes("\x1b[H\x1b[J", 6) <= 0) {
183*22028508SToomas Soome         /* nothing to do, just to avoid warning. */
184*22028508SToomas Soome     }
185*22028508SToomas Soome }
186*22028508SToomas Soome 
187*22028508SToomas Soome static int
getColumns(void)188*22028508SToomas Soome getColumns(void)
189*22028508SToomas Soome {
190*22028508SToomas Soome 	char *columns = getenv("screen-#cols");
191*22028508SToomas Soome 	if (columns == NULL)
192*22028508SToomas Soome 		return (80);
193*22028508SToomas Soome 	return (strtol(columns, NULL, 0));
194*22028508SToomas Soome }
195*22028508SToomas Soome 
196*22028508SToomas Soome /* Beep, used for completion when there is nothing to complete or when all
197*22028508SToomas Soome  * the choices were already shown. */
linenoiseBeep(void)198*22028508SToomas Soome static void linenoiseBeep(void) {
199*22028508SToomas Soome     put_bytes("\x7", 1);
200*22028508SToomas Soome }
201*22028508SToomas Soome 
202*22028508SToomas Soome /* ============================== Completion ================================ */
203*22028508SToomas Soome 
204*22028508SToomas Soome /* Free a list of completion option populated by linenoiseAddCompletion(). */
freeCompletions(linenoiseCompletions * lc)205*22028508SToomas Soome static void freeCompletions(linenoiseCompletions *lc) {
206*22028508SToomas Soome     size_t i;
207*22028508SToomas Soome     for (i = 0; i < lc->len; i++)
208*22028508SToomas Soome         free(lc->cvec[i]);
209*22028508SToomas Soome     if (lc->cvec != NULL)
210*22028508SToomas Soome         free(lc->cvec);
211*22028508SToomas Soome }
212*22028508SToomas Soome 
213*22028508SToomas Soome /* This is an helper function for linenoiseEdit() and is called when the
214*22028508SToomas Soome  * user types the <tab> key in order to complete the string currently in the
215*22028508SToomas Soome  * input.
216*22028508SToomas Soome  *
217*22028508SToomas Soome  * The state of the editing is encapsulated into the pointed linenoiseState
218*22028508SToomas Soome  * structure as described in the structure definition. */
completeLine(struct linenoiseState * ls)219*22028508SToomas Soome static int completeLine(struct linenoiseState *ls) {
220*22028508SToomas Soome     linenoiseCompletions lc = { 0, NULL };
221*22028508SToomas Soome     int nwritten;
222*22028508SToomas Soome     char c = 0;
223*22028508SToomas Soome 
224*22028508SToomas Soome     completionCallback(ls->buf,&lc);
225*22028508SToomas Soome     if (lc.len == 0) {
226*22028508SToomas Soome         linenoiseBeep();
227*22028508SToomas Soome     } else {
228*22028508SToomas Soome         size_t stop = 0, i = 0;
229*22028508SToomas Soome 
230*22028508SToomas Soome         while(!stop) {
231*22028508SToomas Soome             /* Show completion or original buffer */
232*22028508SToomas Soome             if (i < lc.len) {
233*22028508SToomas Soome                 struct linenoiseState saved = *ls;
234*22028508SToomas Soome 
235*22028508SToomas Soome                 ls->len = ls->pos = strlen(lc.cvec[i]);
236*22028508SToomas Soome                 ls->buf = lc.cvec[i];
237*22028508SToomas Soome                 refreshLine(ls);
238*22028508SToomas Soome                 ls->len = saved.len;
239*22028508SToomas Soome                 ls->pos = saved.pos;
240*22028508SToomas Soome                 ls->buf = saved.buf;
241*22028508SToomas Soome             } else {
242*22028508SToomas Soome                 refreshLine(ls);
243*22028508SToomas Soome             }
244*22028508SToomas Soome 
245*22028508SToomas Soome             c = getchar();
246*22028508SToomas Soome             if (c <= 0) {
247*22028508SToomas Soome                 freeCompletions(&lc);
248*22028508SToomas Soome                 return -1;
249*22028508SToomas Soome             }
250*22028508SToomas Soome 
251*22028508SToomas Soome             switch(c) {
252*22028508SToomas Soome                 case 9: /* tab */
253*22028508SToomas Soome                     i = (i+1) % (lc.len+1);
254*22028508SToomas Soome                     if (i == lc.len) linenoiseBeep();
255*22028508SToomas Soome                     break;
256*22028508SToomas Soome                 case 27: /* escape */
257*22028508SToomas Soome                     /* Re-show original buffer */
258*22028508SToomas Soome                     if (i < lc.len) refreshLine(ls);
259*22028508SToomas Soome                     stop = 1;
260*22028508SToomas Soome                     break;
261*22028508SToomas Soome                 default:
262*22028508SToomas Soome                     /* Update buffer and return */
263*22028508SToomas Soome                     if (i < lc.len) {
264*22028508SToomas Soome                         nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
265*22028508SToomas Soome                         ls->len = ls->pos = nwritten;
266*22028508SToomas Soome                     }
267*22028508SToomas Soome                     stop = 1;
268*22028508SToomas Soome                     break;
269*22028508SToomas Soome             }
270*22028508SToomas Soome         }
271*22028508SToomas Soome     }
272*22028508SToomas Soome 
273*22028508SToomas Soome     freeCompletions(&lc);
274*22028508SToomas Soome     return c; /* Return last read character */
275*22028508SToomas Soome }
276*22028508SToomas Soome 
277*22028508SToomas Soome /* Register a callback function to be called for tab-completion. */
linenoiseSetCompletionCallback(linenoiseCompletionCallback * fn)278*22028508SToomas Soome void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
279*22028508SToomas Soome     completionCallback = fn;
280*22028508SToomas Soome }
281*22028508SToomas Soome 
282*22028508SToomas Soome /* This function is used by the callback function registered by the user
283*22028508SToomas Soome  * in order to add completion options given the input string when the
284*22028508SToomas Soome  * user typed <tab>. See the example.c source code for a very easy to
285*22028508SToomas Soome  * understand example. */
linenoiseAddCompletion(linenoiseCompletions * lc,const char * str)286*22028508SToomas Soome void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
287*22028508SToomas Soome     size_t len = strlen(str);
288*22028508SToomas Soome     char *copy, **cvec;
289*22028508SToomas Soome 
290*22028508SToomas Soome     copy = malloc(len+1);
291*22028508SToomas Soome     if (copy == NULL) return;
292*22028508SToomas Soome     memcpy(copy,str,len+1);
293*22028508SToomas Soome     cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
294*22028508SToomas Soome     if (cvec == NULL) {
295*22028508SToomas Soome         free(copy);
296*22028508SToomas Soome         return;
297*22028508SToomas Soome     }
298*22028508SToomas Soome     lc->cvec = cvec;
299*22028508SToomas Soome     lc->cvec[lc->len++] = copy;
300*22028508SToomas Soome }
301*22028508SToomas Soome 
302*22028508SToomas Soome /* =========================== Line editing ================================= */
303*22028508SToomas Soome 
304*22028508SToomas Soome /* We define a very simple "append buffer" structure, that is an heap
305*22028508SToomas Soome  * allocated string where we can append to. This is useful in order to
306*22028508SToomas Soome  * write all the escape sequences in a buffer and flush them to the standard
307*22028508SToomas Soome  * output in a single call, to avoid flickering effects. */
308*22028508SToomas Soome struct abuf {
309*22028508SToomas Soome     char *b;
310*22028508SToomas Soome     int len;
311*22028508SToomas Soome };
312*22028508SToomas Soome 
abInit(struct abuf * ab)313*22028508SToomas Soome static void abInit(struct abuf *ab) {
314*22028508SToomas Soome     ab->b = NULL;
315*22028508SToomas Soome     ab->len = 0;
316*22028508SToomas Soome }
317*22028508SToomas Soome 
abAppend(struct abuf * ab,const char * s,int len)318*22028508SToomas Soome static void abAppend(struct abuf *ab, const char *s, int len) {
319*22028508SToomas Soome     char *new = malloc(ab->len+len);
320*22028508SToomas Soome 
321*22028508SToomas Soome     if (new == NULL) return;
322*22028508SToomas Soome     memcpy(new, ab->b, ab->len);
323*22028508SToomas Soome     memcpy(new+ab->len,s,len);
324*22028508SToomas Soome     free(ab->b);
325*22028508SToomas Soome     ab->b = new;
326*22028508SToomas Soome     ab->len += len;
327*22028508SToomas Soome }
328*22028508SToomas Soome 
abFree(struct abuf * ab)329*22028508SToomas Soome static void abFree(struct abuf *ab) {
330*22028508SToomas Soome     free(ab->b);
331*22028508SToomas Soome }
332*22028508SToomas Soome 
333*22028508SToomas Soome /* Single line low level line refresh.
334*22028508SToomas Soome  *
335*22028508SToomas Soome  * Rewrite the currently edited line accordingly to the buffer content,
336*22028508SToomas Soome  * cursor position, and number of columns of the terminal. */
refreshSingleLine(struct linenoiseState * l)337*22028508SToomas Soome static void refreshSingleLine(struct linenoiseState *l) {
338*22028508SToomas Soome     char seq[64];
339*22028508SToomas Soome     size_t plen = strlen(l->prompt);
340*22028508SToomas Soome     char *buf = l->buf;
341*22028508SToomas Soome     size_t len = l->len;
342*22028508SToomas Soome     size_t pos = l->pos;
343*22028508SToomas Soome     struct abuf ab;
344*22028508SToomas Soome 
345*22028508SToomas Soome     while((plen+pos) >= l->cols) {
346*22028508SToomas Soome         buf++;
347*22028508SToomas Soome         len--;
348*22028508SToomas Soome         pos--;
349*22028508SToomas Soome     }
350*22028508SToomas Soome     while (plen+len > l->cols) {
351*22028508SToomas Soome         len--;
352*22028508SToomas Soome     }
353*22028508SToomas Soome 
354*22028508SToomas Soome     abInit(&ab);
355*22028508SToomas Soome     /* Cursor to left edge */
356*22028508SToomas Soome     snprintf(seq,64,"\r");
357*22028508SToomas Soome     abAppend(&ab,seq,strlen(seq));
358*22028508SToomas Soome     /* Write the prompt and the current buffer content */
359*22028508SToomas Soome     abAppend(&ab,l->prompt,strlen(l->prompt));
360*22028508SToomas Soome     abAppend(&ab,buf,len);
361*22028508SToomas Soome     /* Erase to right */
362*22028508SToomas Soome     snprintf(seq,64,"\x1b[K");
363*22028508SToomas Soome     abAppend(&ab,seq,strlen(seq));
364*22028508SToomas Soome     /* Move cursor to original position. */
365*22028508SToomas Soome     snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
366*22028508SToomas Soome     abAppend(&ab,seq,strlen(seq));
367*22028508SToomas Soome     put_bytes(ab.b, ab.len);
368*22028508SToomas Soome 
369*22028508SToomas Soome     abFree(&ab);
370*22028508SToomas Soome }
371*22028508SToomas Soome 
372*22028508SToomas Soome /* Multi line low level line refresh.
373*22028508SToomas Soome  *
374*22028508SToomas Soome  * Rewrite the currently edited line accordingly to the buffer content,
375*22028508SToomas Soome  * cursor position, and number of columns of the terminal. */
refreshMultiLine(struct linenoiseState * l)376*22028508SToomas Soome static void refreshMultiLine(struct linenoiseState *l) {
377*22028508SToomas Soome     char seq[64];
378*22028508SToomas Soome     int plen = strlen(l->prompt);
379*22028508SToomas Soome     int rows = (plen+l->len+l->cols)/l->cols; /* rows used by current buf. */
380*22028508SToomas Soome     int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
381*22028508SToomas Soome     int rpos2; /* rpos after refresh. */
382*22028508SToomas Soome     int col; /* colum position, zero-based. */
383*22028508SToomas Soome     int old_rows = l->maxrows;
384*22028508SToomas Soome     int j;
385*22028508SToomas Soome     struct abuf ab;
386*22028508SToomas Soome 
387*22028508SToomas Soome     /* Update maxrows if needed. */
388*22028508SToomas Soome     if (rows > (int)l->maxrows) l->maxrows = rows;
389*22028508SToomas Soome 
390*22028508SToomas Soome     /* First step: clear all the lines used before. To do so start by
391*22028508SToomas Soome      * going to the last row. */
392*22028508SToomas Soome     abInit(&ab);
393*22028508SToomas Soome     if (old_rows-rpos > 0) {
394*22028508SToomas Soome         snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
395*22028508SToomas Soome         abAppend(&ab,seq,strlen(seq));
396*22028508SToomas Soome     }
397*22028508SToomas Soome 
398*22028508SToomas Soome     /* Now for every row clear it, go up. */
399*22028508SToomas Soome     for (j = 0; j < old_rows-1; j++) {
400*22028508SToomas Soome         snprintf(seq,64,"\r\x1b[0K\x1b[1A");
401*22028508SToomas Soome         abAppend(&ab,seq,strlen(seq));
402*22028508SToomas Soome     }
403*22028508SToomas Soome 
404*22028508SToomas Soome     /* Clean the top line. */
405*22028508SToomas Soome     snprintf(seq,64,"\r\x1b[0K");
406*22028508SToomas Soome     abAppend(&ab,seq,strlen(seq));
407*22028508SToomas Soome 
408*22028508SToomas Soome     /* Write the prompt and the current buffer content */
409*22028508SToomas Soome     abAppend(&ab,l->prompt,strlen(l->prompt));
410*22028508SToomas Soome     abAppend(&ab,l->buf,l->len);
411*22028508SToomas Soome 
412*22028508SToomas Soome     /* If we are at the very end of the screen with our prompt, we need to
413*22028508SToomas Soome      * emit a newline and move the prompt to the first column. */
414*22028508SToomas Soome     if (l->pos &&
415*22028508SToomas Soome         l->pos == l->len &&
416*22028508SToomas Soome         (l->pos+plen) % l->cols == 0)
417*22028508SToomas Soome     {
418*22028508SToomas Soome         abAppend(&ab,"\n",1);
419*22028508SToomas Soome         snprintf(seq,64,"\r");
420*22028508SToomas Soome         abAppend(&ab,seq,strlen(seq));
421*22028508SToomas Soome         rows++;
422*22028508SToomas Soome         if (rows > (int)l->maxrows) l->maxrows = rows;
423*22028508SToomas Soome     }
424*22028508SToomas Soome 
425*22028508SToomas Soome     /* Move cursor to right position. */
426*22028508SToomas Soome     rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
427*22028508SToomas Soome 
428*22028508SToomas Soome     /* Go up till we reach the expected positon. */
429*22028508SToomas Soome     if (rows-rpos2 > 0) {
430*22028508SToomas Soome         snprintf(seq,64,"\x1b[%dA", rows-rpos2);
431*22028508SToomas Soome         abAppend(&ab,seq,strlen(seq));
432*22028508SToomas Soome     }
433*22028508SToomas Soome 
434*22028508SToomas Soome     /* Set column. */
435*22028508SToomas Soome     col = (plen+(int)l->pos) % (int)l->cols;
436*22028508SToomas Soome     if (col)
437*22028508SToomas Soome         snprintf(seq,64,"\r\x1b[%dC", col);
438*22028508SToomas Soome     else
439*22028508SToomas Soome         snprintf(seq,64,"\r");
440*22028508SToomas Soome     abAppend(&ab,seq,strlen(seq));
441*22028508SToomas Soome 
442*22028508SToomas Soome     l->oldpos = l->pos;
443*22028508SToomas Soome 
444*22028508SToomas Soome     put_bytes(ab.b, ab.len);
445*22028508SToomas Soome     abFree(&ab);
446*22028508SToomas Soome }
447*22028508SToomas Soome 
448*22028508SToomas Soome /* Calls the two low level functions refreshSingleLine() or
449*22028508SToomas Soome  * refreshMultiLine() according to the selected mode. */
refreshLine(struct linenoiseState * l)450*22028508SToomas Soome static void refreshLine(struct linenoiseState *l) {
451*22028508SToomas Soome     if (mlmode)
452*22028508SToomas Soome         refreshMultiLine(l);
453*22028508SToomas Soome     else
454*22028508SToomas Soome         refreshSingleLine(l);
455*22028508SToomas Soome }
456*22028508SToomas Soome 
457*22028508SToomas Soome /* Insert the character 'c' at cursor current position.
458*22028508SToomas Soome  *
459*22028508SToomas Soome  * On error writing to the terminal -1 is returned, otherwise 0. */
460*22028508SToomas Soome static int
linenoiseEditInsert(struct linenoiseState * l,char c)461*22028508SToomas Soome linenoiseEditInsert(struct linenoiseState *l, char c) {
462*22028508SToomas Soome     if (l->len < l->buflen) {
463*22028508SToomas Soome         if (l->len == l->pos) {
464*22028508SToomas Soome             l->buf[l->pos] = c;
465*22028508SToomas Soome             l->pos++;
466*22028508SToomas Soome             l->len++;
467*22028508SToomas Soome             l->buf[l->len] = '\0';
468*22028508SToomas Soome             if ((!mlmode && l->plen+l->len < l->cols) /* || mlmode */) {
469*22028508SToomas Soome                 /* Avoid a full update of the line in the
470*22028508SToomas Soome                  * trivial case. */
471*22028508SToomas Soome                 putchar(c);
472*22028508SToomas Soome             } else {
473*22028508SToomas Soome                 refreshLine(l);
474*22028508SToomas Soome             }
475*22028508SToomas Soome         } else {
476*22028508SToomas Soome             memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
477*22028508SToomas Soome             l->buf[l->pos] = c;
478*22028508SToomas Soome             l->len++;
479*22028508SToomas Soome             l->pos++;
480*22028508SToomas Soome             l->buf[l->len] = '\0';
481*22028508SToomas Soome             refreshLine(l);
482*22028508SToomas Soome         }
483*22028508SToomas Soome     }
484*22028508SToomas Soome     return 0;
485*22028508SToomas Soome }
486*22028508SToomas Soome 
487*22028508SToomas Soome /* Move cursor on the left. */
488*22028508SToomas Soome static void
linenoiseEditMoveLeft(struct linenoiseState * l)489*22028508SToomas Soome linenoiseEditMoveLeft(struct linenoiseState *l) {
490*22028508SToomas Soome     if (l->pos > 0) {
491*22028508SToomas Soome         l->pos--;
492*22028508SToomas Soome         refreshLine(l);
493*22028508SToomas Soome     }
494*22028508SToomas Soome }
495*22028508SToomas Soome 
496*22028508SToomas Soome /* Move cursor on the right. */
497*22028508SToomas Soome static void
linenoiseEditMoveRight(struct linenoiseState * l)498*22028508SToomas Soome linenoiseEditMoveRight(struct linenoiseState *l) {
499*22028508SToomas Soome     if (l->pos != l->len) {
500*22028508SToomas Soome         l->pos++;
501*22028508SToomas Soome         refreshLine(l);
502*22028508SToomas Soome     }
503*22028508SToomas Soome }
504*22028508SToomas Soome 
505*22028508SToomas Soome /* Move cursor to the start of the line. */
506*22028508SToomas Soome static void
linenoiseEditMoveHome(struct linenoiseState * l)507*22028508SToomas Soome linenoiseEditMoveHome(struct linenoiseState *l) {
508*22028508SToomas Soome     if (l->pos != 0) {
509*22028508SToomas Soome         l->pos = 0;
510*22028508SToomas Soome         refreshLine(l);
511*22028508SToomas Soome     }
512*22028508SToomas Soome }
513*22028508SToomas Soome 
514*22028508SToomas Soome /* Move cursor to the end of the line. */
515*22028508SToomas Soome static void
linenoiseEditMoveEnd(struct linenoiseState * l)516*22028508SToomas Soome linenoiseEditMoveEnd(struct linenoiseState *l) {
517*22028508SToomas Soome     if (l->pos != l->len) {
518*22028508SToomas Soome         l->pos = l->len;
519*22028508SToomas Soome         refreshLine(l);
520*22028508SToomas Soome     }
521*22028508SToomas Soome }
522*22028508SToomas Soome 
523*22028508SToomas Soome /* Substitute the currently edited line with the next or previous history
524*22028508SToomas Soome  * entry as specified by 'dir'. */
525*22028508SToomas Soome #define LINENOISE_HISTORY_NEXT 0
526*22028508SToomas Soome #define LINENOISE_HISTORY_PREV 1
527*22028508SToomas Soome static void
linenoiseEditHistoryNext(struct linenoiseState * l,int dir)528*22028508SToomas Soome linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
529*22028508SToomas Soome     if (history_len > 1) {
530*22028508SToomas Soome         /* Update the current history entry before to
531*22028508SToomas Soome          * overwrite it with the next one. */
532*22028508SToomas Soome         free(history[history_len - 1 - l->history_index]);
533*22028508SToomas Soome         history[history_len - 1 - l->history_index] = strdup(l->buf);
534*22028508SToomas Soome         /* Show the new entry */
535*22028508SToomas Soome         l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
536*22028508SToomas Soome         if (l->history_index < 0) {
537*22028508SToomas Soome             l->history_index = 0;
538*22028508SToomas Soome             return;
539*22028508SToomas Soome         } else if (l->history_index >= history_len) {
540*22028508SToomas Soome             l->history_index = history_len-1;
541*22028508SToomas Soome             return;
542*22028508SToomas Soome         }
543*22028508SToomas Soome         strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
544*22028508SToomas Soome         l->buf[l->buflen-1] = '\0';
545*22028508SToomas Soome         l->len = l->pos = strlen(l->buf);
546*22028508SToomas Soome         refreshLine(l);
547*22028508SToomas Soome     }
548*22028508SToomas Soome }
549*22028508SToomas Soome 
550*22028508SToomas Soome /* Delete the character at the right of the cursor without altering the cursor
551*22028508SToomas Soome  * position. Basically this is what happens with the "Delete" keyboard key. */
552*22028508SToomas Soome static void
linenoiseEditDelete(struct linenoiseState * l)553*22028508SToomas Soome linenoiseEditDelete(struct linenoiseState *l) {
554*22028508SToomas Soome     if (l->len > 0 && l->pos < l->len) {
555*22028508SToomas Soome         memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
556*22028508SToomas Soome         l->len--;
557*22028508SToomas Soome         l->buf[l->len] = '\0';
558*22028508SToomas Soome         refreshLine(l);
559*22028508SToomas Soome     }
560*22028508SToomas Soome }
561*22028508SToomas Soome 
562*22028508SToomas Soome /* Backspace implementation. */
563*22028508SToomas Soome static void
linenoiseEditBackspace(struct linenoiseState * l)564*22028508SToomas Soome linenoiseEditBackspace(struct linenoiseState *l) {
565*22028508SToomas Soome     if (l->pos > 0 && l->len > 0) {
566*22028508SToomas Soome         memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
567*22028508SToomas Soome         l->pos--;
568*22028508SToomas Soome         l->len--;
569*22028508SToomas Soome         l->buf[l->len] = '\0';
570*22028508SToomas Soome         refreshLine(l);
571*22028508SToomas Soome     }
572*22028508SToomas Soome }
573*22028508SToomas Soome 
574*22028508SToomas Soome /* Delete the previosu word, maintaining the cursor at the start of the
575*22028508SToomas Soome  * current word. */
576*22028508SToomas Soome static void
linenoiseEditDeletePrevWord(struct linenoiseState * l)577*22028508SToomas Soome linenoiseEditDeletePrevWord(struct linenoiseState *l) {
578*22028508SToomas Soome     size_t old_pos = l->pos;
579*22028508SToomas Soome     size_t diff;
580*22028508SToomas Soome 
581*22028508SToomas Soome     while (l->pos > 0 && l->buf[l->pos-1] == ' ')
582*22028508SToomas Soome         l->pos--;
583*22028508SToomas Soome     while (l->pos > 0 && l->buf[l->pos-1] != ' ')
584*22028508SToomas Soome         l->pos--;
585*22028508SToomas Soome     diff = old_pos - l->pos;
586*22028508SToomas Soome     memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
587*22028508SToomas Soome     l->len -= diff;
588*22028508SToomas Soome     refreshLine(l);
589*22028508SToomas Soome }
590*22028508SToomas Soome 
591*22028508SToomas Soome /* This function is the core of the line editing capability of linenoise.
592*22028508SToomas Soome  * It expects 'fd' to be already in "raw mode" so that every key pressed
593*22028508SToomas Soome  * will be returned ASAP to read().
594*22028508SToomas Soome  *
595*22028508SToomas Soome  * The resulting string is put into 'buf' when the user type enter, or
596*22028508SToomas Soome  * when ctrl+d is typed.
597*22028508SToomas Soome  *
598*22028508SToomas Soome  * The function returns the length of the current buffer. */
linenoiseEdit(char * buf,size_t buflen,const char * prompt)599*22028508SToomas Soome static int linenoiseEdit(char *buf, size_t buflen, const char *prompt)
600*22028508SToomas Soome {
601*22028508SToomas Soome     struct linenoiseState l;
602*22028508SToomas Soome 
603*22028508SToomas Soome     /* Populate the linenoise state that we pass to functions implementing
604*22028508SToomas Soome      * specific editing functionalities. */
605*22028508SToomas Soome     l.buf = buf;
606*22028508SToomas Soome     l.buflen = buflen;
607*22028508SToomas Soome     l.prompt = prompt;
608*22028508SToomas Soome     l.plen = strlen(prompt);
609*22028508SToomas Soome     l.oldpos = l.pos = 0;
610*22028508SToomas Soome     l.len = 0;
611*22028508SToomas Soome     l.cols = getColumns();
612*22028508SToomas Soome     l.maxrows = 0;
613*22028508SToomas Soome     l.history_index = 0;
614*22028508SToomas Soome 
615*22028508SToomas Soome     /* Buffer starts empty. */
616*22028508SToomas Soome     l.buf[0] = '\0';
617*22028508SToomas Soome     l.buflen--; /* Make sure there is always space for the nulterm */
618*22028508SToomas Soome 
619*22028508SToomas Soome     /* The latest history entry is always our current buffer, that
620*22028508SToomas Soome      * initially is just an empty string. */
621*22028508SToomas Soome     linenoiseHistoryAdd("");
622*22028508SToomas Soome 
623*22028508SToomas Soome     printf ("%s", prompt);
624*22028508SToomas Soome     while(1) {
625*22028508SToomas Soome         char c;
626*22028508SToomas Soome         char seq[3];
627*22028508SToomas Soome 
628*22028508SToomas Soome         c = getchar();
629*22028508SToomas Soome 	if (c == -1)
630*22028508SToomas Soome 		continue;
631*22028508SToomas Soome 
632*22028508SToomas Soome         /* Only autocomplete when the callback is set. It returns < 0 when
633*22028508SToomas Soome          * there was an error reading from fd. Otherwise it will return the
634*22028508SToomas Soome          * character that should be handled next. */
635*22028508SToomas Soome         if (c == 9 && completionCallback != NULL) {
636*22028508SToomas Soome             c = completeLine(&l);
637*22028508SToomas Soome             /* Return on errors */
638*22028508SToomas Soome             if (c < 0) return l.len;
639*22028508SToomas Soome             /* Read next character when 0 */
640*22028508SToomas Soome             if (c == 0) continue;
641*22028508SToomas Soome         }
642*22028508SToomas Soome 
643*22028508SToomas Soome         switch(c) {
644*22028508SToomas Soome         case ENTER:    /* enter */
645*22028508SToomas Soome             history_len--;
646*22028508SToomas Soome             free(history[history_len]);
647*22028508SToomas Soome             if (mlmode) linenoiseEditMoveEnd(&l);
648*22028508SToomas Soome             return (int)l.len;
649*22028508SToomas Soome         case CTRL_C:     /* ctrl-c */
650*22028508SToomas Soome             buf[0] = '\0';
651*22028508SToomas Soome             l.pos = l.len = 0;
652*22028508SToomas Soome             refreshLine(&l);
653*22028508SToomas Soome 	    break;
654*22028508SToomas Soome         case BACKSPACE:   /* backspace */
655*22028508SToomas Soome         case 8:     /* ctrl-h */
656*22028508SToomas Soome             linenoiseEditBackspace(&l);
657*22028508SToomas Soome             break;
658*22028508SToomas Soome         case CTRL_D:     /* ctrl-d, remove char at right of cursor. */
659*22028508SToomas Soome             if (l.len > 0) {
660*22028508SToomas Soome                 linenoiseEditDelete(&l);
661*22028508SToomas Soome             }
662*22028508SToomas Soome             break;
663*22028508SToomas Soome         case CTRL_T:    /* ctrl-t, swaps current character with previous. */
664*22028508SToomas Soome             if (l.pos > 0 && l.pos < l.len) {
665*22028508SToomas Soome                 int aux = buf[l.pos-1];
666*22028508SToomas Soome                 buf[l.pos-1] = buf[l.pos];
667*22028508SToomas Soome                 buf[l.pos] = aux;
668*22028508SToomas Soome                 if (l.pos != l.len-1) l.pos++;
669*22028508SToomas Soome                 refreshLine(&l);
670*22028508SToomas Soome             }
671*22028508SToomas Soome             break;
672*22028508SToomas Soome         case CTRL_B:     /* ctrl-b */
673*22028508SToomas Soome             linenoiseEditMoveLeft(&l);
674*22028508SToomas Soome             break;
675*22028508SToomas Soome         case CTRL_F:     /* ctrl-f */
676*22028508SToomas Soome             linenoiseEditMoveRight(&l);
677*22028508SToomas Soome             break;
678*22028508SToomas Soome         case CTRL_P:    /* ctrl-p */
679*22028508SToomas Soome             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
680*22028508SToomas Soome             break;
681*22028508SToomas Soome         case CTRL_N:    /* ctrl-n */
682*22028508SToomas Soome             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
683*22028508SToomas Soome             break;
684*22028508SToomas Soome         case ESC:    /* escape sequence */
685*22028508SToomas Soome             /* Read the next two bytes representing the escape sequence.
686*22028508SToomas Soome              * Use two calls to handle slow terminals returning the two
687*22028508SToomas Soome              * chars at different times. */
688*22028508SToomas Soome             seq[0] = getchar();
689*22028508SToomas Soome             seq[1] = getchar();
690*22028508SToomas Soome 
691*22028508SToomas Soome             /* ESC [ sequences. */
692*22028508SToomas Soome             if (seq[0] == '[') {
693*22028508SToomas Soome                 if (seq[1] >= '0' && seq[1] <= '9') {
694*22028508SToomas Soome                     /* Extended escape, read additional byte. */
695*22028508SToomas Soome                     seq[2] = getchar();
696*22028508SToomas Soome                     if (seq[2] == '~') {
697*22028508SToomas Soome                         switch(seq[1]) {
698*22028508SToomas Soome                         case '3': /* Delete key. */
699*22028508SToomas Soome                             linenoiseEditDelete(&l);
700*22028508SToomas Soome                             break;
701*22028508SToomas Soome                         }
702*22028508SToomas Soome                     }
703*22028508SToomas Soome                 } else {
704*22028508SToomas Soome                     switch(seq[1]) {
705*22028508SToomas Soome                     case 'A': /* Up */
706*22028508SToomas Soome                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
707*22028508SToomas Soome                         break;
708*22028508SToomas Soome                     case 'B': /* Down */
709*22028508SToomas Soome                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
710*22028508SToomas Soome                         break;
711*22028508SToomas Soome                     case 'C': /* Right */
712*22028508SToomas Soome                         linenoiseEditMoveRight(&l);
713*22028508SToomas Soome                         break;
714*22028508SToomas Soome                     case 'D': /* Left */
715*22028508SToomas Soome                         linenoiseEditMoveLeft(&l);
716*22028508SToomas Soome                         break;
717*22028508SToomas Soome                     case 'H': /* Home */
718*22028508SToomas Soome                         linenoiseEditMoveHome(&l);
719*22028508SToomas Soome                         break;
720*22028508SToomas Soome                     case 'F': /* End*/
721*22028508SToomas Soome                         linenoiseEditMoveEnd(&l);
722*22028508SToomas Soome                         break;
723*22028508SToomas Soome                     }
724*22028508SToomas Soome                 }
725*22028508SToomas Soome             }
726*22028508SToomas Soome 
727*22028508SToomas Soome             /* ESC O sequences. */
728*22028508SToomas Soome             else if (seq[0] == 'O') {
729*22028508SToomas Soome                 switch(seq[1]) {
730*22028508SToomas Soome                 case 'H': /* Home */
731*22028508SToomas Soome                     linenoiseEditMoveHome(&l);
732*22028508SToomas Soome                     break;
733*22028508SToomas Soome                 case 'F': /* End*/
734*22028508SToomas Soome                     linenoiseEditMoveEnd(&l);
735*22028508SToomas Soome                     break;
736*22028508SToomas Soome                 }
737*22028508SToomas Soome             }
738*22028508SToomas Soome             break;
739*22028508SToomas Soome         default:
740*22028508SToomas Soome             if (linenoiseEditInsert(&l,c)) return -1;
741*22028508SToomas Soome             break;
742*22028508SToomas Soome         case CTRL_U: /* Ctrl+u, delete the whole line. */
743*22028508SToomas Soome             buf[0] = '\0';
744*22028508SToomas Soome             l.pos = l.len = 0;
745*22028508SToomas Soome             refreshLine(&l);
746*22028508SToomas Soome             break;
747*22028508SToomas Soome         case CTRL_K: /* Ctrl+k, delete from current to end of line. */
748*22028508SToomas Soome             buf[l.pos] = '\0';
749*22028508SToomas Soome             l.len = l.pos;
750*22028508SToomas Soome             refreshLine(&l);
751*22028508SToomas Soome             break;
752*22028508SToomas Soome         case CTRL_A: /* Ctrl+a, go to the start of the line */
753*22028508SToomas Soome             linenoiseEditMoveHome(&l);
754*22028508SToomas Soome             break;
755*22028508SToomas Soome         case CTRL_E: /* ctrl+e, go to the end of the line */
756*22028508SToomas Soome             linenoiseEditMoveEnd(&l);
757*22028508SToomas Soome             break;
758*22028508SToomas Soome         case CTRL_L: /* ctrl+l, clear screen */
759*22028508SToomas Soome             linenoiseClearScreen();
760*22028508SToomas Soome             refreshLine(&l);
761*22028508SToomas Soome             break;
762*22028508SToomas Soome         case CTRL_W: /* ctrl+w, delete previous word */
763*22028508SToomas Soome             linenoiseEditDeletePrevWord(&l);
764*22028508SToomas Soome             break;
765*22028508SToomas Soome         }
766*22028508SToomas Soome     }
767*22028508SToomas Soome     return l.len;
768*22028508SToomas Soome }
769*22028508SToomas Soome 
770*22028508SToomas Soome /* The high level function that is the main API of the linenoise library.
771*22028508SToomas Soome  * This function checks if the terminal has basic capabilities, just checking
772*22028508SToomas Soome  * for a blacklist of stupid terminals, and later either calls the line
773*22028508SToomas Soome  * editing function or uses dummy fgets() so that you will be able to type
774*22028508SToomas Soome  * something even in the most desperate of the conditions. */
linenoise(const char * prompt)775*22028508SToomas Soome char *linenoise(const char *prompt) {
776*22028508SToomas Soome     char buf[LINENOISE_MAX_LINE];
777*22028508SToomas Soome     int count;
778*22028508SToomas Soome 
779*22028508SToomas Soome     cons_mode(C_MODERAW);
780*22028508SToomas Soome     count = linenoiseEdit(buf,LINENOISE_MAX_LINE,prompt);
781*22028508SToomas Soome     cons_mode(0);
782*22028508SToomas Soome     printf("\n");
783*22028508SToomas Soome     if (count == -1) return NULL;
784*22028508SToomas Soome     return strdup(buf);
785*22028508SToomas Soome }
786*22028508SToomas Soome 
787*22028508SToomas Soome /* ================================ History ================================= */
788*22028508SToomas Soome 
789*22028508SToomas Soome /* This is the API call to add a new entry in the linenoise history.
790*22028508SToomas Soome  * It uses a fixed array of char pointers that are shifted (memmoved)
791*22028508SToomas Soome  * when the history max length is reached in order to remove the older
792*22028508SToomas Soome  * entry and make room for the new one, so it is not exactly suitable for huge
793*22028508SToomas Soome  * histories, but will work well for a few hundred of entries.
794*22028508SToomas Soome  *
795*22028508SToomas Soome  * Using a circular buffer is smarter, but a bit more complex to handle. */
linenoiseHistoryAdd(const char * line)796*22028508SToomas Soome int linenoiseHistoryAdd(const char *line) {
797*22028508SToomas Soome     char *linecopy;
798*22028508SToomas Soome 
799*22028508SToomas Soome     if (history_max_len == 0) return 0;
800*22028508SToomas Soome 
801*22028508SToomas Soome     /* Initialization on first call. */
802*22028508SToomas Soome     if (history == NULL) {
803*22028508SToomas Soome         history = malloc(sizeof(char*)*history_max_len);
804*22028508SToomas Soome         if (history == NULL) return 0;
805*22028508SToomas Soome         memset(history,0,(sizeof(char*)*history_max_len));
806*22028508SToomas Soome     }
807*22028508SToomas Soome 
808*22028508SToomas Soome     /* Don't add duplicated lines. */
809*22028508SToomas Soome     if (history_len && !strcmp(history[history_len-1], line)) return 0;
810*22028508SToomas Soome 
811*22028508SToomas Soome     /* Add an heap allocated copy of the line in the history.
812*22028508SToomas Soome      * If we reached the max length, remove the older line. */
813*22028508SToomas Soome     linecopy = strdup(line);
814*22028508SToomas Soome     if (!linecopy) return 0;
815*22028508SToomas Soome     if (history_len == history_max_len) {
816*22028508SToomas Soome         free(history[0]);
817*22028508SToomas Soome         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
818*22028508SToomas Soome         history_len--;
819*22028508SToomas Soome     }
820*22028508SToomas Soome     history[history_len] = linecopy;
821*22028508SToomas Soome     history_len++;
822*22028508SToomas Soome     return 1;
823*22028508SToomas Soome }
824*22028508SToomas Soome 
825*22028508SToomas Soome /* Set the maximum length for the history. This function can be called even
826*22028508SToomas Soome  * if there is already some history, the function will make sure to retain
827*22028508SToomas Soome  * just the latest 'len' elements if the new history length value is smaller
828*22028508SToomas Soome  * than the amount of items already inside the history. */
linenoiseHistorySetMaxLen(int len)829*22028508SToomas Soome int linenoiseHistorySetMaxLen(int len) {
830*22028508SToomas Soome     char **new;
831*22028508SToomas Soome 
832*22028508SToomas Soome     if (len < 1) return 0;
833*22028508SToomas Soome     if (history) {
834*22028508SToomas Soome         int tocopy = history_len;
835*22028508SToomas Soome 
836*22028508SToomas Soome         new = malloc(sizeof(char*)*len);
837*22028508SToomas Soome         if (new == NULL) return 0;
838*22028508SToomas Soome 
839*22028508SToomas Soome         /* If we can't copy everything, free the elements we'll not use. */
840*22028508SToomas Soome         if (len < tocopy) {
841*22028508SToomas Soome             int j;
842*22028508SToomas Soome 
843*22028508SToomas Soome             for (j = 0; j < tocopy-len; j++) free(history[j]);
844*22028508SToomas Soome             tocopy = len;
845*22028508SToomas Soome         }
846*22028508SToomas Soome         memset(new,0,sizeof(char*)*len);
847*22028508SToomas Soome         memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
848*22028508SToomas Soome         free(history);
849*22028508SToomas Soome         history = new;
850*22028508SToomas Soome     }
851*22028508SToomas Soome     history_max_len = len;
852*22028508SToomas Soome     if (history_len > history_max_len)
853*22028508SToomas Soome         history_len = history_max_len;
854*22028508SToomas Soome     return 1;
855*22028508SToomas Soome }
856