Branch data Line data Source code
1 : : /* linenoise.c -- guerrilla line editing library against the idea that a
2 : : * line editing lib needs to be 20,000 lines of C code.
3 : : *
4 : : * You can find the latest source code at:
5 : : *
6 : : * http://github.com/antirez/linenoise
7 : : *
8 : : * Does a number of crazy assumptions that happen to be true in 99.9999% of
9 : : * the 2010 UNIX computers around.
10 : : *
11 : : * ------------------------------------------------------------------------
12 : : *
13 : : * Copyright (c) 2010-2016, Salvatore Sanfilippo <antirez at gmail dot com>
14 : : * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
15 : : *
16 : : * All rights reserved.
17 : : *
18 : : * Redistribution and use in source and binary forms, with or without
19 : : * modification, are permitted provided that the following conditions are
20 : : * met:
21 : : *
22 : : * * Redistributions of source code must retain the above copyright
23 : : * notice, this list of conditions and the following disclaimer.
24 : : *
25 : : * * Redistributions in binary form must reproduce the above copyright
26 : : * notice, this list of conditions and the following disclaimer in the
27 : : * documentation and/or other materials provided with the distribution.
28 : : *
29 : : * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 : : * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 : : * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 : : * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 : : * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 : : * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 : : * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 : : * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 : : * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 : : * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 : : * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 : : *
41 : : * ------------------------------------------------------------------------
42 : : *
43 : : * References:
44 : : * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
45 : : * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
46 : : *
47 : : * Todo list:
48 : : * - Filter bogus Ctrl+<char> combinations.
49 : : * - Win32 support
50 : : *
51 : : * Bloat:
52 : : * - History search like Ctrl+r in readline?
53 : : *
54 : : * List of escape sequences used by this program, we do everything just
55 : : * with three sequences. In order to be so cheap we may have some
56 : : * flickering effect with some slow terminal, but the lesser sequences
57 : : * the more compatible.
58 : : *
59 : : * EL (Erase Line)
60 : : * Sequence: ESC [ n K
61 : : * Effect: if n is 0 or missing, clear from cursor to end of line
62 : : * Effect: if n is 1, clear from beginning of line to cursor
63 : : * Effect: if n is 2, clear entire line
64 : : *
65 : : * CUF (CUrsor Forward)
66 : : * Sequence: ESC [ n C
67 : : * Effect: moves cursor forward n chars
68 : : *
69 : : * CUB (CUrsor Backward)
70 : : * Sequence: ESC [ n D
71 : : * Effect: moves cursor backward n chars
72 : : *
73 : : * The following is used to get the terminal width if getting
74 : : * the width with the TIOCGWINSZ ioctl fails
75 : : *
76 : : * DSR (Device Status Report)
77 : : * Sequence: ESC [ 6 n
78 : : * Effect: reports the current cusor position as ESC [ n ; m R
79 : : * where n is the row and m is the column
80 : : *
81 : : * When multi line mode is enabled, we also use an additional escape
82 : : * sequence. However multi line editing is disabled by default.
83 : : *
84 : : * CUU (Cursor Up)
85 : : * Sequence: ESC [ n A
86 : : * Effect: moves cursor up of n chars.
87 : : *
88 : : * CUD (Cursor Down)
89 : : * Sequence: ESC [ n B
90 : : * Effect: moves cursor down of n chars.
91 : : *
92 : : * When linenoiseClearScreen() is called, two additional escape sequences
93 : : * are used in order to clear the screen and position the cursor at home
94 : : * position.
95 : : *
96 : : * CUP (Cursor position)
97 : : * Sequence: ESC [ H
98 : : * Effect: moves the cursor to upper left corner
99 : : *
100 : : * ED (Erase display)
101 : : * Sequence: ESC [ 2 J
102 : : * Effect: clear the whole screen
103 : : *
104 : : */
105 : :
106 : : #include <termios.h>
107 : : #include <unistd.h>
108 : : #include <stdlib.h>
109 : : #include <stdio.h>
110 : : #include <errno.h>
111 : : #include <string.h>
112 : : #include <stdlib.h>
113 : : #include <ctype.h>
114 : : #include <sys/stat.h>
115 : : #include <sys/types.h>
116 : : #include <sys/ioctl.h>
117 : : #include <unistd.h>
118 : : #include "linenoise.h"
119 : :
120 : : #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
121 : : #define LINENOISE_MAX_LINE 4096
122 : : static char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
123 : : static linenoiseCompletionCallback *completionCallback = NULL;
124 : : static linenoiseHintsCallback *hintsCallback = NULL;
125 : : static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
126 : :
127 : : static struct termios orig_termios; /* In order to restore at exit.*/
128 : : static int rawmode = 0; /* For atexit() function to check if restore is needed*/
129 : : static int mlmode = 0; /* Multi line mode. Default is single line. */
130 : : static int atexit_registered = 0; /* Register atexit just 1 time. */
131 : : static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
132 : : static int history_len = 0;
133 : : static char **history = NULL;
134 : :
135 : : /* The linenoiseState structure represents the state during line editing.
136 : : * We pass this state to functions implementing specific editing
137 : : * functionalities. */
138 : : struct linenoiseState {
139 : : int ifd; /* Terminal stdin file descriptor. */
140 : : int ofd; /* Terminal stdout file descriptor. */
141 : : char *buf; /* Edited line buffer. */
142 : : size_t buflen; /* Edited line buffer size. */
143 : : const char *prompt; /* Prompt to display. */
144 : : size_t plen; /* Prompt length. */
145 : : size_t pos; /* Current cursor position. */
146 : : size_t oldpos; /* Previous refresh cursor position. */
147 : : size_t len; /* Current edited line length. */
148 : : size_t cols; /* Number of columns in terminal. */
149 : : size_t maxrows; /* Maximum num of rows used so far (multiline mode) */
150 : : int history_index; /* The history index we are currently editing. */
151 : : };
152 : :
153 : : enum KEY_ACTION{
154 : : KEY_NULL = 0, /* NULL */
155 : : CTRL_A = 1, /* Ctrl+a */
156 : : CTRL_B = 2, /* Ctrl-b */
157 : : CTRL_C = 3, /* Ctrl-c */
158 : : CTRL_D = 4, /* Ctrl-d */
159 : : CTRL_E = 5, /* Ctrl-e */
160 : : CTRL_F = 6, /* Ctrl-f */
161 : : CTRL_H = 8, /* Ctrl-h */
162 : : TAB = 9, /* Tab */
163 : : CTRL_K = 11, /* Ctrl+k */
164 : : CTRL_L = 12, /* Ctrl+l */
165 : : ENTER = 13, /* Enter */
166 : : CTRL_N = 14, /* Ctrl-n */
167 : : CTRL_P = 16, /* Ctrl-p */
168 : : CTRL_T = 20, /* Ctrl-t */
169 : : CTRL_U = 21, /* Ctrl+u */
170 : : CTRL_W = 23, /* Ctrl+w */
171 : : ESC = 27, /* Escape */
172 : : BACKSPACE = 127 /* Backspace */
173 : : };
174 : :
175 : : static void linenoiseAtExit(void);
176 : : int linenoiseHistoryAdd(const char *line);
177 : : static void refreshLine(struct linenoiseState *l);
178 : :
179 : : /* Debugging macro. */
180 : : #if 0
181 : : FILE *lndebug_fp = NULL;
182 : : #define lndebug(...) \
183 : : do { \
184 : : if (lndebug_fp == NULL) { \
185 : : lndebug_fp = fopen("/tmp/lndebug.txt","a"); \
186 : : fprintf(lndebug_fp, \
187 : : "[%d %d %d] p: %d, rows: %d, rpos: %d, max: %d, oldmax: %d\n", \
188 : : (int)l->len,(int)l->pos,(int)l->oldpos,plen,rows,rpos, \
189 : : (int)l->maxrows,old_rows); \
190 : : } \
191 : : fprintf(lndebug_fp, ", " __VA_ARGS__); \
192 : : fflush(lndebug_fp); \
193 : : } while (0)
194 : : #else
195 : : #define lndebug(fmt, ...)
196 : : #endif
197 : :
198 : : /* ======================= Low level terminal handling ====================== */
199 : :
200 : : /* Set if to use or not the multi line mode. */
201 : 0 : void linenoiseSetMultiLine(int ml) {
202 : 0 : mlmode = ml;
203 : 0 : }
204 : :
205 : : /* Return true if the terminal name is in the list of terminals we know are
206 : : * not able to understand basic escape sequences. */
207 : 0 : static int isUnsupportedTerm(void) {
208 : 0 : char *term = getenv("TERM");
209 : : int j;
210 : :
211 [ # # ]: 0 : if (term == NULL) return 0;
212 [ # # ]: 0 : for (j = 0; unsupported_term[j]; j++)
213 [ # # ]: 0 : if (!strcasecmp(term,unsupported_term[j])) return 1;
214 : 0 : return 0;
215 : 0 : }
216 : :
217 : : /* Raw mode: 1960 magic shit. */
218 : 0 : static int enableRawMode(int fd) {
219 : : struct termios raw;
220 : :
221 [ # # ]: 0 : if (!isatty(STDIN_FILENO)) goto fatal;
222 [ # # ]: 0 : if (!atexit_registered) {
223 : 0 : atexit(linenoiseAtExit);
224 : 0 : atexit_registered = 1;
225 : 0 : }
226 [ # # ]: 0 : if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
227 : :
228 : 0 : raw = orig_termios; /* modify the original mode */
229 : : /* input modes: no break, no CR to NL, no parity check, no strip char,
230 : : * no start/stop output control. */
231 : 0 : raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
232 : : /* output modes - disable post processing */
233 : 0 : raw.c_oflag &= ~(OPOST);
234 : : /* control modes - set 8 bit chars */
235 : 0 : raw.c_cflag |= (CS8);
236 : : /* local modes - choing off, canonical off, no extended functions,
237 : : * no signal chars (^Z,^C) */
238 : 0 : raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
239 : : /* control chars - set return condition: min number of bytes and timer.
240 : : * We want read to return every single byte, without timeout. */
241 : 0 : raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
242 : :
243 : : /* put terminal in raw mode after flushing */
244 [ # # ]: 0 : if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
245 : 0 : rawmode = 1;
246 : 0 : return 0;
247 : :
248 : : fatal:
249 : 0 : errno = ENOTTY;
250 : 0 : return -1;
251 : 0 : }
252 : :
253 : 0 : static void disableRawMode(int fd) {
254 : : /* Don't even check the return value as it's too late. */
255 [ # # # # ]: 0 : if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
256 : 0 : rawmode = 0;
257 : 0 : }
258 : :
259 : : /* Use the ESC [6n escape sequence to query the horizontal cursor position
260 : : * and return it. On error -1 is returned, on success the position of the
261 : : * cursor. */
262 : 0 : static int getCursorPosition(int ifd, int ofd) {
263 : : char buf[32];
264 : : int cols, rows;
265 : 0 : unsigned int i = 0;
266 : :
267 : : /* Report cursor location */
268 [ # # ]: 0 : if (write(ofd, "\x1b[6n", 4) != 4) return -1;
269 : :
270 : : /* Read the response: ESC [ rows ; cols R */
271 [ # # ]: 0 : while (i < sizeof(buf)-1) {
272 [ # # ]: 0 : if (read(ifd,buf+i,1) != 1) break;
273 [ # # ]: 0 : if (buf[i] == 'R') break;
274 : 0 : i++;
275 : : }
276 : 0 : buf[i] = '\0';
277 : :
278 : : /* Parse it. */
279 [ # # # # ]: 0 : if (buf[0] != ESC || buf[1] != '[') return -1;
280 [ # # ]: 0 : if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
281 : 0 : return cols;
282 : 0 : }
283 : :
284 : : /* Try to get the number of columns in the current terminal, or assume 80
285 : : * if it fails. */
286 : 0 : static int getColumns(int ifd, int ofd) {
287 : : struct winsize ws;
288 : :
289 [ # # # # ]: 0 : if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
290 : : /* ioctl() failed. Try to query the terminal itself. */
291 : : int start, cols;
292 : :
293 : : /* Get the initial position so we can restore it later. */
294 : 0 : start = getCursorPosition(ifd,ofd);
295 [ # # ]: 0 : if (start == -1) goto failed;
296 : :
297 : : /* Go to right margin and get position. */
298 [ # # ]: 0 : if (write(ofd,"\x1b[999C",6) != 6) goto failed;
299 : 0 : cols = getCursorPosition(ifd,ofd);
300 [ # # ]: 0 : if (cols == -1) goto failed;
301 : :
302 : : /* Restore position. */
303 [ # # ]: 0 : if (cols > start) {
304 : : char seq[32];
305 : 0 : snprintf(seq,32,"\x1b[%dD",cols-start);
306 [ # # ]: 0 : if (write(ofd,seq,strlen(seq)) == -1) {
307 : : /* Can't recover... */
308 : 0 : }
309 : 0 : }
310 : 0 : return cols;
311 : : } else {
312 : 0 : return ws.ws_col;
313 : : }
314 : :
315 : : failed:
316 : 0 : return 80;
317 : 0 : }
318 : :
319 : : /* Clear the screen. Used to handle ctrl+l */
320 : 0 : void linenoiseClearScreen(void) {
321 [ # # ]: 0 : if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
322 : : /* nothing to do, just to avoid warning. */
323 : 0 : }
324 : 0 : }
325 : :
326 : : /* Beep, used for completion when there is nothing to complete or when all
327 : : * the choices were already shown. */
328 : 0 : static void linenoiseBeep(void) {
329 : 0 : fprintf(stderr, "\x7");
330 : 0 : fflush(stderr);
331 : 0 : }
332 : :
333 : : /* ============================== Completion ================================ */
334 : :
335 : : /* Free a list of completion option populated by linenoiseAddCompletion(). */
336 : 0 : static void freeCompletions(linenoiseCompletions *lc) {
337 : : size_t i;
338 [ # # ]: 0 : for (i = 0; i < lc->len; i++)
339 : 0 : free(lc->cvec[i]);
340 [ # # ]: 0 : if (lc->cvec != NULL)
341 : 0 : free(lc->cvec);
342 : 0 : }
343 : :
344 : : /* This is an helper function for linenoiseEdit() and is called when the
345 : : * user types the <tab> key in order to complete the string currently in the
346 : : * input.
347 : : *
348 : : * The state of the editing is encapsulated into the pointed linenoiseState
349 : : * structure as described in the structure definition. */
350 : 0 : static int completeLine(struct linenoiseState *ls) {
351 : 0 : linenoiseCompletions lc = { 0, NULL };
352 : : int nread, nwritten;
353 : 0 : char c = 0;
354 : :
355 : 0 : completionCallback(ls->buf,&lc);
356 [ # # ]: 0 : if (lc.len == 0) {
357 : 0 : linenoiseBeep();
358 : 0 : } else {
359 : 0 : size_t stop = 0, i = 0;
360 : :
361 [ # # ]: 0 : while(!stop) {
362 : : /* Show completion or original buffer */
363 [ # # ]: 0 : if (i < lc.len) {
364 : 0 : struct linenoiseState saved = *ls;
365 : :
366 : 0 : ls->len = ls->pos = strlen(lc.cvec[i]);
367 : 0 : ls->buf = lc.cvec[i];
368 : 0 : refreshLine(ls);
369 : 0 : ls->len = saved.len;
370 : 0 : ls->pos = saved.pos;
371 : 0 : ls->buf = saved.buf;
372 : 0 : } else {
373 : 0 : refreshLine(ls);
374 : : }
375 : :
376 : 0 : nread = read(ls->ifd,&c,1);
377 [ # # ]: 0 : if (nread <= 0) {
378 : 0 : freeCompletions(&lc);
379 : 0 : return -1;
380 : : }
381 : :
382 [ # # # ]: 0 : switch(c) {
383 : : case 9: /* tab */
384 : 0 : i = (i+1) % (lc.len+1);
385 [ # # ]: 0 : if (i == lc.len) linenoiseBeep();
386 : 0 : break;
387 : : case 27: /* escape */
388 : : /* Re-show original buffer */
389 [ # # ]: 0 : if (i < lc.len) refreshLine(ls);
390 : 0 : stop = 1;
391 : 0 : break;
392 : : default:
393 : : /* Update buffer and return */
394 [ # # ]: 0 : if (i < lc.len) {
395 : 0 : nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
396 : 0 : ls->len = ls->pos = nwritten;
397 : 0 : }
398 : 0 : stop = 1;
399 : 0 : break;
400 : : }
401 : : }
402 : : }
403 : :
404 : 0 : freeCompletions(&lc);
405 : 0 : return c; /* Return last read character */
406 : 0 : }
407 : :
408 : : /* Register a callback function to be called for tab-completion. */
409 : 0 : void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
410 : 0 : completionCallback = fn;
411 : 0 : }
412 : :
413 : : /* Register a hits function to be called to show hits to the user at the
414 : : * right of the prompt. */
415 : 0 : void linenoiseSetHintsCallback(linenoiseHintsCallback *fn) {
416 : 0 : hintsCallback = fn;
417 : 0 : }
418 : :
419 : : /* Register a function to free the hints returned by the hints callback
420 : : * registered with linenoiseSetHintsCallback(). */
421 : 0 : void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *fn) {
422 : 0 : freeHintsCallback = fn;
423 : 0 : }
424 : :
425 : : /* This function is used by the callback function registered by the user
426 : : * in order to add completion options given the input string when the
427 : : * user typed <tab>. See the example.c source code for a very easy to
428 : : * understand example. */
429 : 0 : void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
430 : 0 : size_t len = strlen(str);
431 : : char *copy, **cvec;
432 : :
433 : 0 : copy = malloc(len+1);
434 [ # # ]: 0 : if (copy == NULL) return;
435 : 0 : memcpy(copy,str,len+1);
436 : 0 : cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
437 [ # # ]: 0 : if (cvec == NULL) {
438 : 0 : free(copy);
439 : 0 : return;
440 : : }
441 : 0 : lc->cvec = cvec;
442 : 0 : lc->cvec[lc->len++] = copy;
443 : 0 : }
444 : :
445 : : /* =========================== Line editing ================================= */
446 : :
447 : : /* We define a very simple "append buffer" structure, that is an heap
448 : : * allocated string where we can append to. This is useful in order to
449 : : * write all the escape sequences in a buffer and flush them to the standard
450 : : * output in a single call, to avoid flickering effects. */
451 : : struct abuf {
452 : : char *b;
453 : : int len;
454 : : };
455 : :
456 : 0 : static void abInit(struct abuf *ab) {
457 : 0 : ab->b = NULL;
458 : 0 : ab->len = 0;
459 : 0 : }
460 : :
461 : 0 : static void abAppend(struct abuf *ab, const char *s, int len) {
462 : 0 : char *new = realloc(ab->b,ab->len+len);
463 : :
464 [ # # ]: 0 : if (new == NULL) return;
465 : 0 : memcpy(new+ab->len,s,len);
466 : 0 : ab->b = new;
467 : 0 : ab->len += len;
468 : 0 : }
469 : :
470 : 0 : static void abFree(struct abuf *ab) {
471 : 0 : free(ab->b);
472 : 0 : }
473 : :
474 : : /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
475 : : * to the right of the prompt. */
476 : 0 : void refreshShowHints(struct abuf *ab, struct linenoiseState *l, int plen) {
477 : : char seq[64];
478 [ # # # # ]: 0 : if (hintsCallback && plen+l->len < l->cols) {
479 : 0 : int color = -1, bold = 0;
480 : 0 : char *hint = hintsCallback(l->buf,&color,&bold);
481 [ # # ]: 0 : if (hint) {
482 : 0 : int hintlen = strlen(hint);
483 : 0 : int hintmaxlen = l->cols-(plen+l->len);
484 [ # # ]: 0 : if (hintlen > hintmaxlen) hintlen = hintmaxlen;
485 [ # # # # ]: 0 : if (bold == 1 && color == -1) color = 37;
486 [ # # # # ]: 0 : if (color != -1 || bold != 0)
487 : 0 : snprintf(seq,64,"\033[%d;%d;49m",bold,color);
488 : : else
489 : 0 : seq[0] = '\0';
490 : 0 : abAppend(ab,seq,strlen(seq));
491 : 0 : abAppend(ab,hint,hintlen);
492 [ # # # # ]: 0 : if (color != -1 || bold != 0)
493 : 0 : abAppend(ab,"\033[0m",4);
494 : : /* Call the function to free the hint returned. */
495 [ # # ]: 0 : if (freeHintsCallback) freeHintsCallback(hint);
496 : 0 : }
497 : 0 : }
498 : 0 : }
499 : :
500 : : /* Single line low level line refresh.
501 : : *
502 : : * Rewrite the currently edited line accordingly to the buffer content,
503 : : * cursor position, and number of columns of the terminal. */
504 : 0 : static void refreshSingleLine(struct linenoiseState *l) {
505 : : char seq[64];
506 : 0 : size_t plen = strlen(l->prompt);
507 : 0 : int fd = l->ofd;
508 : 0 : char *buf = l->buf;
509 : 0 : size_t len = l->len;
510 : 0 : size_t pos = l->pos;
511 : : struct abuf ab;
512 : :
513 [ # # ]: 0 : while((plen+pos) >= l->cols) {
514 : 0 : buf++;
515 : 0 : len--;
516 : 0 : pos--;
517 : : }
518 [ # # ]: 0 : while (plen+len > l->cols) {
519 : 0 : len--;
520 : : }
521 : :
522 : 0 : abInit(&ab);
523 : : /* Cursor to left edge */
524 : 0 : snprintf(seq,64,"\r");
525 : 0 : abAppend(&ab,seq,strlen(seq));
526 : : /* Write the prompt and the current buffer content */
527 : 0 : abAppend(&ab,l->prompt,strlen(l->prompt));
528 : 0 : abAppend(&ab,buf,len);
529 : : /* Show hits if any. */
530 : 0 : refreshShowHints(&ab,l,plen);
531 : : /* Erase to right */
532 : 0 : snprintf(seq,64,"\x1b[0K");
533 : 0 : abAppend(&ab,seq,strlen(seq));
534 : : /* Move cursor to original position. */
535 : 0 : snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
536 : 0 : abAppend(&ab,seq,strlen(seq));
537 [ # # ]: 0 : if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
538 : 0 : abFree(&ab);
539 : 0 : }
540 : :
541 : : /* Multi line low level line refresh.
542 : : *
543 : : * Rewrite the currently edited line accordingly to the buffer content,
544 : : * cursor position, and number of columns of the terminal. */
545 : 0 : static void refreshMultiLine(struct linenoiseState *l) {
546 : : char seq[64];
547 : 0 : int plen = strlen(l->prompt);
548 : 0 : int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
549 : 0 : int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
550 : : int rpos2; /* rpos after refresh. */
551 : : int col; /* colum position, zero-based. */
552 : 0 : int old_rows = l->maxrows;
553 : 0 : int fd = l->ofd, j;
554 : : struct abuf ab;
555 : :
556 : : /* Update maxrows if needed. */
557 [ # # ]: 0 : if (rows > (int)l->maxrows) l->maxrows = rows;
558 : :
559 : : /* First step: clear all the lines used before. To do so start by
560 : : * going to the last row. */
561 : 0 : abInit(&ab);
562 [ # # ]: 0 : if (old_rows-rpos > 0) {
563 : : lndebug("go down %d", old_rows-rpos);
564 : 0 : snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
565 : 0 : abAppend(&ab,seq,strlen(seq));
566 : 0 : }
567 : :
568 : : /* Now for every row clear it, go up. */
569 [ # # ]: 0 : for (j = 0; j < old_rows-1; j++) {
570 : : lndebug("clear+up");
571 : 0 : snprintf(seq,64,"\r\x1b[0K\x1b[1A");
572 : 0 : abAppend(&ab,seq,strlen(seq));
573 : 0 : }
574 : :
575 : : /* Clean the top line. */
576 : : lndebug("clear");
577 : 0 : snprintf(seq,64,"\r\x1b[0K");
578 : 0 : abAppend(&ab,seq,strlen(seq));
579 : :
580 : : /* Write the prompt and the current buffer content */
581 : 0 : abAppend(&ab,l->prompt,strlen(l->prompt));
582 : 0 : abAppend(&ab,l->buf,l->len);
583 : :
584 : : /* Show hits if any. */
585 : 0 : refreshShowHints(&ab,l,plen);
586 : :
587 : : /* If we are at the very end of the screen with our prompt, we need to
588 : : * emit a newline and move the prompt to the first column. */
589 [ # # # # ]: 0 : if (l->pos &&
590 [ # # ]: 0 : l->pos == l->len &&
591 : 0 : (l->pos+plen) % l->cols == 0)
592 : : {
593 : : lndebug("<newline>");
594 : 0 : abAppend(&ab,"\n",1);
595 : 0 : snprintf(seq,64,"\r");
596 : 0 : abAppend(&ab,seq,strlen(seq));
597 : 0 : rows++;
598 [ # # ]: 0 : if (rows > (int)l->maxrows) l->maxrows = rows;
599 : 0 : }
600 : :
601 : : /* Move cursor to right position. */
602 : 0 : rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
603 : : lndebug("rpos2 %d", rpos2);
604 : :
605 : : /* Go up till we reach the expected positon. */
606 [ # # ]: 0 : if (rows-rpos2 > 0) {
607 : : lndebug("go-up %d", rows-rpos2);
608 : 0 : snprintf(seq,64,"\x1b[%dA", rows-rpos2);
609 : 0 : abAppend(&ab,seq,strlen(seq));
610 : 0 : }
611 : :
612 : : /* Set column. */
613 : 0 : col = (plen+(int)l->pos) % (int)l->cols;
614 : : lndebug("set col %d", 1+col);
615 [ # # ]: 0 : if (col)
616 : 0 : snprintf(seq,64,"\r\x1b[%dC", col);
617 : : else
618 : 0 : snprintf(seq,64,"\r");
619 : 0 : abAppend(&ab,seq,strlen(seq));
620 : :
621 : : lndebug("\n");
622 : 0 : l->oldpos = l->pos;
623 : :
624 [ # # ]: 0 : if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
625 : 0 : abFree(&ab);
626 : 0 : }
627 : :
628 : : /* Calls the two low level functions refreshSingleLine() or
629 : : * refreshMultiLine() according to the selected mode. */
630 : 0 : static void refreshLine(struct linenoiseState *l) {
631 [ # # ]: 0 : if (mlmode)
632 : 0 : refreshMultiLine(l);
633 : : else
634 : 0 : refreshSingleLine(l);
635 : 0 : }
636 : :
637 : : /* Insert the character 'c' at cursor current position.
638 : : *
639 : : * On error writing to the terminal -1 is returned, otherwise 0. */
640 : 0 : int linenoiseEditInsert(struct linenoiseState *l, char c) {
641 [ # # ]: 0 : if (l->len < l->buflen) {
642 [ # # ]: 0 : if (l->len == l->pos) {
643 : 0 : l->buf[l->pos] = c;
644 : 0 : l->pos++;
645 : 0 : l->len++;
646 : 0 : l->buf[l->len] = '\0';
647 [ # # # # : 0 : if ((!mlmode && l->plen+l->len < l->cols && !hintsCallback)) {
# # ]
648 : : /* Avoid a full update of the line in the
649 : : * trivial case. */
650 [ # # ]: 0 : if (write(l->ofd,&c,1) == -1) return -1;
651 : 0 : } else {
652 : 0 : refreshLine(l);
653 : : }
654 : 0 : } else {
655 : 0 : memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
656 : 0 : l->buf[l->pos] = c;
657 : 0 : l->len++;
658 : 0 : l->pos++;
659 : 0 : l->buf[l->len] = '\0';
660 : 0 : refreshLine(l);
661 : : }
662 : 0 : }
663 : 0 : return 0;
664 : 0 : }
665 : :
666 : : /* Move cursor on the left. */
667 : 0 : void linenoiseEditMoveLeft(struct linenoiseState *l) {
668 [ # # ]: 0 : if (l->pos > 0) {
669 : 0 : l->pos--;
670 : 0 : refreshLine(l);
671 : 0 : }
672 : 0 : }
673 : :
674 : : /* Move cursor on the right. */
675 : 0 : void linenoiseEditMoveRight(struct linenoiseState *l) {
676 [ # # ]: 0 : if (l->pos != l->len) {
677 : 0 : l->pos++;
678 : 0 : refreshLine(l);
679 : 0 : }
680 : 0 : }
681 : :
682 : : /* Move cursor to the start of the line. */
683 : 0 : void linenoiseEditMoveHome(struct linenoiseState *l) {
684 [ # # ]: 0 : if (l->pos != 0) {
685 : 0 : l->pos = 0;
686 : 0 : refreshLine(l);
687 : 0 : }
688 : 0 : }
689 : :
690 : : /* Move cursor to the end of the line. */
691 : 0 : void linenoiseEditMoveEnd(struct linenoiseState *l) {
692 [ # # ]: 0 : if (l->pos != l->len) {
693 : 0 : l->pos = l->len;
694 : 0 : refreshLine(l);
695 : 0 : }
696 : 0 : }
697 : :
698 : : /* Substitute the currently edited line with the next or previous history
699 : : * entry as specified by 'dir'. */
700 : : #define LINENOISE_HISTORY_NEXT 0
701 : : #define LINENOISE_HISTORY_PREV 1
702 : 0 : void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
703 [ # # ]: 0 : if (history_len > 1) {
704 : : /* Update the current history entry before to
705 : : * overwrite it with the next one. */
706 : 0 : free(history[history_len - 1 - l->history_index]);
707 : 0 : history[history_len - 1 - l->history_index] = strdup(l->buf);
708 : : /* Show the new entry */
709 : 0 : l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
710 [ # # ]: 0 : if (l->history_index < 0) {
711 : 0 : l->history_index = 0;
712 : 0 : return;
713 [ # # ]: 0 : } else if (l->history_index >= history_len) {
714 : 0 : l->history_index = history_len-1;
715 : 0 : return;
716 : : }
717 : 0 : strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
718 : 0 : l->buf[l->buflen-1] = '\0';
719 : 0 : l->len = l->pos = strlen(l->buf);
720 : 0 : refreshLine(l);
721 : 0 : }
722 : 0 : }
723 : :
724 : : /* Delete the character at the right of the cursor without altering the cursor
725 : : * position. Basically this is what happens with the "Delete" keyboard key. */
726 : 0 : void linenoiseEditDelete(struct linenoiseState *l) {
727 [ # # # # ]: 0 : if (l->len > 0 && l->pos < l->len) {
728 : 0 : memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
729 : 0 : l->len--;
730 : 0 : l->buf[l->len] = '\0';
731 : 0 : refreshLine(l);
732 : 0 : }
733 : 0 : }
734 : :
735 : : /* Backspace implementation. */
736 : 0 : void linenoiseEditBackspace(struct linenoiseState *l) {
737 [ # # # # ]: 0 : if (l->pos > 0 && l->len > 0) {
738 : 0 : memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
739 : 0 : l->pos--;
740 : 0 : l->len--;
741 : 0 : l->buf[l->len] = '\0';
742 : 0 : refreshLine(l);
743 : 0 : }
744 : 0 : }
745 : :
746 : : /* Delete the previosu word, maintaining the cursor at the start of the
747 : : * current word. */
748 : 0 : void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
749 : 0 : size_t old_pos = l->pos;
750 : : size_t diff;
751 : :
752 [ # # # # ]: 0 : while (l->pos > 0 && l->buf[l->pos-1] == ' ')
753 : 0 : l->pos--;
754 [ # # # # ]: 0 : while (l->pos > 0 && l->buf[l->pos-1] != ' ')
755 : 0 : l->pos--;
756 : 0 : diff = old_pos - l->pos;
757 : 0 : memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
758 : 0 : l->len -= diff;
759 : 0 : refreshLine(l);
760 : 0 : }
761 : :
762 : : /* This function is the core of the line editing capability of linenoise.
763 : : * It expects 'fd' to be already in "raw mode" so that every key pressed
764 : : * will be returned ASAP to read().
765 : : *
766 : : * The resulting string is put into 'buf' when the user type enter, or
767 : : * when ctrl+d is typed.
768 : : *
769 : : * The function returns the length of the current buffer. */
770 : 0 : static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt)
771 : : {
772 : : struct linenoiseState l;
773 : :
774 : : /* Populate the linenoise state that we pass to functions implementing
775 : : * specific editing functionalities. */
776 : 0 : l.ifd = stdin_fd;
777 : 0 : l.ofd = stdout_fd;
778 : 0 : l.buf = buf;
779 : 0 : l.buflen = buflen;
780 : 0 : l.prompt = prompt;
781 : 0 : l.plen = strlen(prompt);
782 : 0 : l.oldpos = l.pos = 0;
783 : 0 : l.len = 0;
784 : 0 : l.cols = getColumns(stdin_fd, stdout_fd);
785 : 0 : l.maxrows = 0;
786 : 0 : l.history_index = 0;
787 : :
788 : : /* Buffer starts empty. */
789 : 0 : l.buf[0] = '\0';
790 : 0 : l.buflen--; /* Make sure there is always space for the nulterm */
791 : :
792 : : /* The latest history entry is always our current buffer, that
793 : : * initially is just an empty string. */
794 : 0 : linenoiseHistoryAdd("");
795 : :
796 [ # # ]: 0 : if (write(l.ofd,prompt,l.plen) == -1) return -1;
797 : 0 : while(1) {
798 : : char c;
799 : : int nread;
800 : : char seq[3];
801 : :
802 : 0 : nread = read(l.ifd,&c,1);
803 [ # # ]: 0 : if (nread <= 0) return l.len;
804 : :
805 : : /* Only autocomplete when the callback is set. It returns < 0 when
806 : : * there was an error reading from fd. Otherwise it will return the
807 : : * character that should be handled next. */
808 [ # # # # ]: 0 : if (c == 9 && completionCallback != NULL) {
809 : 0 : int cv = completeLine(&l);
810 : : /* Return on errors */
811 [ # # ]: 0 : if (cv < 0) return l.len;
812 : : /* char may be unsigned */
813 : 0 : c = (char)cv;
814 : : /* Read next character when 0 */
815 [ # # ]: 0 : if (c == 0) continue;
816 : 0 : }
817 : :
818 [ # # # # : 0 : switch(c) {
# # # # #
# # # # #
# # # ]
819 : : case ENTER: /* enter */
820 : 0 : history_len--;
821 : 0 : free(history[history_len]);
822 [ # # ]: 0 : if (mlmode) linenoiseEditMoveEnd(&l);
823 [ # # ]: 0 : if (hintsCallback) {
824 : : /* Force a refresh without hints to leave the previous
825 : : * line as the user typed it after a newline. */
826 : 0 : linenoiseHintsCallback *hc = hintsCallback;
827 : 0 : hintsCallback = NULL;
828 : 0 : refreshLine(&l);
829 : 0 : hintsCallback = hc;
830 : 0 : }
831 : 0 : return (int)l.len;
832 : : case CTRL_C: /* ctrl-c */
833 : 0 : errno = EAGAIN;
834 : 0 : return -1;
835 : : case BACKSPACE: /* backspace */
836 : : case 8: /* ctrl-h */
837 : 0 : linenoiseEditBackspace(&l);
838 : 0 : break;
839 : : case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the
840 : : line is empty, act as end-of-file. */
841 [ # # ]: 0 : if (l.len > 0) {
842 : 0 : linenoiseEditDelete(&l);
843 : 0 : } else {
844 : 0 : history_len--;
845 : 0 : free(history[history_len]);
846 : 0 : return -1;
847 : : }
848 : 0 : break;
849 : : case CTRL_T: /* ctrl-t, swaps current character with previous. */
850 [ # # # # ]: 0 : if (l.pos > 0 && l.pos < l.len) {
851 : 0 : int aux = buf[l.pos-1];
852 : 0 : buf[l.pos-1] = buf[l.pos];
853 : 0 : buf[l.pos] = aux;
854 [ # # ]: 0 : if (l.pos != l.len-1) l.pos++;
855 : 0 : refreshLine(&l);
856 : 0 : }
857 : 0 : break;
858 : : case CTRL_B: /* ctrl-b */
859 : 0 : linenoiseEditMoveLeft(&l);
860 : 0 : break;
861 : : case CTRL_F: /* ctrl-f */
862 : 0 : linenoiseEditMoveRight(&l);
863 : 0 : break;
864 : : case CTRL_P: /* ctrl-p */
865 : 0 : linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
866 : 0 : break;
867 : : case CTRL_N: /* ctrl-n */
868 : 0 : linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
869 : 0 : break;
870 : : case ESC: /* escape sequence */
871 : : /* Read the next two bytes representing the escape sequence.
872 : : * Use two calls to handle slow terminals returning the two
873 : : * chars at different times. */
874 [ # # ]: 0 : if (read(l.ifd,seq,1) == -1) break;
875 [ # # ]: 0 : if (read(l.ifd,seq+1,1) == -1) break;
876 : :
877 : : /* ESC [ sequences. */
878 [ # # ]: 0 : if (seq[0] == '[') {
879 [ # # # # ]: 0 : if (seq[1] >= '0' && seq[1] <= '9') {
880 : : /* Extended escape, read additional byte. */
881 [ # # ]: 0 : if (read(l.ifd,seq+2,1) == -1) break;
882 [ # # ]: 0 : if (seq[2] == '~') {
883 [ # # ]: 0 : switch(seq[1]) {
884 : : case '3': /* Delete key. */
885 : 0 : linenoiseEditDelete(&l);
886 : 0 : break;
887 : : }
888 : 0 : }
889 : 0 : } else {
890 [ # # # # : 0 : switch(seq[1]) {
# # # ]
891 : : case 'A': /* Up */
892 : 0 : linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
893 : 0 : break;
894 : : case 'B': /* Down */
895 : 0 : linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
896 : 0 : break;
897 : : case 'C': /* Right */
898 : 0 : linenoiseEditMoveRight(&l);
899 : 0 : break;
900 : : case 'D': /* Left */
901 : 0 : linenoiseEditMoveLeft(&l);
902 : 0 : break;
903 : : case 'H': /* Home */
904 : 0 : linenoiseEditMoveHome(&l);
905 : 0 : break;
906 : : case 'F': /* End*/
907 : 0 : linenoiseEditMoveEnd(&l);
908 : 0 : break;
909 : : }
910 : : }
911 : 0 : }
912 : :
913 : : /* ESC O sequences. */
914 [ # # ]: 0 : else if (seq[0] == 'O') {
915 [ # # # ]: 0 : switch(seq[1]) {
916 : : case 'H': /* Home */
917 : 0 : linenoiseEditMoveHome(&l);
918 : 0 : break;
919 : : case 'F': /* End*/
920 : 0 : linenoiseEditMoveEnd(&l);
921 : 0 : break;
922 : : }
923 : 0 : }
924 : 0 : break;
925 : : default:
926 [ # # ]: 0 : if (linenoiseEditInsert(&l,c)) return -1;
927 : 0 : break;
928 : : case CTRL_U: /* Ctrl+u, delete the whole line. */
929 : 0 : buf[0] = '\0';
930 : 0 : l.pos = l.len = 0;
931 : 0 : refreshLine(&l);
932 : 0 : break;
933 : : case CTRL_K: /* Ctrl+k, delete from current to end of line. */
934 : 0 : buf[l.pos] = '\0';
935 : 0 : l.len = l.pos;
936 : 0 : refreshLine(&l);
937 : 0 : break;
938 : : case CTRL_A: /* Ctrl+a, go to the start of the line */
939 : 0 : linenoiseEditMoveHome(&l);
940 : 0 : break;
941 : : case CTRL_E: /* ctrl+e, go to the end of the line */
942 : 0 : linenoiseEditMoveEnd(&l);
943 : 0 : break;
944 : : case CTRL_L: /* ctrl+l, clear screen */
945 : 0 : linenoiseClearScreen();
946 : 0 : refreshLine(&l);
947 : 0 : break;
948 : : case CTRL_W: /* ctrl+w, delete previous word */
949 : 0 : linenoiseEditDeletePrevWord(&l);
950 : 0 : break;
951 : : }
952 : : }
953 : : return l.len;
954 : 0 : }
955 : :
956 : : /* This special mode is used by linenoise in order to print scan codes
957 : : * on screen for debugging / development purposes. It is implemented
958 : : * by the linenoise_example program using the --keycodes option. */
959 : 0 : void linenoisePrintKeyCodes(void) {
960 : : char quit[4];
961 : :
962 : 0 : printf("Linenoise key codes debugging mode.\n"
963 : : "Press keys to see scan codes. Type 'quit' at any time to exit.\n");
964 [ # # ]: 0 : if (enableRawMode(STDIN_FILENO) == -1) return;
965 : 0 : memset(quit,' ',4);
966 : 0 : while(1) {
967 : : char c;
968 : : int nread;
969 : :
970 : 0 : nread = read(STDIN_FILENO,&c,1);
971 [ # # ]: 0 : if (nread <= 0) continue;
972 : 0 : memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */
973 : 0 : quit[sizeof(quit)-1] = c; /* Insert current char on the right. */
974 [ # # ]: 0 : if (memcmp(quit,"quit",sizeof(quit)) == 0) break;
975 : :
976 : 0 : printf("'%c' %02x (%d) (type quit to exit)\n",
977 [ # # ]: 0 : isprint(c) ? c : '?', (int)c, (int)c);
978 : 0 : printf("\r"); /* Go left edge manually, we are in raw mode. */
979 : 0 : fflush(stdout);
980 : : }
981 : 0 : disableRawMode(STDIN_FILENO);
982 : 0 : }
983 : :
984 : : /* This function calls the line editing function linenoiseEdit() using
985 : : * the STDIN file descriptor set in raw mode. */
986 : 0 : static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
987 : : int count;
988 : :
989 [ # # ]: 0 : if (buflen == 0) {
990 : 0 : errno = EINVAL;
991 : 0 : return -1;
992 : : }
993 : :
994 [ # # ]: 0 : if (enableRawMode(STDIN_FILENO) == -1) return -1;
995 : 0 : count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt);
996 : 0 : disableRawMode(STDIN_FILENO);
997 : 0 : printf("\n");
998 : 0 : return count;
999 : 0 : }
1000 : :
1001 : : /* This function is called when linenoise() is called with the standard
1002 : : * input file descriptor not attached to a TTY. So for example when the
1003 : : * program using linenoise is called in pipe or with a file redirected
1004 : : * to its standard input. In this case, we want to be able to return the
1005 : : * line regardless of its length (by default we are limited to 4k). */
1006 : 0 : static char *linenoiseNoTTY(void) {
1007 : 0 : char *line = NULL;
1008 : 0 : size_t len = 0, maxlen = 0;
1009 : :
1010 : 0 : while(1) {
1011 [ # # ]: 0 : if (len == maxlen) {
1012 [ # # ]: 0 : if (maxlen == 0) maxlen = 16;
1013 : 0 : maxlen *= 2;
1014 : 0 : char *oldval = line;
1015 : 0 : line = realloc(line,maxlen);
1016 [ # # ]: 0 : if (line == NULL) {
1017 [ # # ]: 0 : if (oldval) free(oldval);
1018 : 0 : return NULL;
1019 : : }
1020 : 0 : }
1021 : 0 : int c = fgetc(stdin);
1022 [ # # # # ]: 0 : if (c == EOF || c == '\n') {
1023 [ # # # # ]: 0 : if (c == EOF && len == 0) {
1024 : 0 : free(line);
1025 : 0 : return NULL;
1026 : : } else {
1027 : 0 : line[len] = '\0';
1028 : 0 : return line;
1029 : : }
1030 : : } else {
1031 : 0 : line[len] = c;
1032 : 0 : len++;
1033 : : }
1034 : : }
1035 : 0 : }
1036 : :
1037 : : /* The high level function that is the main API of the linenoise library.
1038 : : * This function checks if the terminal has basic capabilities, just checking
1039 : : * for a blacklist of stupid terminals, and later either calls the line
1040 : : * editing function or uses dummy fgets() so that you will be able to type
1041 : : * something even in the most desperate of the conditions. */
1042 : 0 : char *linenoise(const char *prompt) {
1043 : : char buf[LINENOISE_MAX_LINE];
1044 : : int count;
1045 : :
1046 [ # # ]: 0 : if (!isatty(STDIN_FILENO)) {
1047 : : /* Not a tty: read from file / pipe. In this mode we don't want any
1048 : : * limit to the line size, so we call a function to handle that. */
1049 : 0 : return linenoiseNoTTY();
1050 [ # # ]: 0 : } else if (isUnsupportedTerm()) {
1051 : : size_t len;
1052 : :
1053 : 0 : printf("%s",prompt);
1054 : 0 : fflush(stdout);
1055 [ # # ]: 0 : if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
1056 : 0 : len = strlen(buf);
1057 [ # # # # : 0 : while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
# # ]
1058 : 0 : len--;
1059 : 0 : buf[len] = '\0';
1060 : : }
1061 : 0 : return strdup(buf);
1062 : : } else {
1063 : 0 : count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
1064 [ # # ]: 0 : if (count == -1) return NULL;
1065 : 0 : return strdup(buf);
1066 : : }
1067 : 0 : }
1068 : :
1069 : : /* This is just a wrapper the user may want to call in order to make sure
1070 : : * the linenoise returned buffer is freed with the same allocator it was
1071 : : * created with. Useful when the main program is using an alternative
1072 : : * allocator. */
1073 : 0 : void linenoiseFree(void *ptr) {
1074 : 0 : free(ptr);
1075 : 0 : }
1076 : :
1077 : : /* ================================ History ================================= */
1078 : :
1079 : : /* Free the history, but does not reset it. Only used when we have to
1080 : : * exit() to avoid memory leaks are reported by valgrind & co. */
1081 : 0 : static void freeHistory(void) {
1082 [ # # ]: 0 : if (history) {
1083 : : int j;
1084 : :
1085 [ # # ]: 0 : for (j = 0; j < history_len; j++)
1086 : 0 : free(history[j]);
1087 : 0 : free(history);
1088 : 0 : }
1089 : 0 : }
1090 : :
1091 : : /* At exit we'll try to fix the terminal to the initial conditions. */
1092 : 0 : static void linenoiseAtExit(void) {
1093 : 0 : disableRawMode(STDIN_FILENO);
1094 : 0 : freeHistory();
1095 : 0 : }
1096 : :
1097 : : /* This is the API call to add a new entry in the linenoise history.
1098 : : * It uses a fixed array of char pointers that are shifted (memmoved)
1099 : : * when the history max length is reached in order to remove the older
1100 : : * entry and make room for the new one, so it is not exactly suitable for huge
1101 : : * histories, but will work well for a few hundred of entries.
1102 : : *
1103 : : * Using a circular buffer is smarter, but a bit more complex to handle. */
1104 : 0 : int linenoiseHistoryAdd(const char *line) {
1105 : : char *linecopy;
1106 : :
1107 [ # # ]: 0 : if (history_max_len == 0) return 0;
1108 : :
1109 : : /* Initialization on first call. */
1110 [ # # ]: 0 : if (history == NULL) {
1111 : 0 : history = malloc(sizeof(char*)*history_max_len);
1112 [ # # ]: 0 : if (history == NULL) return 0;
1113 : 0 : memset(history,0,(sizeof(char*)*history_max_len));
1114 : 0 : }
1115 : :
1116 : : /* Don't add duplicated lines. */
1117 [ # # # # ]: 0 : if (history_len && !strcmp(history[history_len-1], line)) return 0;
1118 : :
1119 : : /* Add an heap allocated copy of the line in the history.
1120 : : * If we reached the max length, remove the older line. */
1121 : 0 : linecopy = strdup(line);
1122 [ # # ]: 0 : if (!linecopy) return 0;
1123 [ # # ]: 0 : if (history_len == history_max_len) {
1124 : 0 : free(history[0]);
1125 : 0 : memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1126 : 0 : history_len--;
1127 : 0 : }
1128 : 0 : history[history_len] = linecopy;
1129 : 0 : history_len++;
1130 : 0 : return 1;
1131 : 0 : }
1132 : :
1133 : : /* Set the maximum length for the history. This function can be called even
1134 : : * if there is already some history, the function will make sure to retain
1135 : : * just the latest 'len' elements if the new history length value is smaller
1136 : : * than the amount of items already inside the history. */
1137 : 0 : int linenoiseHistorySetMaxLen(int len) {
1138 : : char **new;
1139 : :
1140 [ # # ]: 0 : if (len < 1) return 0;
1141 [ # # ]: 0 : if (history) {
1142 : 0 : int tocopy = history_len;
1143 : :
1144 : 0 : new = malloc(sizeof(char*)*len);
1145 [ # # ]: 0 : if (new == NULL) return 0;
1146 : :
1147 : : /* If we can't copy everything, free the elements we'll not use. */
1148 [ # # ]: 0 : if (len < tocopy) {
1149 : : int j;
1150 : :
1151 [ # # ]: 0 : for (j = 0; j < tocopy-len; j++) free(history[j]);
1152 : 0 : tocopy = len;
1153 : 0 : }
1154 : 0 : memset(new,0,sizeof(char*)*len);
1155 : 0 : memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
1156 : 0 : free(history);
1157 : 0 : history = new;
1158 : 0 : }
1159 : 0 : history_max_len = len;
1160 [ # # ]: 0 : if (history_len > history_max_len)
1161 : 0 : history_len = history_max_len;
1162 : 0 : return 1;
1163 : 0 : }
1164 : :
1165 : : /* Save the history in the specified file. On success 0 is returned
1166 : : * otherwise -1 is returned. */
1167 : 0 : int linenoiseHistorySave(const char *filename) {
1168 : 0 : mode_t old_umask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
1169 : : FILE *fp;
1170 : : int j;
1171 : :
1172 : 0 : fp = fopen(filename,"w");
1173 : 0 : umask(old_umask);
1174 [ # # ]: 0 : if (fp == NULL) return -1;
1175 : 0 : chmod(filename,S_IRUSR|S_IWUSR);
1176 [ # # ]: 0 : for (j = 0; j < history_len; j++)
1177 : 0 : fprintf(fp,"%s\n",history[j]);
1178 : 0 : fclose(fp);
1179 : 0 : return 0;
1180 : 0 : }
1181 : :
1182 : : /* Load the history from the specified file. If the file does not exist
1183 : : * zero is returned and no operation is performed.
1184 : : *
1185 : : * If the file exists and the operation succeeded 0 is returned, otherwise
1186 : : * on error -1 is returned. */
1187 : 0 : int linenoiseHistoryLoad(const char *filename) {
1188 : 0 : FILE *fp = fopen(filename,"r");
1189 : : char buf[LINENOISE_MAX_LINE];
1190 : :
1191 [ # # ]: 0 : if (fp == NULL) return -1;
1192 : :
1193 [ # # ]: 0 : while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1194 : : char *p;
1195 : :
1196 : 0 : p = strchr(buf,'\r');
1197 [ # # ]: 0 : if (!p) p = strchr(buf,'\n');
1198 [ # # ]: 0 : if (p) *p = '\0';
1199 : 0 : linenoiseHistoryAdd(buf);
1200 : : }
1201 : 0 : fclose(fp);
1202 : 0 : return 0;
1203 : 0 : }
|