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