1199767f8SToomas Soome /* linenoise.c -- VERSION 1.0
2199767f8SToomas Soome  *
3199767f8SToomas Soome  * Guerrilla line editing library against the idea that a line editing lib
4199767f8SToomas Soome  * needs to be 20,000 lines of C code.
5199767f8SToomas Soome  *
6199767f8SToomas Soome  * You can find the latest source code at:
7199767f8SToomas Soome  *
8199767f8SToomas Soome  *   http://github.com/antirez/linenoise
9199767f8SToomas Soome  *
10199767f8SToomas Soome  * Does a number of crazy assumptions that happen to be true in 99.9999% of
11199767f8SToomas Soome  * the 2010 UNIX computers around.
12199767f8SToomas Soome  *
13199767f8SToomas Soome  * ------------------------------------------------------------------------
14199767f8SToomas Soome  *
15199767f8SToomas Soome  * Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
16199767f8SToomas Soome  * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
17199767f8SToomas Soome  *
18199767f8SToomas Soome  * All rights reserved.
19199767f8SToomas Soome  *
20199767f8SToomas Soome  * Redistribution and use in source and binary forms, with or without
21199767f8SToomas Soome  * modification, are permitted provided that the following conditions are
22199767f8SToomas Soome  * met:
23199767f8SToomas Soome  *
24199767f8SToomas Soome  *  *  Redistributions of source code must retain the above copyright
25199767f8SToomas Soome  *     notice, this list of conditions and the following disclaimer.
26199767f8SToomas Soome  *
27199767f8SToomas Soome  *  *  Redistributions in binary form must reproduce the above copyright
28199767f8SToomas Soome  *     notice, this list of conditions and the following disclaimer in the
29199767f8SToomas Soome  *     documentation and/or other materials provided with the distribution.
30199767f8SToomas Soome  *
31199767f8SToomas Soome  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32199767f8SToomas Soome  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33199767f8SToomas Soome  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34199767f8SToomas Soome  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35199767f8SToomas Soome  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36199767f8SToomas Soome  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37199767f8SToomas Soome  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38199767f8SToomas Soome  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39199767f8SToomas Soome  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40199767f8SToomas Soome  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41199767f8SToomas Soome  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42199767f8SToomas Soome  *
43199767f8SToomas Soome  * ------------------------------------------------------------------------
44199767f8SToomas Soome  *
45199767f8SToomas Soome  * References:
46199767f8SToomas Soome  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
47199767f8SToomas Soome  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
48199767f8SToomas Soome  *
49199767f8SToomas Soome  * Todo list:
50199767f8SToomas Soome  * - Filter bogus Ctrl+<char> combinations.
51199767f8SToomas Soome  * - Win32 support
52199767f8SToomas Soome  *
53199767f8SToomas Soome  * Bloat:
54199767f8SToomas Soome  * - History search like Ctrl+r in readline?
55199767f8SToomas Soome  *
56199767f8SToomas Soome  * List of escape sequences used by this program, we do everything just
57199767f8SToomas Soome  * with three sequences. In order to be so cheap we may have some
58199767f8SToomas Soome  * flickering effect with some slow terminal, but the lesser sequences
59199767f8SToomas Soome  * the more compatible.
60199767f8SToomas Soome  *
61199767f8SToomas Soome  * EL (Erase Line)
62199767f8SToomas Soome  *    Sequence: ESC [ n K
63199767f8SToomas Soome  *    Effect: if n is 0 or missing, clear from cursor to end of line
64199767f8SToomas Soome  *    Effect: if n is 1, clear from beginning of line to cursor
65199767f8SToomas Soome  *    Effect: if n is 2, clear entire line
66199767f8SToomas Soome  *
67199767f8SToomas Soome  * CUF (CUrsor Forward)
68199767f8SToomas Soome  *    Sequence: ESC [ n C
69199767f8SToomas Soome  *    Effect: moves cursor forward n chars
70199767f8SToomas Soome  *
71199767f8SToomas Soome  * CUB (CUrsor Backward)
72199767f8SToomas Soome  *    Sequence: ESC [ n D
73199767f8SToomas Soome  *    Effect: moves cursor backward n chars
74199767f8SToomas Soome  *
75199767f8SToomas Soome  * The following is used to get the terminal width if getting
76199767f8SToomas Soome  * the width with the TIOCGWINSZ ioctl fails
77199767f8SToomas Soome  *
78199767f8SToomas Soome  * DSR (Device Status Report)
79199767f8SToomas Soome  *    Sequence: ESC [ 6 n
80199767f8SToomas Soome  *    Effect: reports the current cusor position as ESC [ n ; m R
81199767f8SToomas Soome  *            where n is the row and m is the column
82199767f8SToomas Soome  *
83199767f8SToomas Soome  * When multi line mode is enabled, we also use an additional escape
84199767f8SToomas Soome  * sequence. However multi line editing is disabled by default.
85199767f8SToomas Soome  *
86199767f8SToomas Soome  * CUU (Cursor Up)
87199767f8SToomas Soome  *    Sequence: ESC [ n A
88199767f8SToomas Soome  *    Effect: moves cursor up of n chars.
89199767f8SToomas Soome  *
90199767f8SToomas Soome  * CUD (Cursor Down)
91199767f8SToomas Soome  *    Sequence: ESC [ n B
92199767f8SToomas Soome  *    Effect: moves cursor down of n chars.
93199767f8SToomas Soome  *
94199767f8SToomas Soome  * When linenoiseClearScreen() is called, two additional escape sequences
95199767f8SToomas Soome  * are used in order to clear the screen and position the cursor at home
96199767f8SToomas Soome  * position.
97199767f8SToomas Soome  *
98199767f8SToomas Soome  * CUP (Cursor position)
99199767f8SToomas Soome  *    Sequence: ESC [ H
100199767f8SToomas Soome  *    Effect: moves the cursor to upper left corner
101199767f8SToomas Soome  *
102199767f8SToomas Soome  * ED (Erase display)
103199767f8SToomas Soome  *    Sequence: ESC [ 2 J
104199767f8SToomas Soome  *    Effect: clear the whole screen
105199767f8SToomas Soome  *
106199767f8SToomas Soome  */
107199767f8SToomas Soome 
108199767f8SToomas Soome #include <stand.h>
109199767f8SToomas Soome #include "linenoise.h"
110199767f8SToomas Soome #include "bootstrap.h"
111199767f8SToomas Soome 
112199767f8SToomas Soome #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
113199767f8SToomas Soome #define LINENOISE_MAX_LINE 256
114199767f8SToomas Soome static linenoiseCompletionCallback *completionCallback = NULL;
115199767f8SToomas Soome 
116199767f8SToomas Soome static int mlmode = 1;  /* Multi line mode. Default is single line. */
117199767f8SToomas Soome static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
118199767f8SToomas Soome static int history_len = 0;
119199767f8SToomas Soome static char **history = NULL;
120199767f8SToomas Soome 
121199767f8SToomas Soome /* The linenoiseState structure represents the state during line editing.
122199767f8SToomas Soome  * We pass this state to functions implementing specific editing
123199767f8SToomas Soome  * functionalities. */
124199767f8SToomas Soome struct linenoiseState {
125199767f8SToomas Soome     char *buf;          /* Edited line buffer. */
126199767f8SToomas Soome     size_t buflen;      /* Edited line buffer size. */
127199767f8SToomas Soome     const char *prompt; /* Prompt to display. */
128199767f8SToomas Soome     size_t plen;        /* Prompt length. */
129199767f8SToomas Soome     size_t pos;         /* Current cursor position. */
130199767f8SToomas Soome     size_t oldpos;      /* Previous refresh cursor position. */
131199767f8SToomas Soome     size_t len;         /* Current edited line length. */
132199767f8SToomas Soome     size_t cols;        /* Number of columns in terminal. */
133199767f8SToomas Soome     size_t maxrows;     /* Maximum num of rows used so far (multiline mode) */
134199767f8SToomas Soome     int history_index;  /* The history index we are currently editing. */
135199767f8SToomas Soome };
136199767f8SToomas Soome 
137199767f8SToomas Soome enum KEY_ACTION{
138199767f8SToomas Soome 	KEY_NULL = 0,	    /* NULL */
139199767f8SToomas Soome 	CTRL_A = 1,         /* Ctrl+a */
140199767f8SToomas Soome 	CTRL_B = 2,         /* Ctrl-b */
141199767f8SToomas Soome 	CTRL_C = 3,         /* Ctrl-c */
142199767f8SToomas Soome 	CTRL_D = 4,         /* Ctrl-d */
143199767f8SToomas Soome 	CTRL_E = 5,         /* Ctrl-e */
144199767f8SToomas Soome 	CTRL_F = 6,         /* Ctrl-f */
145199767f8SToomas Soome 	CTRL_H = 8,         /* Ctrl-h */
146199767f8SToomas Soome 	TAB = 9,            /* Tab */
147199767f8SToomas Soome 	CTRL_K = 11,        /* Ctrl+k */
148199767f8SToomas Soome 	CTRL_L = 12,        /* Ctrl+l */
149199767f8SToomas Soome 	ENTER = 13,         /* Enter */
150199767f8SToomas Soome 	CTRL_N = 14,        /* Ctrl-n */
151199767f8SToomas Soome 	CTRL_P = 16,        /* Ctrl-p */
152199767f8SToomas Soome 	CTRL_T = 20,        /* Ctrl-t */
153199767f8SToomas Soome 	CTRL_U = 21,        /* Ctrl+u */
154199767f8SToomas Soome 	CTRL_W = 23,        /* Ctrl+w */
155199767f8SToomas Soome 	ESC = 27,           /* Escape */
156199767f8SToomas Soome 	BACKSPACE =  127    /* Backspace */
157199767f8SToomas Soome };
158199767f8SToomas Soome 
159199767f8SToomas Soome static void refreshLine(struct linenoiseState *l);
160199767f8SToomas Soome 
161199767f8SToomas Soome /* ======================= Low level terminal handling ====================== */
162199767f8SToomas Soome 
163199767f8SToomas Soome static int
put_bytes(const char * s,int len)164199767f8SToomas Soome put_bytes(const char *s, int len)
165199767f8SToomas Soome {
166199767f8SToomas Soome     int i;
167199767f8SToomas Soome     if (s == NULL)
168199767f8SToomas Soome 	return -1;
169199767f8SToomas Soome 
170199767f8SToomas Soome     for (i = 0; i < len; i++)
171199767f8SToomas Soome 	putchar(s[i]);
172199767f8SToomas Soome     return (i);
173199767f8SToomas Soome }
174199767f8SToomas Soome 
175199767f8SToomas Soome /* Set if to use or not the multi line mode. */
linenoiseSetMultiLine(int ml)176199767f8SToomas Soome void linenoiseSetMultiLine(int ml) {
177199767f8SToomas Soome     mlmode = ml;
178199767f8SToomas Soome }
179199767f8SToomas Soome 
180199767f8SToomas Soome /* Clear the screen. Used to handle ctrl+l */
linenoiseClearScreen(void)181199767f8SToomas Soome void linenoiseClearScreen(void) {
182199767f8SToomas Soome     if (put_bytes("\x1b[H\x1b[J", 6) <= 0) {
183199767f8SToomas Soome         /* nothing to do, just to avoid warning. */
184199767f8SToomas Soome     }
185199767f8SToomas Soome }
186199767f8SToomas Soome 
187199767f8SToomas Soome static int
getColumns(void)188199767f8SToomas Soome getColumns(void)
189199767f8SToomas Soome {
1909890ff83SToomas Soome 	char *columns = getenv("screen-#cols");
191199767f8SToomas Soome 	if (columns == NULL)
192199767f8SToomas Soome 		return (80);
193199767f8SToomas Soome 	return (strtol(columns, NULL, 0));
194199767f8SToomas Soome }
195199767f8SToomas Soome 
196199767f8SToomas Soome /* Beep, used for completion when there is nothing to complete or when all
197199767f8SToomas Soome  * the choices were already shown. */
linenoiseBeep(void)198199767f8SToomas Soome static void linenoiseBeep(void) {
199199767f8SToomas Soome     put_bytes("\x7", 1);
200199767f8SToomas Soome }
201199767f8SToomas Soome 
202199767f8SToomas Soome /* ============================== Completion ================================ */
203199767f8SToomas Soome 
204199767f8SToomas Soome /* Free a list of completion option populated by linenoiseAddCompletion(). */
freeCompletions(linenoiseCompletions * lc)205199767f8SToomas Soome static void freeCompletions(linenoiseCompletions *lc) {
206199767f8SToomas Soome     size_t i;
207199767f8SToomas Soome     for (i = 0; i < lc->len; i++)
208199767f8SToomas Soome         free(lc->cvec[i]);
209199767f8SToomas Soome     if (lc->cvec != NULL)
210199767f8SToomas Soome         free(lc->cvec);
211199767f8SToomas Soome }
212199767f8SToomas Soome 
213199767f8SToomas Soome /* This is an helper function for linenoiseEdit() and is called when the
214199767f8SToomas Soome  * user types the <tab> key in order to complete the string currently in the
215199767f8SToomas Soome  * input.
216199767f8SToomas Soome  *
217199767f8SToomas Soome  * The state of the editing is encapsulated into the pointed linenoiseState
218199767f8SToomas Soome  * structure as described in the structure definition. */
completeLine(struct linenoiseState * ls)219199767f8SToomas Soome static int completeLine(struct linenoiseState *ls) {
220199767f8SToomas Soome     linenoiseCompletions lc = { 0, NULL };
221199767f8SToomas Soome     int nwritten;
222199767f8SToomas Soome     char c = 0;
223199767f8SToomas Soome 
224199767f8SToomas Soome     completionCallback(ls->buf,&lc);
225199767f8SToomas Soome     if (lc.len == 0) {
226199767f8SToomas Soome         linenoiseBeep();
227199767f8SToomas Soome     } else {
228199767f8SToomas Soome         size_t stop = 0, i = 0;
229199767f8SToomas Soome 
230199767f8SToomas Soome         while(!stop) {
231199767f8SToomas Soome             /* Show completion or original buffer */
232199767f8SToomas Soome             if (i < lc.len) {
233199767f8SToomas Soome                 struct linenoiseState saved = *ls;
234199767f8SToomas Soome 
235199767f8SToomas Soome                 ls->len = ls->pos = strlen(lc.cvec[i]);
236199767f8SToomas Soome                 ls->buf = lc.cvec[i];
237199767f8SToomas Soome                 refreshLine(ls);
238199767f8SToomas Soome                 ls->len = saved.len;
239199767f8SToomas Soome                 ls->pos = saved.pos;
240199767f8SToomas Soome                 ls->buf = saved.buf;
241199767f8SToomas Soome             } else {
242199767f8SToomas Soome                 refreshLine(ls);
243199767f8SToomas Soome             }
244199767f8SToomas Soome 
245199767f8SToomas Soome             c = getchar();
246199767f8SToomas Soome             if (c <= 0) {
247199767f8SToomas Soome                 freeCompletions(&lc);
248199767f8SToomas Soome                 return -1;
249199767f8SToomas Soome             }
250199767f8SToomas Soome 
251199767f8SToomas Soome             switch(c) {
252199767f8SToomas Soome                 case 9: /* tab */
253199767f8SToomas Soome                     i = (i+1) % (lc.len+1);
254199767f8SToomas Soome                     if (i == lc.len) linenoiseBeep();
255199767f8SToomas Soome                     break;
256199767f8SToomas Soome                 case 27: /* escape */
257199767f8SToomas Soome                     /* Re-show original buffer */
258199767f8SToomas Soome                     if (i < lc.len) refreshLine(ls);
259199767f8SToomas Soome                     stop = 1;
260199767f8SToomas Soome                     break;
261199767f8SToomas Soome                 default:
262199767f8SToomas Soome                     /* Update buffer and return */
263199767f8SToomas Soome                     if (i < lc.len) {
264199767f8SToomas Soome                         nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
265199767f8SToomas Soome                         ls->len = ls->pos = nwritten;
266199767f8SToomas Soome                     }
267199767f8SToomas Soome                     stop = 1;
268199767f8SToomas Soome                     break;
269199767f8SToomas Soome             }
270199767f8SToomas Soome         }
271199767f8SToomas Soome     }
272199767f8SToomas Soome 
273199767f8SToomas Soome     freeCompletions(&lc);
274199767f8SToomas Soome     return c; /* Return last read character */
275199767f8SToomas Soome }
276199767f8SToomas Soome 
277199767f8SToomas Soome /* Register a callback function to be called for tab-completion. */
linenoiseSetCompletionCallback(linenoiseCompletionCallback * fn)278199767f8SToomas Soome void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
279199767f8SToomas Soome     completionCallback = fn;
280199767f8SToomas Soome }
281199767f8SToomas Soome 
282199767f8SToomas Soome /* This function is used by the callback function registered by the user
283199767f8SToomas Soome  * in order to add completion options given the input string when the
284199767f8SToomas Soome  * user typed <tab>. See the example.c source code for a very easy to
285199767f8SToomas Soome  * understand example. */
linenoiseAddCompletion(linenoiseCompletions * lc,const char * str)286199767f8SToomas Soome void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
287199767f8SToomas Soome     size_t len = strlen(str);
288199767f8SToomas Soome     char *copy, **cvec;
289199767f8SToomas Soome 
290199767f8SToomas Soome     copy = malloc(len+1);
291199767f8SToomas Soome     if (copy == NULL) return;
292199767f8SToomas Soome     memcpy(copy,str,len+1);
293199767f8SToomas Soome     cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
294199767f8SToomas Soome     if (cvec == NULL) {
295199767f8SToomas Soome         free(copy);
296199767f8SToomas Soome         return;
297199767f8SToomas Soome     }
298199767f8SToomas Soome     lc->cvec = cvec;
299199767f8SToomas Soome     lc->cvec[lc->len++] = copy;
300199767f8SToomas Soome }
301199767f8SToomas Soome 
302199767f8SToomas Soome /* =========================== Line editing ================================= */
303199767f8SToomas Soome 
304199767f8SToomas Soome /* We define a very simple "append buffer" structure, that is an heap
305199767f8SToomas Soome  * allocated string where we can append to. This is useful in order to
306199767f8SToomas Soome  * write all the escape sequences in a buffer and flush them to the standard
307199767f8SToomas Soome  * output in a single call, to avoid flickering effects. */
308199767f8SToomas Soome struct abuf {
309199767f8SToomas Soome     char *b;
310199767f8SToomas Soome     int len;
311199767f8SToomas Soome };
312199767f8SToomas Soome 
abInit(struct abuf * ab)313199767f8SToomas Soome static void abInit(struct abuf *ab) {
314199767f8SToomas Soome     ab->b = NULL;
315199767f8SToomas Soome     ab->len = 0;
316199767f8SToomas Soome }
317199767f8SToomas Soome 
abAppend(struct abuf * ab,const char * s,int len)318199767f8SToomas Soome static void abAppend(struct abuf *ab, const char *s, int len) {
319199767f8SToomas Soome     char *new = malloc(ab->len+len);
320199767f8SToomas Soome 
321199767f8SToomas Soome     if (new == NULL) return;
322199767f8SToomas Soome     memcpy(new, ab->b, ab->len);
323199767f8SToomas Soome     memcpy(new+ab->len,s,len);
324199767f8SToomas Soome     free(ab->b);
325199767f8SToomas Soome     ab->b = new;
326199767f8SToomas Soome     ab->len += len;
327199767f8SToomas Soome }
328199767f8SToomas Soome 
abFree(struct abuf * ab)329199767f8SToomas Soome static void abFree(struct abuf *ab) {
330199767f8SToomas Soome     free(ab->b);
331199767f8SToomas Soome }
332199767f8SToomas Soome 
333199767f8SToomas Soome /* Single line low level line refresh.
334199767f8SToomas Soome  *
335199767f8SToomas Soome  * Rewrite the currently edited line accordingly to the buffer content,
336199767f8SToomas Soome  * cursor position, and number of columns of the terminal. */
refreshSingleLine(struct linenoiseState * l)337199767f8SToomas Soome static void refreshSingleLine(struct linenoiseState *l) {
338199767f8SToomas Soome     char seq[64];
339199767f8SToomas Soome     size_t plen = strlen(l->prompt);
340199767f8SToomas Soome     char *buf = l->buf;
341199767f8SToomas Soome     size_t len = l->len;
342199767f8SToomas Soome     size_t pos = l->pos;
343199767f8SToomas Soome     struct abuf ab;
344199767f8SToomas Soome 
345199767f8SToomas Soome     while((plen+pos) >= l->cols) {
346199767f8SToomas Soome         buf++;
347199767f8SToomas Soome         len--;
348199767f8SToomas Soome         pos--;
349199767f8SToomas Soome     }
350199767f8SToomas Soome     while (plen+len > l->cols) {
351199767f8SToomas Soome         len--;
352199767f8SToomas Soome     }
353199767f8SToomas Soome 
354199767f8SToomas Soome     abInit(&ab);
355199767f8SToomas Soome     /* Cursor to left edge */
356199767f8SToomas Soome     snprintf(seq,64,"\r");
357199767f8SToomas Soome     abAppend(&ab,seq,strlen(seq));
358199767f8SToomas Soome     /* Write the prompt and the current buffer content */
359199767f8SToomas Soome     abAppend(&ab,l->prompt,strlen(l->prompt));
360199767f8SToomas Soome     abAppend(&ab,buf,len);
361199767f8SToomas Soome     /* Erase to right */
362199767f8SToomas Soome     snprintf(seq,64,"\x1b[K");
363199767f8SToomas Soome     abAppend(&ab,seq,strlen(seq));
364199767f8SToomas Soome     /* Move cursor to original position. */
365199767f8SToomas Soome     snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
366199767f8SToomas Soome     abAppend(&ab,seq,strlen(seq));
367199767f8SToomas Soome     put_bytes(ab.b, ab.len);
368199767f8SToomas Soome 
369199767f8SToomas Soome     abFree(&ab);
370199767f8SToomas Soome }
371199767f8SToomas Soome 
372199767f8SToomas Soome /* Multi line low level line refresh.
373199767f8SToomas Soome  *
374199767f8SToomas Soome  * Rewrite the currently edited line accordingly to the buffer content,
375199767f8SToomas Soome  * cursor position, and number of columns of the terminal. */
refreshMultiLine(struct linenoiseState * l)376199767f8SToomas Soome static void refreshMultiLine(struct linenoiseState *l) {
377199767f8SToomas Soome     char seq[64];
378199767f8SToomas Soome     int plen = strlen(l->prompt);
379199767f8SToomas Soome     int rows = (plen+l->len+l->cols)/l->cols; /* rows used by current buf. */
380199767f8SToomas Soome     int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
381199767f8SToomas Soome     int rpos2; /* rpos after refresh. */
382199767f8SToomas Soome     int col; /* colum position, zero-based. */
383199767f8SToomas Soome     int old_rows = l->maxrows;
384199767f8SToomas Soome     int j;
385199767f8SToomas Soome     struct abuf ab;
386199767f8SToomas Soome 
387199767f8SToomas Soome     /* Update maxrows if needed. */
388199767f8SToomas Soome     if (rows > (int)l->maxrows) l->maxrows = rows;
389199767f8SToomas Soome 
390199767f8SToomas Soome     /* First step: clear all the lines used before. To do so start by
391199767f8SToomas Soome      * going to the last row. */
392199767f8SToomas Soome     abInit(&ab);
393199767f8SToomas Soome     if (old_rows-rpos > 0) {
394199767f8SToomas Soome         snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
395199767f8SToomas Soome         abAppend(&ab,seq,strlen(seq));
396199767f8SToomas Soome     }
397199767f8SToomas Soome 
398199767f8SToomas Soome     /* Now for every row clear it, go up. */
399199767f8SToomas Soome     for (j = 0; j < old_rows-1; j++) {
400199767f8SToomas Soome         snprintf(seq,64,"\r\x1b[0K\x1b[1A");
401199767f8SToomas Soome         abAppend(&ab,seq,strlen(seq));
402199767f8SToomas Soome     }
403199767f8SToomas Soome 
404199767f8SToomas Soome     /* Clean the top line. */
405199767f8SToomas Soome     snprintf(seq,64,"\r\x1b[0K");
406199767f8SToomas Soome     abAppend(&ab,seq,strlen(seq));
407199767f8SToomas Soome 
408199767f8SToomas Soome     /* Write the prompt and the current buffer content */
409199767f8SToomas Soome     abAppend(&ab,l->prompt,strlen(l->prompt));
410199767f8SToomas Soome     abAppend(&ab,l->buf,l->len);
411199767f8SToomas Soome 
412199767f8SToomas Soome     /* If we are at the very end of the screen with our prompt, we need to
413199767f8SToomas Soome      * emit a newline and move the prompt to the first column. */
414199767f8SToomas Soome     if (l->pos &&
415199767f8SToomas Soome         l->pos == l->len &&
416199767f8SToomas Soome         (l->pos+plen) % l->cols == 0)
417199767f8SToomas Soome     {
418199767f8SToomas Soome         abAppend(&ab,"\n",1);
419199767f8SToomas Soome         snprintf(seq,64,"\r");
420199767f8SToomas Soome         abAppend(&ab,seq,strlen(seq));
421199767f8SToomas Soome         rows++;
422199767f8SToomas Soome         if (rows > (int)l->maxrows) l->maxrows = rows;
423199767f8SToomas Soome     }
424199767f8SToomas Soome 
425199767f8SToomas Soome     /* Move cursor to right position. */
426199767f8SToomas Soome     rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
427199767f8SToomas Soome 
428199767f8SToomas Soome     /* Go up till we reach the expected positon. */
429199767f8SToomas Soome     if (rows-rpos2 > 0) {
430199767f8SToomas Soome         snprintf(seq,64,"\x1b[%dA", rows-rpos2);
431199767f8SToomas Soome         abAppend(&ab,seq,strlen(seq));
432199767f8SToomas Soome     }
433199767f8SToomas Soome 
434199767f8SToomas Soome     /* Set column. */
435199767f8SToomas Soome     col = (plen+(int)l->pos) % (int)l->cols;
436199767f8SToomas Soome     if (col)
437199767f8SToomas Soome         snprintf(seq,64,"\r\x1b[%dC", col);
438199767f8SToomas Soome     else
439199767f8SToomas Soome         snprintf(seq,64,"\r");
440199767f8SToomas Soome     abAppend(&ab,seq,strlen(seq));
441199767f8SToomas Soome 
442199767f8SToomas Soome     l->oldpos = l->pos;
443199767f8SToomas Soome 
444199767f8SToomas Soome     put_bytes(ab.b, ab.len);
445199767f8SToomas Soome     abFree(&ab);
446199767f8SToomas Soome }
447199767f8SToomas Soome 
448199767f8SToomas Soome /* Calls the two low level functions refreshSingleLine() or
449199767f8SToomas Soome  * refreshMultiLine() according to the selected mode. */
refreshLine(struct linenoiseState * l)450199767f8SToomas Soome static void refreshLine(struct linenoiseState *l) {
451199767f8SToomas Soome     if (mlmode)
452199767f8SToomas Soome         refreshMultiLine(l);
453199767f8SToomas Soome     else
454199767f8SToomas Soome         refreshSingleLine(l);
455199767f8SToomas Soome }
456199767f8SToomas Soome 
457199767f8SToomas Soome /* Insert the character 'c' at cursor current position.
458199767f8SToomas Soome  *
459199767f8SToomas Soome  * On error writing to the terminal -1 is returned, otherwise 0. */
460199767f8SToomas Soome static int
linenoiseEditInsert(struct linenoiseState * l,char c)461199767f8SToomas Soome linenoiseEditInsert(struct linenoiseState *l, char c) {
462199767f8SToomas Soome     if (l->len < l->buflen) {
463199767f8SToomas Soome         if (l->len == l->pos) {
464199767f8SToomas Soome             l->buf[l->pos] = c;
465199767f8SToomas Soome             l->pos++;
466199767f8SToomas Soome             l->len++;
467199767f8SToomas Soome             l->buf[l->len] = '\0';
468199767f8SToomas Soome             if ((!mlmode && l->plen+l->len < l->cols) /* || mlmode */) {
469199767f8SToomas Soome                 /* Avoid a full update of the line in the
470199767f8SToomas Soome                  * trivial case. */
471199767f8SToomas Soome                 putchar(c);
472199767f8SToomas Soome             } else {
473199767f8SToomas Soome                 refreshLine(l);
474199767f8SToomas Soome             }
475199767f8SToomas Soome         } else {
476199767f8SToomas Soome             memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
477199767f8SToomas Soome             l->buf[l->pos] = c;
478199767f8SToomas Soome             l->len++;
479199767f8SToomas Soome             l->pos++;
480199767f8SToomas Soome             l->buf[l->len] = '\0';
481199767f8SToomas Soome             refreshLine(l);
482199767f8SToomas Soome         }
483199767f8SToomas Soome     }
484199767f8SToomas Soome     return 0;
485199767f8SToomas Soome }
486199767f8SToomas Soome 
487199767f8SToomas Soome /* Move cursor on the left. */
488199767f8SToomas Soome static void
linenoiseEditMoveLeft(struct linenoiseState * l)489199767f8SToomas Soome linenoiseEditMoveLeft(struct linenoiseState *l) {
490199767f8SToomas Soome     if (l->pos > 0) {
491199767f8SToomas Soome         l->pos--;
492199767f8SToomas Soome         refreshLine(l);
493199767f8SToomas Soome     }
494199767f8SToomas Soome }
495199767f8SToomas Soome 
496199767f8SToomas Soome /* Move cursor on the right. */
497199767f8SToomas Soome static void
linenoiseEditMoveRight(struct linenoiseState * l)498199767f8SToomas Soome linenoiseEditMoveRight(struct linenoiseState *l) {
499199767f8SToomas Soome     if (l->pos != l->len) {
500199767f8SToomas Soome         l->pos++;
501199767f8SToomas Soome         refreshLine(l);
502199767f8SToomas Soome     }
503199767f8SToomas Soome }
504199767f8SToomas Soome 
505199767f8SToomas Soome /* Move cursor to the start of the line. */
506199767f8SToomas Soome static void
linenoiseEditMoveHome(struct linenoiseState * l)507199767f8SToomas Soome linenoiseEditMoveHome(struct linenoiseState *l) {
508199767f8SToomas Soome     if (l->pos != 0) {
509199767f8SToomas Soome         l->pos = 0;
510199767f8SToomas Soome         refreshLine(l);
511199767f8SToomas Soome     }
512199767f8SToomas Soome }
513199767f8SToomas Soome 
514199767f8SToomas Soome /* Move cursor to the end of the line. */
515199767f8SToomas Soome static void
linenoiseEditMoveEnd(struct linenoiseState * l)516199767f8SToomas Soome linenoiseEditMoveEnd(struct linenoiseState *l) {
517199767f8SToomas Soome     if (l->pos != l->len) {
518199767f8SToomas Soome         l->pos = l->len;
519199767f8SToomas Soome         refreshLine(l);
520199767f8SToomas Soome     }
521199767f8SToomas Soome }
522199767f8SToomas Soome 
523199767f8SToomas Soome /* Substitute the currently edited line with the next or previous history
524199767f8SToomas Soome  * entry as specified by 'dir'. */
525199767f8SToomas Soome #define LINENOISE_HISTORY_NEXT 0
526199767f8SToomas Soome #define LINENOISE_HISTORY_PREV 1
527199767f8SToomas Soome static void
linenoiseEditHistoryNext(struct linenoiseState * l,int dir)528199767f8SToomas Soome linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
529199767f8SToomas Soome     if (history_len > 1) {
530199767f8SToomas Soome         /* Update the current history entry before to
531199767f8SToomas Soome          * overwrite it with the next one. */
532199767f8SToomas Soome         free(history[history_len - 1 - l->history_index]);
533199767f8SToomas Soome         history[history_len - 1 - l->history_index] = strdup(l->buf);
534199767f8SToomas Soome         /* Show the new entry */
535199767f8SToomas Soome         l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
536199767f8SToomas Soome         if (l->history_index < 0) {
537199767f8SToomas Soome             l->history_index = 0;
538199767f8SToomas Soome             return;
539199767f8SToomas Soome         } else if (l->history_index >= history_len) {
540199767f8SToomas Soome             l->history_index = history_len-1;
541199767f8SToomas Soome             return;
542199767f8SToomas Soome         }
543199767f8SToomas Soome         strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
544199767f8SToomas Soome         l->buf[l->buflen-1] = '\0';
545199767f8SToomas Soome         l->len = l->pos = strlen(l->buf);
546199767f8SToomas Soome         refreshLine(l);
547199767f8SToomas Soome     }
548199767f8SToomas Soome }
549199767f8SToomas Soome 
550199767f8SToomas Soome /* Delete the character at the right of the cursor without altering the cursor
551199767f8SToomas Soome  * position. Basically this is what happens with the "Delete" keyboard key. */
552199767f8SToomas Soome static void
linenoiseEditDelete(struct linenoiseState * l)553199767f8SToomas Soome linenoiseEditDelete(struct linenoiseState *l) {
554199767f8SToomas Soome     if (l->len > 0 && l->pos < l->len) {
555199767f8SToomas Soome         memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
556199767f8SToomas Soome         l->len--;
557199767f8SToomas Soome         l->buf[l->len] = '\0';
558199767f8SToomas Soome         refreshLine(l);
559199767f8SToomas Soome     }
560199767f8SToomas Soome }
561199767f8SToomas Soome 
562199767f8SToomas Soome /* Backspace implementation. */
563199767f8SToomas Soome static void
linenoiseEditBackspace(struct linenoiseState * l)564199767f8SToomas Soome linenoiseEditBackspace(struct linenoiseState *l) {
565199767f8SToomas Soome     if (l->pos > 0 && l->len > 0) {
566199767f8SToomas Soome         memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
567199767f8SToomas Soome         l->pos--;
568199767f8SToomas Soome         l->len--;
569199767f8SToomas Soome         l->buf[l->len] = '\0';
570199767f8SToomas Soome         refreshLine(l);
571199767f8SToomas Soome     }
572199767f8SToomas Soome }
573199767f8SToomas Soome 
574199767f8SToomas Soome /* Delete the previosu word, maintaining the cursor at the start of the
575199767f8SToomas Soome  * current word. */
576199767f8SToomas Soome static void
linenoiseEditDeletePrevWord(struct linenoiseState * l)577199767f8SToomas Soome linenoiseEditDeletePrevWord(struct linenoiseState *l) {
578199767f8SToomas Soome     size_t old_pos = l->pos;
579199767f8SToomas Soome     size_t diff;
580199767f8SToomas Soome 
581199767f8SToomas Soome     while (l->pos > 0 && l->buf[l->pos-1] == ' ')
582199767f8SToomas Soome         l->pos--;
583199767f8SToomas Soome     while (l->pos > 0 && l->buf[l->pos-1] != ' ')
584199767f8SToomas Soome         l->pos--;
585199767f8SToomas Soome     diff = old_pos - l->pos;
586199767f8SToomas Soome     memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
587199767f8SToomas Soome     l->len -= diff;
588199767f8SToomas Soome     refreshLine(l);
589199767f8SToomas Soome }
590199767f8SToomas Soome 
591199767f8SToomas Soome /* This function is the core of the line editing capability of linenoise.
592199767f8SToomas Soome  * It expects 'fd' to be already in "raw mode" so that every key pressed
593199767f8SToomas Soome  * will be returned ASAP to read().
594199767f8SToomas Soome  *
595199767f8SToomas Soome  * The resulting string is put into 'buf' when the user type enter, or
596199767f8SToomas Soome  * when ctrl+d is typed.
597199767f8SToomas Soome  *
598199767f8SToomas Soome  * The function returns the length of the current buffer. */
linenoiseEdit(char * buf,size_t buflen,const char * prompt)599199767f8SToomas Soome static int linenoiseEdit(char *buf, size_t buflen, const char *prompt)
600199767f8SToomas Soome {
601199767f8SToomas Soome     struct linenoiseState l;
602199767f8SToomas Soome 
603199767f8SToomas Soome     /* Populate the linenoise state that we pass to functions implementing
604199767f8SToomas Soome      * specific editing functionalities. */
605199767f8SToomas Soome     l.buf = buf;
606199767f8SToomas Soome     l.buflen = buflen;
607199767f8SToomas Soome     l.prompt = prompt;
608199767f8SToomas Soome     l.plen = strlen(prompt);
609199767f8SToomas Soome     l.oldpos = l.pos = 0;
610199767f8SToomas Soome     l.len = 0;
611199767f8SToomas Soome     l.cols = getColumns();
612199767f8SToomas Soome     l.maxrows = 0;
613199767f8SToomas Soome     l.history_index = 0;
614199767f8SToomas Soome 
615199767f8SToomas Soome     /* Buffer starts empty. */
616199767f8SToomas Soome     l.buf[0] = '\0';
617199767f8SToomas Soome     l.buflen--; /* Make sure there is always space for the nulterm */
618199767f8SToomas Soome 
619199767f8SToomas Soome     /* The latest history entry is always our current buffer, that
620199767f8SToomas Soome      * initially is just an empty string. */
621199767f8SToomas Soome     linenoiseHistoryAdd("");
622199767f8SToomas Soome 
623199767f8SToomas Soome     printf ("%s", prompt);
624199767f8SToomas Soome     while(1) {
625199767f8SToomas Soome         char c;
626199767f8SToomas Soome         char seq[3];
627199767f8SToomas Soome 
628199767f8SToomas Soome         c = getchar();
629199767f8SToomas Soome 	if (c == -1)
630199767f8SToomas Soome 		continue;
631199767f8SToomas Soome 
632199767f8SToomas Soome         /* Only autocomplete when the callback is set. It returns < 0 when
633199767f8SToomas Soome          * there was an error reading from fd. Otherwise it will return the
634199767f8SToomas Soome          * character that should be handled next. */
635199767f8SToomas Soome         if (c == 9 && completionCallback != NULL) {
636199767f8SToomas Soome             c = completeLine(&l);
637199767f8SToomas Soome             /* Return on errors */
638199767f8SToomas Soome             if (c < 0) return l.len;
639199767f8SToomas Soome             /* Read next character when 0 */
640199767f8SToomas Soome             if (c == 0) continue;
641199767f8SToomas Soome         }
642199767f8SToomas Soome 
643199767f8SToomas Soome         switch(c) {
644199767f8SToomas Soome         case ENTER:    /* enter */
645199767f8SToomas Soome             history_len--;
646199767f8SToomas Soome             free(history[history_len]);
647199767f8SToomas Soome             if (mlmode) linenoiseEditMoveEnd(&l);
648199767f8SToomas Soome             return (int)l.len;
649199767f8SToomas Soome         case CTRL_C:     /* ctrl-c */
650199767f8SToomas Soome             buf[0] = '\0';
651199767f8SToomas Soome             l.pos = l.len = 0;
652199767f8SToomas Soome             refreshLine(&l);
653c4b91d4bSToomas Soome 	    break;
654199767f8SToomas Soome         case BACKSPACE:   /* backspace */
655199767f8SToomas Soome         case 8:     /* ctrl-h */
656199767f8SToomas Soome             linenoiseEditBackspace(&l);
657199767f8SToomas Soome             break;
658199767f8SToomas Soome         case CTRL_D:     /* ctrl-d, remove char at right of cursor. */
659199767f8SToomas Soome             if (l.len > 0) {
660199767f8SToomas Soome                 linenoiseEditDelete(&l);
661199767f8SToomas Soome             }
662199767f8SToomas Soome             break;
663199767f8SToomas Soome         case CTRL_T:    /* ctrl-t, swaps current character with previous. */
664199767f8SToomas Soome             if (l.pos > 0 && l.pos < l.len) {
665199767f8SToomas Soome                 int aux = buf[l.pos-1];
666199767f8SToomas Soome                 buf[l.pos-1] = buf[l.pos];
667199767f8SToomas Soome                 buf[l.pos] = aux;
668199767f8SToomas Soome                 if (l.pos != l.len-1) l.pos++;
669199767f8SToomas Soome                 refreshLine(&l);
670199767f8SToomas Soome             }
671199767f8SToomas Soome             break;
672199767f8SToomas Soome         case CTRL_B:     /* ctrl-b */
673199767f8SToomas Soome             linenoiseEditMoveLeft(&l);
674199767f8SToomas Soome             break;
675199767f8SToomas Soome         case CTRL_F:     /* ctrl-f */
676199767f8SToomas Soome             linenoiseEditMoveRight(&l);
677199767f8SToomas Soome             break;
678199767f8SToomas Soome         case CTRL_P:    /* ctrl-p */
679199767f8SToomas Soome             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
680199767f8SToomas Soome             break;
681199767f8SToomas Soome         case CTRL_N:    /* ctrl-n */
682199767f8SToomas Soome             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
683199767f8SToomas Soome             break;
684199767f8SToomas Soome         case ESC:    /* escape sequence */
685199767f8SToomas Soome             /* Read the next two bytes representing the escape sequence.
686199767f8SToomas Soome              * Use two calls to handle slow terminals returning the two
687199767f8SToomas Soome              * chars at different times. */
688199767f8SToomas Soome             seq[0] = getchar();
689199767f8SToomas Soome             seq[1] = getchar();
690199767f8SToomas Soome 
691199767f8SToomas Soome             /* ESC [ sequences. */
692199767f8SToomas Soome             if (seq[0] == '[') {
693199767f8SToomas Soome                 if (seq[1] >= '0' && seq[1] <= '9') {
694199767f8SToomas Soome                     /* Extended escape, read additional byte. */
695199767f8SToomas Soome                     seq[2] = getchar();
696199767f8SToomas Soome                     if (seq[2] == '~') {
697199767f8SToomas Soome                         switch(seq[1]) {
698199767f8SToomas Soome                         case '3': /* Delete key. */
699199767f8SToomas Soome                             linenoiseEditDelete(&l);
700199767f8SToomas Soome                             break;
701199767f8SToomas Soome                         }
702199767f8SToomas Soome                     }
703199767f8SToomas Soome                 } else {
704199767f8SToomas Soome                     switch(seq[1]) {
705199767f8SToomas Soome                     case 'A': /* Up */
706199767f8SToomas Soome                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
707199767f8SToomas Soome                         break;
708199767f8SToomas Soome                     case 'B': /* Down */
709199767f8SToomas Soome                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
710199767f8SToomas Soome                         break;
711199767f8SToomas Soome                     case 'C': /* Right */
712199767f8SToomas Soome                         linenoiseEditMoveRight(&l);
713199767f8SToomas Soome                         break;
714199767f8SToomas Soome                     case 'D': /* Left */
715199767f8SToomas Soome                         linenoiseEditMoveLeft(&l);
716199767f8SToomas Soome                         break;
717199767f8SToomas Soome                     case 'H': /* Home */
718199767f8SToomas Soome                         linenoiseEditMoveHome(&l);
719199767f8SToomas Soome                         break;
720199767f8SToomas Soome                     case 'F': /* End*/
721199767f8SToomas Soome                         linenoiseEditMoveEnd(&l);
722199767f8SToomas Soome                         break;
723199767f8SToomas Soome                     }
724199767f8SToomas Soome                 }
725199767f8SToomas Soome             }
726199767f8SToomas Soome 
727199767f8SToomas Soome             /* ESC O sequences. */
728199767f8SToomas Soome             else if (seq[0] == 'O') {
729199767f8SToomas Soome                 switch(seq[1]) {
730199767f8SToomas Soome                 case 'H': /* Home */
731199767f8SToomas Soome                     linenoiseEditMoveHome(&l);
732199767f8SToomas Soome                     break;
733199767f8SToomas Soome                 case 'F': /* End*/
734199767f8SToomas Soome                     linenoiseEditMoveEnd(&l);
735199767f8SToomas Soome                     break;
736199767f8SToomas Soome                 }
737199767f8SToomas Soome             }
738199767f8SToomas Soome             break;
739199767f8SToomas Soome         default:
740199767f8SToomas Soome             if (linenoiseEditInsert(&l,c)) return -1;
741199767f8SToomas Soome             break;
742199767f8SToomas Soome         case CTRL_U: /* Ctrl+u, delete the whole line. */
743199767f8SToomas Soome             buf[0] = '\0';
744199767f8SToomas Soome             l.pos = l.len = 0;
745199767f8SToomas Soome             refreshLine(&l);
746199767f8SToomas Soome             break;
747199767f8SToomas Soome         case CTRL_K: /* Ctrl+k, delete from current to end of line. */
748199767f8SToomas Soome             buf[l.pos] = '\0';
749199767f8SToomas Soome             l.len = l.pos;
750199767f8SToomas Soome             refreshLine(&l);
751199767f8SToomas Soome             break;
752199767f8SToomas Soome         case CTRL_A: /* Ctrl+a, go to the start of the line */
753199767f8SToomas Soome             linenoiseEditMoveHome(&l);
754199767f8SToomas Soome             break;
755199767f8SToomas Soome         case CTRL_E: /* ctrl+e, go to the end of the line */
756199767f8SToomas Soome             linenoiseEditMoveEnd(&l);
757199767f8SToomas Soome             break;
758199767f8SToomas Soome         case CTRL_L: /* ctrl+l, clear screen */
759199767f8SToomas Soome             linenoiseClearScreen();
760199767f8SToomas Soome             refreshLine(&l);
761199767f8SToomas Soome             break;
762199767f8SToomas Soome         case CTRL_W: /* ctrl+w, delete previous word */
763199767f8SToomas Soome             linenoiseEditDeletePrevWord(&l);
764199767f8SToomas Soome             break;
765199767f8SToomas Soome         }
766199767f8SToomas Soome     }
767199767f8SToomas Soome     return l.len;
768199767f8SToomas Soome }
769199767f8SToomas Soome 
770199767f8SToomas Soome /* The high level function that is the main API of the linenoise library.
771199767f8SToomas Soome  * This function checks if the terminal has basic capabilities, just checking
772199767f8SToomas Soome  * for a blacklist of stupid terminals, and later either calls the line
773199767f8SToomas Soome  * editing function or uses dummy fgets() so that you will be able to type
774199767f8SToomas Soome  * something even in the most desperate of the conditions. */
linenoise(const char * prompt)775199767f8SToomas Soome char *linenoise(const char *prompt) {
776199767f8SToomas Soome     char buf[LINENOISE_MAX_LINE];
777199767f8SToomas Soome     int count;
778199767f8SToomas Soome 
779199767f8SToomas Soome     cons_mode(C_MODERAW);
780199767f8SToomas Soome     count = linenoiseEdit(buf,LINENOISE_MAX_LINE,prompt);
781199767f8SToomas Soome     cons_mode(0);
782199767f8SToomas Soome     printf("\n");
783199767f8SToomas Soome     if (count == -1) return NULL;
784199767f8SToomas Soome     return strdup(buf);
785199767f8SToomas Soome }
786199767f8SToomas Soome 
787199767f8SToomas Soome /* ================================ History ================================= */
788199767f8SToomas Soome 
789199767f8SToomas Soome /* This is the API call to add a new entry in the linenoise history.
790199767f8SToomas Soome  * It uses a fixed array of char pointers that are shifted (memmoved)
791199767f8SToomas Soome  * when the history max length is reached in order to remove the older
792199767f8SToomas Soome  * entry and make room for the new one, so it is not exactly suitable for huge
793199767f8SToomas Soome  * histories, but will work well for a few hundred of entries.
794199767f8SToomas Soome  *
795199767f8SToomas Soome  * Using a circular buffer is smarter, but a bit more complex to handle. */
linenoiseHistoryAdd(const char * line)796199767f8SToomas Soome int linenoiseHistoryAdd(const char *line) {
797199767f8SToomas Soome     char *linecopy;
798199767f8SToomas Soome 
799199767f8SToomas Soome     if (history_max_len == 0) return 0;
800199767f8SToomas Soome 
801199767f8SToomas Soome     /* Initialization on first call. */
802199767f8SToomas Soome     if (history == NULL) {
803199767f8SToomas Soome         history = malloc(sizeof(char*)*history_max_len);
804199767f8SToomas Soome         if (history == NULL) return 0;
805199767f8SToomas Soome         memset(history,0,(sizeof(char*)*history_max_len));
806199767f8SToomas Soome     }
807199767f8SToomas Soome 
808199767f8SToomas Soome     /* Don't add duplicated lines. */
809199767f8SToomas Soome     if (history_len && !strcmp(history[history_len-1], line)) return 0;
810199767f8SToomas Soome 
811199767f8SToomas Soome     /* Add an heap allocated copy of the line in the history.
812199767f8SToomas Soome      * If we reached the max length, remove the older line. */
813199767f8SToomas Soome     linecopy = strdup(line);
814199767f8SToomas Soome     if (!linecopy) return 0;
815199767f8SToomas Soome     if (history_len == history_max_len) {
816199767f8SToomas Soome         free(history[0]);
817199767f8SToomas Soome         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
818199767f8SToomas Soome         history_len--;
819199767f8SToomas Soome     }
820199767f8SToomas Soome     history[history_len] = linecopy;
821199767f8SToomas Soome     history_len++;
822199767f8SToomas Soome     return 1;
823199767f8SToomas Soome }
824199767f8SToomas Soome 
825199767f8SToomas Soome /* Set the maximum length for the history. This function can be called even
826199767f8SToomas Soome  * if there is already some history, the function will make sure to retain
827199767f8SToomas Soome  * just the latest 'len' elements if the new history length value is smaller
828199767f8SToomas Soome  * than the amount of items already inside the history. */
linenoiseHistorySetMaxLen(int len)829199767f8SToomas Soome int linenoiseHistorySetMaxLen(int len) {
830199767f8SToomas Soome     char **new;
831199767f8SToomas Soome 
832199767f8SToomas Soome     if (len < 1) return 0;
833199767f8SToomas Soome     if (history) {
834199767f8SToomas Soome         int tocopy = history_len;
835199767f8SToomas Soome 
836199767f8SToomas Soome         new = malloc(sizeof(char*)*len);
837199767f8SToomas Soome         if (new == NULL) return 0;
838199767f8SToomas Soome 
839199767f8SToomas Soome         /* If we can't copy everything, free the elements we'll not use. */
840199767f8SToomas Soome         if (len < tocopy) {
841199767f8SToomas Soome             int j;
842199767f8SToomas Soome 
843199767f8SToomas Soome             for (j = 0; j < tocopy-len; j++) free(history[j]);
844199767f8SToomas Soome             tocopy = len;
845199767f8SToomas Soome         }
846199767f8SToomas Soome         memset(new,0,sizeof(char*)*len);
847199767f8SToomas Soome         memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
848199767f8SToomas Soome         free(history);
849199767f8SToomas Soome         history = new;
850199767f8SToomas Soome     }
851199767f8SToomas Soome     history_max_len = len;
852199767f8SToomas Soome     if (history_len > history_max_len)
853199767f8SToomas Soome         history_len = history_max_len;
854199767f8SToomas Soome     return 1;
855199767f8SToomas Soome }
856