embox

Форк
0
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

121
static char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
122
static linenoiseCompletionCallback *completionCallback = NULL;
123
static linenoiseHintsCallback *hintsCallback = NULL;
124
static 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
#else
138
static struct termios orig_termios; /* In order to restore at exit.*/
139
static int maskmode = 0; /* Show "***" instead of input. For passwords. */
140
static int rawmode = 0; /* For atexit() function to check if restore is needed*/
141
static int mlmode = 0;  /* Multi line mode. Default is single line. */
142
static int atexit_registered = 0; /* Register atexit just 1 time. */
143
static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
144
static int history_len = 0;
145
static 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. */
151
struct linenoiseState {
152
    int ifd;            /* Terminal stdin file descriptor. */
153
    int ofd;            /* Terminal stdout file descriptor. */
154
    char *buf;          /* Edited line buffer. */
155
    size_t buflen;      /* Edited line buffer size. */
156
    const char *prompt; /* Prompt to display. */
157
    size_t plen;        /* Prompt length. */
158
    size_t pos;         /* Current cursor position. */
159
    size_t oldpos;      /* Previous refresh cursor position. */
160
    size_t len;         /* Current edited line length. */
161
    size_t cols;        /* Number of columns in terminal. */
162
    size_t maxrows;     /* Maximum num of rows used so far (multiline mode) */
163
    int history_index;  /* The history index we are currently editing. */
164
};
165

166
enum KEY_ACTION{
167
	KEY_NULL = 0,	    /* NULL */
168
	CTRL_A = 1,         /* Ctrl+a */
169
	CTRL_B = 2,         /* Ctrl-b */
170
	CTRL_C = 3,         /* Ctrl-c */
171
	CTRL_D = 4,         /* Ctrl-d */
172
	CTRL_E = 5,         /* Ctrl-e */
173
	CTRL_F = 6,         /* Ctrl-f */
174
	CTRL_H = 8,         /* Ctrl-h */
175
	TAB = 9,            /* Tab */
176
	CTRL_K = 11,        /* Ctrl+k */
177
	CTRL_L = 12,        /* Ctrl+l */
178
	ENTER = 13,         /* Enter */
179
	CTRL_N = 14,        /* Ctrl-n */
180
	CTRL_P = 16,        /* Ctrl-p */
181
	CTRL_T = 20,        /* Ctrl-t */
182
	CTRL_U = 21,        /* Ctrl+u */
183
	CTRL_W = 23,        /* Ctrl+w */
184
	ESC = 27,           /* Escape */
185
	BACKSPACE =  127    /* Backspace */
186
};
187

188
#ifndef __EMBOX__
189
static void linenoiseAtExit(void);
190
#endif
191
int linenoiseHistoryAdd(const char *line);
192
static void refreshLine(struct linenoiseState *l);
193

194
/* Debugging macro. */
195
#if 0
196
FILE *lndebug_fp = NULL;
197
#define lndebug(...) \
198
    do { \
199
        if (lndebug_fp == NULL) { \
200
            lndebug_fp = fopen("/tmp/lndebug.txt","a"); \
201
            fprintf(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
        } \
206
        fprintf(lndebug_fp, ", " __VA_ARGS__); \
207
        fflush(lndebug_fp); \
208
    } while (0)
209
#else
210
#define lndebug(fmt, ...)
211
#endif
212

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. */
219
void linenoiseMaskModeEnable(void) {
220
    maskmode = 1;
221
}
222

223
/* Disable mask mode. */
224
void linenoiseMaskModeDisable(void) {
225
    maskmode = 0;
226
}
227

228
/* Set if to use or not the multi line mode. */
229
void linenoiseSetMultiLine(int ml) {
230
    mlmode = 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. */
235
static int isUnsupportedTerm(void) {
236
    char *term = getenv("TERM");
237
    int j;
238

239
    if (term == NULL) return 0;
240
    for (j = 0; unsupported_term[j]; j++)
241
        if (!strcasecmp(term,unsupported_term[j])) return 1;
242
    return 0;
243
}
244

245
/* Raw mode: 1960 magic shit. */
246
static int enableRawMode(int fd) {
247
    struct termios raw;
248

249
    if (!isatty(STDIN_FILENO)) goto fatal;
250
    if (!atexit_registered) {
251
#ifndef __EMBOX__
252
        atexit(linenoiseAtExit);
253
#endif
254
        atexit_registered = 1;
255
    }
256
    if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
257

258
    raw = 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. */
261
    raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
262
    /* output modes - disable post processing */
263
    raw.c_oflag &= ~(OPOST);
264
    /* control modes - set 8 bit chars */
265
    raw.c_cflag |= (CS8);
266
    /* local modes - choing off, canonical off, no extended functions,
267
     * no signal chars (^Z,^C) */
268
    raw.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. */
271
    raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
272

273
    /* put terminal in raw mode after flushing */
274
    if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
275
    rawmode = 1;
276
    return 0;
277

278
fatal:
279
    errno = ENOTTY;
280
    return -1;
281
}
282

283
static void disableRawMode(int fd) {
284
    /* Don't even check the return value as it's too late. */
285
    if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
286
        rawmode = 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. */
292
static int getCursorPosition(int ifd, int ofd) {
293
    char buf[32];
294
    int cols, rows;
295
    unsigned int i = 0;
296

297
    /* Report cursor location */
298
    if (write(ofd, "\x1b[6n", 4) != 4) return -1;
299

300
    /* Read the response: ESC [ rows ; cols R */
301
    while (i < sizeof(buf)-1) {
302
        if (read(ifd,buf+i,1) != 1) break;
303
        if (buf[i] == 'R') break;
304
        i++;
305
    }
306
    buf[i] = '\0';
307

308
    /* Parse it. */
309
    if (buf[0] != ESC || buf[1] != '[') return -1;
310
    if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
311
    return cols;
312
}
313
#endif
314

315
/* Try to get the number of columns in the current terminal, or assume 80
316
 * if it fails. */
317
static int getColumns(int ifd, int ofd) {
318
#ifndef __EMBOX__
319
    struct winsize ws;
320

321
    if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
322
        /* ioctl() failed. Try to query the terminal itself. */
323
        int start, cols;
324

325
        /* Get the initial position so we can restore it later. */
326
        start = getCursorPosition(ifd,ofd);
327
        if (start == -1) goto failed;
328

329
        /* Go to right margin and get position. */
330
        if (write(ofd,"\x1b[999C",6) != 6) goto failed;
331
        cols = getCursorPosition(ifd,ofd);
332
        if (cols == -1) goto failed;
333

334
        /* Restore position. */
335
        if (cols > start) {
336
            char seq[32];
337
            snprintf(seq,32,"\x1b[%dD",cols-start);
338
            if (write(ofd,seq,strlen(seq)) == -1) {
339
                /* Can't recover... */
340
            }
341
        }
342
        return cols;
343
    } else {
344
        return ws.ws_col;
345
    }
346

347
failed:
348
#endif
349
    return 80;
350
}
351

352
/* Clear the screen. Used to handle ctrl+l */
353
void linenoiseClearScreen(void) {
354
    if (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. */
361
static void linenoiseBeep(void) {
362
    fprintf(stderr, "\x7");
363
    fflush(stderr);
364
}
365

366
/* ============================== Completion ================================ */
367

368
/* Free a list of completion option populated by linenoiseAddCompletion(). */
369
static void freeCompletions(linenoiseCompletions *lc) {
370
    size_t i;
371
    for (i = 0; i < lc->len; i++)
372
        free(lc->cvec[i]);
373
    if (lc->cvec != NULL)
374
        free(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. */
383
static int completeLine(struct linenoiseState *ls) {
384
    linenoiseCompletions lc = { 0, NULL };
385
    int nread, nwritten;
386
    char c = 0;
387

388
    completionCallback(ls->buf,&lc);
389
    if (lc.len == 0) {
390
        linenoiseBeep();
391
    } else {
392
        size_t stop = 0, i = 0;
393

394
        while(!stop) {
395
            /* Show completion or original buffer */
396
            if (i < lc.len) {
397
                struct linenoiseState saved = *ls;
398

399
                ls->len = ls->pos = strlen(lc.cvec[i]);
400
                ls->buf = lc.cvec[i];
401
                refreshLine(ls);
402
                ls->len = saved.len;
403
                ls->pos = saved.pos;
404
                ls->buf = saved.buf;
405
            } else {
406
                refreshLine(ls);
407
            }
408

409
            nread = read(ls->ifd,&c,1);
410
            if (nread <= 0) {
411
                freeCompletions(&lc);
412
                return -1;
413
            }
414

415
            switch(c) {
416
                case 9: /* tab */
417
                    i = (i+1) % (lc.len+1);
418
                    if (i == lc.len) linenoiseBeep();
419
                    break;
420
                case 27: /* escape */
421
                    /* Re-show original buffer */
422
                    if (i < lc.len) refreshLine(ls);
423
                    stop = 1;
424
                    break;
425
                default:
426
                    /* Update buffer and return */
427
                    if (i < lc.len) {
428
                        nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
429
                        ls->len = ls->pos = nwritten;
430
                    }
431
                    stop = 1;
432
                    break;
433
            }
434
        }
435
    }
436

437
    freeCompletions(&lc);
438
    return c; /* Return last read character */
439
}
440

441
/* Register a callback function to be called for tab-completion. */
442
void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
443
    completionCallback = fn;
444
}
445

446
/* Register a hits function to be called to show hits to the user at the
447
 * right of the prompt. */
448
void linenoiseSetHintsCallback(linenoiseHintsCallback *fn) {
449
    hintsCallback = fn;
450
}
451

452
/* Register a function to free the hints returned by the hints callback
453
 * registered with linenoiseSetHintsCallback(). */
454
void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *fn) {
455
    freeHintsCallback = 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. */
462
void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
463
    size_t len = strlen(str);
464
    char *copy, **cvec;
465

466
    copy = malloc(len+1);
467
    if (copy == NULL) return;
468
    memcpy(copy,str,len+1);
469
    cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
470
    if (cvec == NULL) {
471
        free(copy);
472
        return;
473
    }
474
    lc->cvec = cvec;
475
    lc->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. */
484
struct abuf {
485
    char *b;
486
    int len;
487
};
488

489
static void abInit(struct abuf *ab) {
490
    ab->b = NULL;
491
    ab->len = 0;
492
}
493

494
static void abAppend(struct abuf *ab, const char *s, int len) {
495
    char *new = realloc(ab->b,ab->len+len);
496

497
    if (new == NULL) return;
498
    memcpy(new+ab->len,s,len);
499
    ab->b = new;
500
    ab->len += len;
501
}
502

503
static void abFree(struct abuf *ab) {
504
    free(ab->b);
505
}
506

507
/* Helper of refreshSingleLine() and refreshMultiLine() to show hints
508
 * to the right of the prompt. */
509
void refreshShowHints(struct abuf *ab, struct linenoiseState *l, int plen) {
510
    char seq[64];
511
    if (hintsCallback && plen+l->len < l->cols) {
512
        int color = -1, bold = 0;
513
        char *hint = hintsCallback(l->buf,&color,&bold);
514
        if (hint) {
515
            int hintlen = strlen(hint);
516
            int hintmaxlen = l->cols-(plen+l->len);
517
            if (hintlen > hintmaxlen) hintlen = hintmaxlen;
518
            if (bold == 1 && color == -1) color = 37;
519
            if (color != -1 || bold != 0)
520
                snprintf(seq,64,"\033[%d;%d;49m",bold,color);
521
            else
522
                seq[0] = '\0';
523
            abAppend(ab,seq,strlen(seq));
524
            abAppend(ab,hint,hintlen);
525
            if (color != -1 || bold != 0)
526
                abAppend(ab,"\033[0m",4);
527
            /* Call the function to free the hint returned. */
528
            if (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. */
537
static void refreshSingleLine(struct linenoiseState *l) {
538
    char seq[64];
539
    size_t plen = strlen(l->prompt);
540
    int fd = l->ofd;
541
    char *buf = l->buf;
542
    size_t len = l->len;
543
    size_t pos = l->pos;
544
    struct abuf ab;
545

546
    while((plen+pos) >= l->cols) {
547
        buf++;
548
        len--;
549
        pos--;
550
    }
551
    while (plen+len > l->cols) {
552
        len--;
553
    }
554

555
    abInit(&ab);
556
    /* Cursor to left edge */
557
    snprintf(seq,64,"\r");
558
    abAppend(&ab,seq,strlen(seq));
559
    /* Write the prompt and the current buffer content */
560
    abAppend(&ab,l->prompt,strlen(l->prompt));
561
    if (maskmode == 1) {
562
        while (len--) abAppend(&ab,"*",1);
563
    } else {
564
        abAppend(&ab,buf,len);
565
    }
566
    /* Show hits if any. */
567
    refreshShowHints(&ab,l,plen);
568
    /* Erase to right */
569
    snprintf(seq,64,"\x1b[0K");
570
    abAppend(&ab,seq,strlen(seq));
571
    /* Move cursor to original position. */
572
    snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
573
    abAppend(&ab,seq,strlen(seq));
574
    if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
575
    abFree(&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. */
582
static void refreshMultiLine(struct linenoiseState *l) {
583
    char seq[64];
584
    int plen = strlen(l->prompt);
585
    int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
586
    int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
587
    int rpos2; /* rpos after refresh. */
588
    int col; /* colum position, zero-based. */
589
    int old_rows = l->maxrows;
590
    int fd = l->ofd, j;
591
    struct abuf ab;
592

593
    /* Update maxrows if needed. */
594
    if (rows > (int)l->maxrows) l->maxrows = rows;
595

596
    /* First step: clear all the lines used before. To do so start by
597
     * going to the last row. */
598
    abInit(&ab);
599
    if (old_rows-rpos > 0) {
600
        lndebug("go down %d", old_rows-rpos);
601
        snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
602
        abAppend(&ab,seq,strlen(seq));
603
    }
604

605
    /* Now for every row clear it, go up. */
606
    for (j = 0; j < old_rows-1; j++) {
607
        lndebug("clear+up");
608
        snprintf(seq,64,"\r\x1b[0K\x1b[1A");
609
        abAppend(&ab,seq,strlen(seq));
610
    }
611

612
    /* Clean the top line. */
613
    lndebug("clear");
614
    snprintf(seq,64,"\r\x1b[0K");
615
    abAppend(&ab,seq,strlen(seq));
616

617
    /* Write the prompt and the current buffer content */
618
    abAppend(&ab,l->prompt,strlen(l->prompt));
619
    if (maskmode == 1) {
620
        unsigned int i;
621
        for (i = 0; i < l->len; i++) abAppend(&ab,"*",1);
622
    } else {
623
        abAppend(&ab,l->buf,l->len);
624
    }
625

626
    /* Show hits if any. */
627
    refreshShowHints(&ab,l,plen);
628

629
    /* If we are at the very end of the screen with our prompt, we need to
630
     * emit a newline and move the prompt to the first column. */
631
    if (l->pos &&
632
        l->pos == l->len &&
633
        (l->pos+plen) % l->cols == 0)
634
    {
635
        lndebug("<newline>");
636
        abAppend(&ab,"\n",1);
637
        snprintf(seq,64,"\r");
638
        abAppend(&ab,seq,strlen(seq));
639
        rows++;
640
        if (rows > (int)l->maxrows) l->maxrows = rows;
641
    }
642

643
    /* Move cursor to right position. */
644
    rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
645
    lndebug("rpos2 %d", rpos2);
646

647
    /* Go up till we reach the expected positon. */
648
    if (rows-rpos2 > 0) {
649
        lndebug("go-up %d", rows-rpos2);
650
        snprintf(seq,64,"\x1b[%dA", rows-rpos2);
651
        abAppend(&ab,seq,strlen(seq));
652
    }
653

654
    /* Set column. */
655
    col = (plen+(int)l->pos) % (int)l->cols;
656
    lndebug("set col %d", 1+col);
657
    if (col)
658
        snprintf(seq,64,"\r\x1b[%dC", col);
659
    else
660
        snprintf(seq,64,"\r");
661
    abAppend(&ab,seq,strlen(seq));
662

663
    lndebug("\n");
664
    l->oldpos = l->pos;
665

666
    if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
667
    abFree(&ab);
668
}
669

670
/* Calls the two low level functions refreshSingleLine() or
671
 * refreshMultiLine() according to the selected mode. */
672
static void refreshLine(struct linenoiseState *l) {
673
    if (mlmode)
674
        refreshMultiLine(l);
675
    else
676
        refreshSingleLine(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. */
682
int linenoiseEditInsert(struct linenoiseState *l, char c) {
683
    if (l->len < l->buflen) {
684
        if (l->len == l->pos) {
685
            l->buf[l->pos] = c;
686
            l->pos++;
687
            l->len++;
688
            l->buf[l->len] = '\0';
689
            if ((!mlmode && l->plen+l->len < l->cols && !hintsCallback)) {
690
                /* Avoid a full update of the line in the
691
                 * trivial case. */
692
                char d = (maskmode==1) ? '*' : c;
693
                if (write(l->ofd,&d,1) == -1) return -1;
694
            } else {
695
                refreshLine(l);
696
            }
697
        } else {
698
            memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
699
            l->buf[l->pos] = c;
700
            l->len++;
701
            l->pos++;
702
            l->buf[l->len] = '\0';
703
            refreshLine(l);
704
        }
705
    }
706
    return 0;
707
}
708

709
/* Move cursor on the left. */
710
void linenoiseEditMoveLeft(struct linenoiseState *l) {
711
    if (l->pos > 0) {
712
        l->pos--;
713
        refreshLine(l);
714
    }
715
}
716

717
/* Move cursor on the right. */
718
void linenoiseEditMoveRight(struct linenoiseState *l) {
719
    if (l->pos != l->len) {
720
        l->pos++;
721
        refreshLine(l);
722
    }
723
}
724

725
/* Move cursor to the start of the line. */
726
void linenoiseEditMoveHome(struct linenoiseState *l) {
727
    if (l->pos != 0) {
728
        l->pos = 0;
729
        refreshLine(l);
730
    }
731
}
732

733
/* Move cursor to the end of the line. */
734
void linenoiseEditMoveEnd(struct linenoiseState *l) {
735
    if (l->pos != l->len) {
736
        l->pos = l->len;
737
        refreshLine(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 0
744
#define LINENOISE_HISTORY_PREV 1
745
void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
746
    if (history_len > 1) {
747
        /* Update the current history entry before to
748
         * overwrite it with the next one. */
749
        free(history[history_len - 1 - l->history_index]);
750
        history[history_len - 1 - l->history_index] = strdup(l->buf);
751
        /* Show the new entry */
752
        l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
753
        if (l->history_index < 0) {
754
            l->history_index = 0;
755
            return;
756
        } else if (l->history_index >= history_len) {
757
            l->history_index = history_len-1;
758
            return;
759
        }
760
        strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
761
        l->buf[l->buflen-1] = '\0';
762
        l->len = l->pos = strlen(l->buf);
763
        refreshLine(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. */
769
void linenoiseEditDelete(struct linenoiseState *l) {
770
    if (l->len > 0 && l->pos < l->len) {
771
        memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
772
        l->len--;
773
        l->buf[l->len] = '\0';
774
        refreshLine(l);
775
    }
776
}
777

778
/* Backspace implementation. */
779
void linenoiseEditBackspace(struct linenoiseState *l) {
780
    if (l->pos > 0 && l->len > 0) {
781
        memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
782
        l->pos--;
783
        l->len--;
784
        l->buf[l->len] = '\0';
785
        refreshLine(l);
786
    }
787
}
788

789
/* Delete the previosu word, maintaining the cursor at the start of the
790
 * current word. */
791
void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
792
    size_t old_pos = l->pos;
793
    size_t diff;
794

795
    while (l->pos > 0 && l->buf[l->pos-1] == ' ')
796
        l->pos--;
797
    while (l->pos > 0 && l->buf[l->pos-1] != ' ')
798
        l->pos--;
799
    diff = old_pos - l->pos;
800
    memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
801
    l->len -= diff;
802
    refreshLine(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. */
813
static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt)
814
{
815
    struct linenoiseState l;
816

817
    /* Populate the linenoise state that we pass to functions implementing
818
     * specific editing functionalities. */
819
    l.ifd = stdin_fd;
820
    l.ofd = stdout_fd;
821
    l.buf = buf;
822
    l.buflen = buflen;
823
    l.prompt = prompt;
824
    l.plen = strlen(prompt);
825
    l.oldpos = l.pos = 0;
826
    l.len = 0;
827
    l.cols = getColumns(stdin_fd, stdout_fd);
828
    l.maxrows = 0;
829
    l.history_index = 0;
830

831
    /* Buffer starts empty. */
832
    l.buf[0] = '\0';
833
    l.buflen--; /* Make sure there is always space for the nulterm */
834

835
    /* The latest history entry is always our current buffer, that
836
     * initially is just an empty string. */
837
    linenoiseHistoryAdd("");
838

839
    if (write(l.ofd,prompt,l.plen) == -1) return -1;
840
    while(1) {
841
        char c;
842
        int nread;
843
        char seq[3];
844

845
        nread = read(l.ifd,&c,1);
846
        if (nread <= 0) return l.len;
847

848
        /* Only autocomplete when the callback is set. It returns < 0 when
849
         * there was an error reading from fd. Otherwise it will return the
850
         * character that should be handled next. */
851
        if (c == 9 && completionCallback != NULL) {
852
            c = completeLine(&l);
853
            /* Return on errors */
854
            if (c < 0) return l.len;
855
            /* Read next character when 0 */
856
            if (c == 0) continue;
857
        }
858

859
        switch(c) {
860
        case ENTER:    /* enter */
861
            history_len--;
862
            free(history[history_len]);
863
            if (mlmode) linenoiseEditMoveEnd(&l);
864
            if (hintsCallback) {
865
                /* Force a refresh without hints to leave the previous
866
                 * line as the user typed it after a newline. */
867
                linenoiseHintsCallback *hc = hintsCallback;
868
                hintsCallback = NULL;
869
                refreshLine(&l);
870
                hintsCallback = hc;
871
            }
872
            return (int)l.len;
873
        case CTRL_C:     /* ctrl-c */
874
            errno = EAGAIN;
875
            return -1;
876
        case BACKSPACE:   /* backspace */
877
        case 8:     /* ctrl-h */
878
            linenoiseEditBackspace(&l);
879
            break;
880
        case CTRL_D:     /* ctrl-d, remove char at right of cursor, or if the
881
                            line is empty, act as end-of-file. */
882
            if (l.len > 0) {
883
                linenoiseEditDelete(&l);
884
            } else {
885
                history_len--;
886
                free(history[history_len]);
887
                return -1;
888
            }
889
            break;
890
        case CTRL_T:    /* ctrl-t, swaps current character with previous. */
891
            if (l.pos > 0 && l.pos < l.len) {
892
                int aux = buf[l.pos-1];
893
                buf[l.pos-1] = buf[l.pos];
894
                buf[l.pos] = aux;
895
                if (l.pos != l.len-1) l.pos++;
896
                refreshLine(&l);
897
            }
898
            break;
899
        case CTRL_B:     /* ctrl-b */
900
            linenoiseEditMoveLeft(&l);
901
            break;
902
        case CTRL_F:     /* ctrl-f */
903
            linenoiseEditMoveRight(&l);
904
            break;
905
        case CTRL_P:    /* ctrl-p */
906
            linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
907
            break;
908
        case CTRL_N:    /* ctrl-n */
909
            linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
910
            break;
911
        case 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. */
915
            if (read(l.ifd,seq,1) == -1) break;
916
            if (read(l.ifd,seq+1,1) == -1) break;
917

918
            /* ESC [ sequences. */
919
            if (seq[0] == '[') {
920
                if (seq[1] >= '0' && seq[1] <= '9') {
921
                    /* Extended escape, read additional byte. */
922
                    if (read(l.ifd,seq+2,1) == -1) break;
923
                    if (seq[2] == '~') {
924
                        switch(seq[1]) {
925
                        case '3': /* Delete key. */
926
                            linenoiseEditDelete(&l);
927
                            break;
928
                        }
929
                    }
930
                } else {
931
                    switch(seq[1]) {
932
                    case 'A': /* Up */
933
                        linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
934
                        break;
935
                    case 'B': /* Down */
936
                        linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
937
                        break;
938
                    case 'C': /* Right */
939
                        linenoiseEditMoveRight(&l);
940
                        break;
941
                    case 'D': /* Left */
942
                        linenoiseEditMoveLeft(&l);
943
                        break;
944
                    case 'H': /* Home */
945
                        linenoiseEditMoveHome(&l);
946
                        break;
947
                    case 'F': /* End*/
948
                        linenoiseEditMoveEnd(&l);
949
                        break;
950
                    }
951
                }
952
            }
953

954
            /* ESC O sequences. */
955
            else if (seq[0] == 'O') {
956
                switch(seq[1]) {
957
                case 'H': /* Home */
958
                    linenoiseEditMoveHome(&l);
959
                    break;
960
                case 'F': /* End*/
961
                    linenoiseEditMoveEnd(&l);
962
                    break;
963
                }
964
            }
965
            break;
966
        default:
967
            if (linenoiseEditInsert(&l,c)) return -1;
968
            break;
969
        case CTRL_U: /* Ctrl+u, delete the whole line. */
970
            buf[0] = '\0';
971
            l.pos = l.len = 0;
972
            refreshLine(&l);
973
            break;
974
        case CTRL_K: /* Ctrl+k, delete from current to end of line. */
975
            buf[l.pos] = '\0';
976
            l.len = l.pos;
977
            refreshLine(&l);
978
            break;
979
        case CTRL_A: /* Ctrl+a, go to the start of the line */
980
            linenoiseEditMoveHome(&l);
981
            break;
982
        case CTRL_E: /* ctrl+e, go to the end of the line */
983
            linenoiseEditMoveEnd(&l);
984
            break;
985
        case CTRL_L: /* ctrl+l, clear screen */
986
            linenoiseClearScreen();
987
            refreshLine(&l);
988
            break;
989
        case CTRL_W: /* ctrl+w, delete previous word */
990
            linenoiseEditDeletePrevWord(&l);
991
            break;
992
        }
993
    }
994
    return 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. */
1000
void linenoisePrintKeyCodes(void) {
1001
    char quit[4];
1002

1003
    printf("Linenoise key codes debugging mode.\n"
1004
            "Press keys to see scan codes. Type 'quit' at any time to exit.\n");
1005
    if (enableRawMode(STDIN_FILENO) == -1) return;
1006
    memset(quit,' ',4);
1007
    while(1) {
1008
        char c;
1009
        int nread;
1010

1011
        nread = read(STDIN_FILENO,&c,1);
1012
        if (nread <= 0) continue;
1013
        memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */
1014
        quit[sizeof(quit)-1] = c; /* Insert current char on the right. */
1015
        if (memcmp(quit,"quit",sizeof(quit)) == 0) break;
1016

1017
        printf("'%c' %02x (%d) (type quit to exit)\n",
1018
            isprint(c) ? c : '?', (int)c, (int)c);
1019
        printf("\r"); /* Go left edge manually, we are in raw mode. */
1020
        fflush(stdout);
1021
    }
1022
    disableRawMode(STDIN_FILENO);
1023
}
1024

1025
/* This function calls the line editing function linenoiseEdit() using
1026
 * the STDIN file descriptor set in raw mode. */
1027
static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
1028
    int count;
1029

1030
    if (buflen == 0) {
1031
        errno = EINVAL;
1032
        return -1;
1033
    }
1034

1035
    if (enableRawMode(STDIN_FILENO) == -1) return -1;
1036
    count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt);
1037
    disableRawMode(STDIN_FILENO);
1038
    printf("\n");
1039
    return 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). */
1047
static char *linenoiseNoTTY(void) {
1048
    char *line = NULL;
1049
    size_t len = 0, maxlen = 0;
1050

1051
    while(1) {
1052
        if (len == maxlen) {
1053
            if (maxlen == 0) maxlen = 16;
1054
            maxlen *= 2;
1055
            char *oldval = line;
1056
            line = realloc(line,maxlen);
1057
            if (line == NULL) {
1058
                if (oldval) free(oldval);
1059
                return NULL;
1060
            }
1061
        }
1062
        int c = fgetc(stdin);
1063
        if (c == EOF || c == '\n') {
1064
            if (c == EOF && len == 0) {
1065
                free(line);
1066
                return NULL;
1067
            } else {
1068
                line[len] = '\0';
1069
                return line;
1070
            }
1071
        } else {
1072
            line[len] = c;
1073
            len++;
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. */
1083
char *linenoise(const char *prompt) {
1084
    char buf[LINENOISE_MAX_LINE];
1085
    int count;
1086

1087
    if (!isatty(STDIN_FILENO)) {
1088
        /* Not a tty: read from file / pipe. In this mode we don't want any
1089
         * limit to the line size, so we call a function to handle that. */
1090
        return linenoiseNoTTY();
1091
    } else if (isUnsupportedTerm()) {
1092
        size_t len;
1093

1094
        printf("%s",prompt);
1095
        fflush(stdout);
1096
        if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
1097
        len = strlen(buf);
1098
        while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
1099
            len--;
1100
            buf[len] = '\0';
1101
        }
1102
        return strdup(buf);
1103
    } else {
1104
        count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
1105
        if (count == -1) return NULL;
1106
        return 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. */
1114
void linenoiseFree(void *ptr) {
1115
    free(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. */
1122
static void freeHistory(void) {
1123
    if (history) {
1124
        int j;
1125

1126
        for (j = 0; j < history_len; j++)
1127
            free(history[j]);
1128
        free(history);
1129
    }
1130
}
1131

1132
/* At exit we'll try to fix the terminal to the initial conditions. */
1133
static void linenoiseAtExit(void) {
1134
    disableRawMode(STDIN_FILENO);
1135
    freeHistory();
1136
}
1137
#endif
1138
/* 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. */
1145
int linenoiseHistoryAdd(const char *line) {
1146
    char *linecopy;
1147

1148
    if (history_max_len == 0) return 0;
1149

1150
    /* Initialization on first call. */
1151
    if (history == NULL) {
1152
        history = malloc(sizeof(char*)*history_max_len);
1153
        if (history == NULL) return 0;
1154
        memset(history,0,(sizeof(char*)*history_max_len));
1155
    }
1156

1157
    /* Don't add duplicated lines. */
1158
    if (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. */
1162
    linecopy = strdup(line);
1163
    if (!linecopy) return 0;
1164
    if (history_len == history_max_len) {
1165
        free(history[0]);
1166
        memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1167
        history_len--;
1168
    }
1169
    history[history_len] = linecopy;
1170
    history_len++;
1171
    return 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. */
1178
int linenoiseHistorySetMaxLen(int len) {
1179
    char **new;
1180

1181
    if (len < 1) return 0;
1182
    if (history) {
1183
        int tocopy = history_len;
1184

1185
        new = malloc(sizeof(char*)*len);
1186
        if (new == NULL) return 0;
1187

1188
        /* If we can't copy everything, free the elements we'll not use. */
1189
        if (len < tocopy) {
1190
            int j;
1191

1192
            for (j = 0; j < tocopy-len; j++) free(history[j]);
1193
            tocopy = len;
1194
        }
1195
        memset(new,0,sizeof(char*)*len);
1196
        memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
1197
        free(history);
1198
        history = new;
1199
    }
1200
    history_max_len = len;
1201
    if (history_len > history_max_len)
1202
        history_len = history_max_len;
1203
    return 1;
1204
}
1205

1206
/* Save the history in the specified file. On success 0 is returned
1207
 * otherwise -1 is returned. */
1208
int linenoiseHistorySave(const char *filename) {
1209
    mode_t old_umask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
1210
    FILE *fp;
1211
    int j;
1212

1213
    fp = fopen(filename,"w");
1214
    umask(old_umask);
1215
    if (fp == NULL) return -1;
1216
    chmod(filename,S_IRUSR|S_IWUSR);
1217
    for (j = 0; j < history_len; j++)
1218
        fprintf(fp,"%s\n",history[j]);
1219
    fclose(fp);
1220
    return 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. */
1228
int linenoiseHistoryLoad(const char *filename) {
1229
    FILE *fp = fopen(filename,"r");
1230
    char buf[LINENOISE_MAX_LINE];
1231

1232
    if (fp == NULL) return -1;
1233

1234
    while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1235
        char *p;
1236

1237
        p = strchr(buf,'\r');
1238
        if (!p) p = strchr(buf,'\n');
1239
        if (p) *p = '\0';
1240
        linenoiseHistoryAdd(buf);
1241
    }
1242
    fclose(fp);
1243
    return 0;
1244
}
1245

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.