Back to home page

Enduro/X

 
 

    


0001 /* linenoise.c -- guerrilla line editing library against the idea that a
0002  * line editing lib needs to be 20,000 lines of C code.
0003  *
0004  * You can find the latest source code at:
0005  *
0006  *   http://github.com/antirez/linenoise
0007  *
0008  * Does a number of crazy assumptions that happen to be true in 99.9999% of
0009  * the 2010 UNIX computers around.
0010  *
0011  * ------------------------------------------------------------------------
0012  *
0013  * Copyright (c) 2010-2016, Salvatore Sanfilippo <antirez at gmail dot com>
0014  * Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
0015  *
0016  * All rights reserved.
0017  *
0018  * Redistribution and use in source and binary forms, with or without
0019  * modification, are permitted provided that the following conditions are
0020  * met:
0021  *
0022  *  *  Redistributions of source code must retain the above copyright
0023  *     notice, this list of conditions and the following disclaimer.
0024  *
0025  *  *  Redistributions in binary form must reproduce the above copyright
0026  *     notice, this list of conditions and the following disclaimer in the
0027  *     documentation and/or other materials provided with the distribution.
0028  *
0029  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0030  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0031  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0032  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0033  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0034  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0035  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0036  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0037  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0038  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0039  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0040  *
0041  * ------------------------------------------------------------------------
0042  *
0043  * References:
0044  * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
0045  * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
0046  *
0047  * Todo list:
0048  * - Filter bogus Ctrl+<char> combinations.
0049  * - Win32 support
0050  *
0051  * Bloat:
0052  * - History search like Ctrl+r in readline?
0053  *
0054  * List of escape sequences used by this program, we do everything just
0055  * with three sequences. In order to be so cheap we may have some
0056  * flickering effect with some slow terminal, but the lesser sequences
0057  * the more compatible.
0058  *
0059  * EL (Erase Line)
0060  *    Sequence: ESC [ n K
0061  *    Effect: if n is 0 or missing, clear from cursor to end of line
0062  *    Effect: if n is 1, clear from beginning of line to cursor
0063  *    Effect: if n is 2, clear entire line
0064  *
0065  * CUF (CUrsor Forward)
0066  *    Sequence: ESC [ n C
0067  *    Effect: moves cursor forward n chars
0068  *
0069  * CUB (CUrsor Backward)
0070  *    Sequence: ESC [ n D
0071  *    Effect: moves cursor backward n chars
0072  *
0073  * The following is used to get the terminal width if getting
0074  * the width with the TIOCGWINSZ ioctl fails
0075  *
0076  * DSR (Device Status Report)
0077  *    Sequence: ESC [ 6 n
0078  *    Effect: reports the current cusor position as ESC [ n ; m R
0079  *            where n is the row and m is the column
0080  *
0081  * When multi line mode is enabled, we also use an additional escape
0082  * sequence. However multi line editing is disabled by default.
0083  *
0084  * CUU (Cursor Up)
0085  *    Sequence: ESC [ n A
0086  *    Effect: moves cursor up of n chars.
0087  *
0088  * CUD (Cursor Down)
0089  *    Sequence: ESC [ n B
0090  *    Effect: moves cursor down of n chars.
0091  *
0092  * When linenoiseClearScreen() is called, two additional escape sequences
0093  * are used in order to clear the screen and position the cursor at home
0094  * position.
0095  *
0096  * CUP (Cursor position)
0097  *    Sequence: ESC [ H
0098  *    Effect: moves the cursor to upper left corner
0099  *
0100  * ED (Erase display)
0101  *    Sequence: ESC [ 2 J
0102  *    Effect: clear the whole screen
0103  *
0104  */
0105 
0106 #include <termios.h>
0107 #include <unistd.h>
0108 #include <stdlib.h>
0109 #include <stdio.h>
0110 #include <errno.h>
0111 #include <string.h>
0112 #include <stdlib.h>
0113 #include <ctype.h>
0114 #include <sys/stat.h>
0115 #include <sys/types.h>
0116 #include <sys/ioctl.h>
0117 #include <unistd.h>
0118 #include "linenoise.h"
0119 
0120 #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
0121 #define LINENOISE_MAX_LINE 4096
0122 static char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
0123 static linenoiseCompletionCallback *completionCallback = NULL;
0124 static linenoiseHintsCallback *hintsCallback = NULL;
0125 static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
0126 
0127 static struct termios orig_termios; /* In order to restore at exit.*/
0128 static int rawmode = 0; /* For atexit() function to check if restore is needed*/
0129 static int mlmode = 0;  /* Multi line mode. Default is single line. */
0130 static int atexit_registered = 0; /* Register atexit just 1 time. */
0131 static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
0132 static int history_len = 0;
0133 static char **history = NULL;
0134 
0135 int ndrx_G_ctrl_d = 0;    /**< Is ctrl+d EOF ? */
0136 
0137 /* The linenoiseState structure represents the state during line editing.
0138  * We pass this state to functions implementing specific editing
0139  * functionalities. */
0140 struct linenoiseState {
0141     int ifd;            /* Terminal stdin file descriptor. */
0142     int ofd;            /* Terminal stdout file descriptor. */
0143     char *buf;          /* Edited line buffer. */
0144     size_t buflen;      /* Edited line buffer size. */
0145     const char *prompt; /* Prompt to display. */
0146     size_t plen;        /* Prompt length. */
0147     size_t pos;         /* Current cursor position. */
0148     size_t oldpos;      /* Previous refresh cursor position. */
0149     size_t len;         /* Current edited line length. */
0150     size_t cols;        /* Number of columns in terminal. */
0151     size_t maxrows;     /* Maximum num of rows used so far (multiline mode) */
0152     int history_index;  /* The history index we are currently editing. */
0153 };
0154 
0155 enum KEY_ACTION{
0156     KEY_NULL = 0,       /* NULL */
0157     CTRL_A = 1,         /* Ctrl+a */
0158     CTRL_B = 2,         /* Ctrl-b */
0159     CTRL_C = 3,         /* Ctrl-c */
0160     CTRL_D = 4,         /* Ctrl-d */
0161     CTRL_E = 5,         /* Ctrl-e */
0162     CTRL_F = 6,         /* Ctrl-f */
0163     CTRL_H = 8,         /* Ctrl-h */
0164     TAB = 9,            /* Tab */
0165     CTRL_K = 11,        /* Ctrl+k */
0166     CTRL_L = 12,        /* Ctrl+l */
0167     ENTER = 13,         /* Enter */
0168     CTRL_N = 14,        /* Ctrl-n */
0169     CTRL_P = 16,        /* Ctrl-p */
0170     CTRL_T = 20,        /* Ctrl-t */
0171     CTRL_U = 21,        /* Ctrl+u */
0172     CTRL_W = 23,        /* Ctrl+w */
0173     ESC = 27,           /* Escape */
0174     BACKSPACE =  127    /* Backspace */
0175 };
0176 
0177 static void linenoiseAtExit(void);
0178 int linenoiseHistoryAdd(const char *line);
0179 static void refreshLine(struct linenoiseState *l);
0180 
0181 /* Debugging macro. */
0182 #if 0
0183 FILE *lndebug_fp = NULL;
0184 #define lndebug(...) \
0185     do { \
0186         if (lndebug_fp == NULL) { \
0187             lndebug_fp = fopen("/tmp/lndebug.txt","a"); \
0188             fprintf(lndebug_fp, \
0189             "[%d %d %d] p: %d, rows: %d, rpos: %d, max: %d, oldmax: %d\n", \
0190             (int)l->len,(int)l->pos,(int)l->oldpos,plen,rows,rpos, \
0191             (int)l->maxrows,old_rows); \
0192         } \
0193         fprintf(lndebug_fp, ", " __VA_ARGS__); \
0194         fflush(lndebug_fp); \
0195     } while (0)
0196 #else
0197 #define lndebug(fmt, ...)
0198 #endif
0199 
0200 /* ======================= Low level terminal handling ====================== */
0201 
0202 /* Set if to use or not the multi line mode. */
0203 void linenoiseSetMultiLine(int ml) {
0204     mlmode = ml;
0205 }
0206 
0207 /* Return true if the terminal name is in the list of terminals we know are
0208  * not able to understand basic escape sequences. */
0209 static int isUnsupportedTerm(void) {
0210     char *term = getenv("TERM");
0211     int j;
0212 
0213     if (term == NULL) return 0;
0214     for (j = 0; unsupported_term[j]; j++)
0215         if (!strcasecmp(term,unsupported_term[j])) return 1;
0216     return 0;
0217 }
0218 
0219 /* Raw mode: 1960 magic shit. */
0220 static int enableRawMode(int fd) {
0221     struct termios raw;
0222 
0223     if (!isatty(STDIN_FILENO)) goto fatal;
0224     if (!atexit_registered) {
0225         atexit(linenoiseAtExit);
0226         atexit_registered = 1;
0227     }
0228     if (tcgetattr(fd,&orig_termios) == -1) goto fatal;
0229 
0230     raw = orig_termios;  /* modify the original mode */
0231     /* input modes: no break, no CR to NL, no parity check, no strip char,
0232      * no start/stop output control. */
0233     raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
0234     /* output modes - disable post processing */
0235     raw.c_oflag &= ~(OPOST);
0236     /* control modes - set 8 bit chars */
0237     raw.c_cflag |= (CS8);
0238     /* local modes - choing off, canonical off, no extended functions,
0239      * no signal chars (^Z,^C) */
0240     raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
0241     /* control chars - set return condition: min number of bytes and timer.
0242      * We want read to return every single byte, without timeout. */
0243     raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
0244 
0245     /* put terminal in raw mode after flushing */
0246     if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;
0247     rawmode = 1;
0248     return 0;
0249 
0250 fatal:
0251     errno = ENOTTY;
0252     return -1;
0253 }
0254 
0255 static void disableRawMode(int fd) {
0256     /* Don't even check the return value as it's too late. */
0257     if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)
0258         rawmode = 0;
0259 }
0260 
0261 /* Use the ESC [6n escape sequence to query the horizontal cursor position
0262  * and return it. On error -1 is returned, on success the position of the
0263  * cursor. */
0264 static int getCursorPosition(int ifd, int ofd) {
0265     char buf[32];
0266     int cols, rows;
0267     unsigned int i = 0;
0268 
0269     /* Report cursor location */
0270     if (write(ofd, "\x1b[6n", 4) != 4) return -1;
0271 
0272     /* Read the response: ESC [ rows ; cols R */
0273     while (i < sizeof(buf)-1) {
0274         if (read(ifd,buf+i,1) != 1) break;
0275         if (buf[i] == 'R') break;
0276         i++;
0277     }
0278     buf[i] = '\0';
0279 
0280     /* Parse it. */
0281     if (buf[0] != ESC || buf[1] != '[') return -1;
0282     if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1;
0283     return cols;
0284 }
0285 
0286 /* Try to get the number of columns in the current terminal, or assume 80
0287  * if it fails. */
0288 static int getColumns(int ifd, int ofd) {
0289     struct winsize ws;
0290 
0291     if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
0292         /* ioctl() failed. Try to query the terminal itself. */
0293         int start, cols;
0294 
0295         /* Get the initial position so we can restore it later. */
0296         start = getCursorPosition(ifd,ofd);
0297         if (start == -1) goto failed;
0298 
0299         /* Go to right margin and get position. */
0300         if (write(ofd,"\x1b[999C",6) != 6) goto failed;
0301         cols = getCursorPosition(ifd,ofd);
0302         if (cols == -1) goto failed;
0303 
0304         /* Restore position. */
0305         if (cols > start) {
0306             char seq[32];
0307             snprintf(seq,32,"\x1b[%dD",cols-start);
0308             if (write(ofd,seq,strlen(seq)) == -1) {
0309                 /* Can't recover... */
0310             }
0311         }
0312         return cols;
0313     } else {
0314         return ws.ws_col;
0315     }
0316 
0317 failed:
0318     return 80;
0319 }
0320 
0321 /* Clear the screen. Used to handle ctrl+l */
0322 void linenoiseClearScreen(void) {
0323     if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
0324         /* nothing to do, just to avoid warning. */
0325     }
0326 }
0327 
0328 /* Beep, used for completion when there is nothing to complete or when all
0329  * the choices were already shown. */
0330 static void linenoiseBeep(void) {
0331     fprintf(stderr, "\x7");
0332     fflush(stderr);
0333 }
0334 
0335 /* ============================== Completion ================================ */
0336 
0337 /* Free a list of completion option populated by linenoiseAddCompletion(). */
0338 static void freeCompletions(linenoiseCompletions *lc) {
0339     size_t i;
0340     for (i = 0; i < lc->len; i++)
0341         free(lc->cvec[i]);
0342     if (lc->cvec != NULL)
0343         free(lc->cvec);
0344 }
0345 
0346 /* This is an helper function for linenoiseEdit() and is called when the
0347  * user types the <tab> key in order to complete the string currently in the
0348  * input.
0349  *
0350  * The state of the editing is encapsulated into the pointed linenoiseState
0351  * structure as described in the structure definition. */
0352 static int completeLine(struct linenoiseState *ls) {
0353     linenoiseCompletions lc = { 0, NULL };
0354     int nread, nwritten;
0355     char c = 0;
0356 
0357     completionCallback(ls->buf,&lc);
0358     if (lc.len == 0) {
0359         linenoiseBeep();
0360     } else {
0361         size_t stop = 0, i = 0;
0362 
0363         while(!stop) {
0364             /* Show completion or original buffer */
0365             if (i < lc.len) {
0366                 struct linenoiseState saved = *ls;
0367 
0368                 ls->len = ls->pos = strlen(lc.cvec[i]);
0369                 ls->buf = lc.cvec[i];
0370                 refreshLine(ls);
0371                 ls->len = saved.len;
0372                 ls->pos = saved.pos;
0373                 ls->buf = saved.buf;
0374             } else {
0375                 refreshLine(ls);
0376             }
0377 
0378             nread = read(ls->ifd,&c,1);
0379             if (nread <= 0) {
0380                 freeCompletions(&lc);
0381                 return -1;
0382             }
0383 
0384             switch(c) {
0385                 case 9: /* tab */
0386                     i = (i+1) % (lc.len+1);
0387                     if (i == lc.len) linenoiseBeep();
0388                     break;
0389                 case 27: /* escape */
0390                     /* Re-show original buffer */
0391                     if (i < lc.len) refreshLine(ls);
0392                     stop = 1;
0393                     break;
0394                 default:
0395                     /* Update buffer and return */
0396                     if (i < lc.len) {
0397                         nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]);
0398                         ls->len = ls->pos = nwritten;
0399                     }
0400                     stop = 1;
0401                     break;
0402             }
0403         }
0404     }
0405 
0406     freeCompletions(&lc);
0407     return c; /* Return last read character */
0408 }
0409 
0410 /* Register a callback function to be called for tab-completion. */
0411 void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) {
0412     completionCallback = fn;
0413 }
0414 
0415 /* Register a hits function to be called to show hits to the user at the
0416  * right of the prompt. */
0417 void linenoiseSetHintsCallback(linenoiseHintsCallback *fn) {
0418     hintsCallback = fn;
0419 }
0420 
0421 /* Register a function to free the hints returned by the hints callback
0422  * registered with linenoiseSetHintsCallback(). */
0423 void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *fn) {
0424     freeHintsCallback = fn;
0425 }
0426 
0427 /* This function is used by the callback function registered by the user
0428  * in order to add completion options given the input string when the
0429  * user typed <tab>. See the example.c source code for a very easy to
0430  * understand example. */
0431 void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
0432     size_t len = strlen(str);
0433     char *copy, **cvec;
0434 
0435     copy = malloc(len+1);
0436     if (copy == NULL) return;
0437     memcpy(copy,str,len+1);
0438     cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1));
0439     if (cvec == NULL) {
0440         free(copy);
0441         return;
0442     }
0443     lc->cvec = cvec;
0444     lc->cvec[lc->len++] = copy;
0445 }
0446 
0447 /* =========================== Line editing ================================= */
0448 
0449 /* We define a very simple "append buffer" structure, that is an heap
0450  * allocated string where we can append to. This is useful in order to
0451  * write all the escape sequences in a buffer and flush them to the standard
0452  * output in a single call, to avoid flickering effects. */
0453 struct abuf {
0454     char *b;
0455     int len;
0456 };
0457 
0458 static void abInit(struct abuf *ab) {
0459     ab->b = NULL;
0460     ab->len = 0;
0461 }
0462 
0463 static void abAppend(struct abuf *ab, const char *s, int len) {
0464     char *new = realloc(ab->b,ab->len+len);
0465 
0466     if (new == NULL) return;
0467     memcpy(new+ab->len,s,len);
0468     ab->b = new;
0469     ab->len += len;
0470 }
0471 
0472 static void abFree(struct abuf *ab) {
0473     free(ab->b);
0474 }
0475 
0476 /* Helper of refreshSingleLine() and refreshMultiLine() to show hints
0477  * to the right of the prompt. */
0478 void refreshShowHints(struct abuf *ab, struct linenoiseState *l, int plen) {
0479     char seq[64];
0480     if (hintsCallback && plen+l->len < l->cols) {
0481         int color = -1, bold = 0;
0482         char *hint = hintsCallback(l->buf,&color,&bold);
0483         if (hint) {
0484             int hintlen = strlen(hint);
0485             int hintmaxlen = l->cols-(plen+l->len);
0486             if (hintlen > hintmaxlen) hintlen = hintmaxlen;
0487             if (bold == 1 && color == -1) color = 37;
0488             if (color != -1 || bold != 0)
0489                 snprintf(seq,64,"\033[%d;%d;49m",bold,color);
0490             else
0491                 seq[0] = '\0';
0492             abAppend(ab,seq,strlen(seq));
0493             abAppend(ab,hint,hintlen);
0494             if (color != -1 || bold != 0)
0495                 abAppend(ab,"\033[0m",4);
0496             /* Call the function to free the hint returned. */
0497             if (freeHintsCallback) freeHintsCallback(hint);
0498         }
0499     }
0500 }
0501 
0502 /* Single line low level line refresh.
0503  *
0504  * Rewrite the currently edited line accordingly to the buffer content,
0505  * cursor position, and number of columns of the terminal. */
0506 static void refreshSingleLine(struct linenoiseState *l) {
0507     char seq[64];
0508     size_t plen = strlen(l->prompt);
0509     int fd = l->ofd;
0510     char *buf = l->buf;
0511     size_t len = l->len;
0512     size_t pos = l->pos;
0513     struct abuf ab;
0514 
0515     while((plen+pos) >= l->cols) {
0516         buf++;
0517         len--;
0518         pos--;
0519     }
0520     while (plen+len > l->cols) {
0521         len--;
0522     }
0523 
0524     abInit(&ab);
0525     /* Cursor to left edge */
0526     snprintf(seq,64,"\r");
0527     abAppend(&ab,seq,strlen(seq));
0528     /* Write the prompt and the current buffer content */
0529     abAppend(&ab,l->prompt,strlen(l->prompt));
0530     abAppend(&ab,buf,len);
0531     /* Show hits if any. */
0532     refreshShowHints(&ab,l,plen);
0533     /* Erase to right */
0534     snprintf(seq,64,"\x1b[0K");
0535     abAppend(&ab,seq,strlen(seq));
0536     /* Move cursor to original position. */
0537     snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
0538     abAppend(&ab,seq,strlen(seq));
0539     if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
0540     abFree(&ab);
0541 }
0542 
0543 /* Multi line low level line refresh.
0544  *
0545  * Rewrite the currently edited line accordingly to the buffer content,
0546  * cursor position, and number of columns of the terminal. */
0547 static void refreshMultiLine(struct linenoiseState *l) {
0548     char seq[64];
0549     int plen = strlen(l->prompt);
0550     int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
0551     int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
0552     int rpos2; /* rpos after refresh. */
0553     int col; /* colum position, zero-based. */
0554     int old_rows = l->maxrows;
0555     int fd = l->ofd, j;
0556     struct abuf ab;
0557 
0558     /* Update maxrows if needed. */
0559     if (rows > (int)l->maxrows) l->maxrows = rows;
0560 
0561     /* First step: clear all the lines used before. To do so start by
0562      * going to the last row. */
0563     abInit(&ab);
0564     if (old_rows-rpos > 0) {
0565         lndebug("go down %d", old_rows-rpos);
0566         snprintf(seq,64,"\x1b[%dB", old_rows-rpos);
0567         abAppend(&ab,seq,strlen(seq));
0568     }
0569 
0570     /* Now for every row clear it, go up. */
0571     for (j = 0; j < old_rows-1; j++) {
0572         lndebug("clear+up");
0573         snprintf(seq,64,"\r\x1b[0K\x1b[1A");
0574         abAppend(&ab,seq,strlen(seq));
0575     }
0576 
0577     /* Clean the top line. */
0578     lndebug("clear");
0579     snprintf(seq,64,"\r\x1b[0K");
0580     abAppend(&ab,seq,strlen(seq));
0581 
0582     /* Write the prompt and the current buffer content */
0583     abAppend(&ab,l->prompt,strlen(l->prompt));
0584     abAppend(&ab,l->buf,l->len);
0585 
0586     /* Show hits if any. */
0587     refreshShowHints(&ab,l,plen);
0588 
0589     /* If we are at the very end of the screen with our prompt, we need to
0590      * emit a newline and move the prompt to the first column. */
0591     if (l->pos &&
0592         l->pos == l->len &&
0593         (l->pos+plen) % l->cols == 0)
0594     {
0595         lndebug("<newline>");
0596         abAppend(&ab,"\n",1);
0597         snprintf(seq,64,"\r");
0598         abAppend(&ab,seq,strlen(seq));
0599         rows++;
0600         if (rows > (int)l->maxrows) l->maxrows = rows;
0601     }
0602 
0603     /* Move cursor to right position. */
0604     rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */
0605     lndebug("rpos2 %d", rpos2);
0606 
0607     /* Go up till we reach the expected positon. */
0608     if (rows-rpos2 > 0) {
0609         lndebug("go-up %d", rows-rpos2);
0610         snprintf(seq,64,"\x1b[%dA", rows-rpos2);
0611         abAppend(&ab,seq,strlen(seq));
0612     }
0613 
0614     /* Set column. */
0615     col = (plen+(int)l->pos) % (int)l->cols;
0616     lndebug("set col %d", 1+col);
0617     if (col)
0618         snprintf(seq,64,"\r\x1b[%dC", col);
0619     else
0620         snprintf(seq,64,"\r");
0621     abAppend(&ab,seq,strlen(seq));
0622 
0623     lndebug("\n");
0624     l->oldpos = l->pos;
0625 
0626     if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
0627     abFree(&ab);
0628 }
0629 
0630 /* Calls the two low level functions refreshSingleLine() or
0631  * refreshMultiLine() according to the selected mode. */
0632 static void refreshLine(struct linenoiseState *l) {
0633     if (mlmode)
0634         refreshMultiLine(l);
0635     else
0636         refreshSingleLine(l);
0637 }
0638 
0639 /* Insert the character 'c' at cursor current position.
0640  *
0641  * On error writing to the terminal -1 is returned, otherwise 0. */
0642 int linenoiseEditInsert(struct linenoiseState *l, char c) {
0643     if (l->len < l->buflen) {
0644         if (l->len == l->pos) {
0645             l->buf[l->pos] = c;
0646             l->pos++;
0647             l->len++;
0648             l->buf[l->len] = '\0';
0649             if ((!mlmode && l->plen+l->len < l->cols && !hintsCallback)) {
0650                 /* Avoid a full update of the line in the
0651                  * trivial case. */
0652                 if (write(l->ofd,&c,1) == -1) return -1;
0653             } else {
0654                 refreshLine(l);
0655             }
0656         } else {
0657             memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos);
0658             l->buf[l->pos] = c;
0659             l->len++;
0660             l->pos++;
0661             l->buf[l->len] = '\0';
0662             refreshLine(l);
0663         }
0664     }
0665     return 0;
0666 }
0667 
0668 /* Move cursor on the left. */
0669 void linenoiseEditMoveLeft(struct linenoiseState *l) {
0670     if (l->pos > 0) {
0671         l->pos--;
0672         refreshLine(l);
0673     }
0674 }
0675 
0676 /* Move cursor on the right. */
0677 void linenoiseEditMoveRight(struct linenoiseState *l) {
0678     if (l->pos != l->len) {
0679         l->pos++;
0680         refreshLine(l);
0681     }
0682 }
0683 
0684 /* Move cursor to the start of the line. */
0685 void linenoiseEditMoveHome(struct linenoiseState *l) {
0686     if (l->pos != 0) {
0687         l->pos = 0;
0688         refreshLine(l);
0689     }
0690 }
0691 
0692 /* Move cursor to the end of the line. */
0693 void linenoiseEditMoveEnd(struct linenoiseState *l) {
0694     if (l->pos != l->len) {
0695         l->pos = l->len;
0696         refreshLine(l);
0697     }
0698 }
0699 
0700 /* Substitute the currently edited line with the next or previous history
0701  * entry as specified by 'dir'. */
0702 #define LINENOISE_HISTORY_NEXT 0
0703 #define LINENOISE_HISTORY_PREV 1
0704 void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) {
0705     if (history_len > 1) {
0706         /* Update the current history entry before to
0707          * overwrite it with the next one. */
0708         free(history[history_len - 1 - l->history_index]);
0709         history[history_len - 1 - l->history_index] = strdup(l->buf);
0710         /* Show the new entry */
0711         l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
0712         if (l->history_index < 0) {
0713             l->history_index = 0;
0714             return;
0715         } else if (l->history_index >= history_len) {
0716             l->history_index = history_len-1;
0717             return;
0718         }
0719         strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen);
0720         l->buf[l->buflen-1] = '\0';
0721         l->len = l->pos = strlen(l->buf);
0722         refreshLine(l);
0723     }
0724 }
0725 
0726 /* Delete the character at the right of the cursor without altering the cursor
0727  * position. Basically this is what happens with the "Delete" keyboard key. */
0728 void linenoiseEditDelete(struct linenoiseState *l) {
0729     if (l->len > 0 && l->pos < l->len) {
0730         memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1);
0731         l->len--;
0732         l->buf[l->len] = '\0';
0733         refreshLine(l);
0734     }
0735 }
0736 
0737 /* Backspace implementation. */
0738 void linenoiseEditBackspace(struct linenoiseState *l) {
0739     if (l->pos > 0 && l->len > 0) {
0740         memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos);
0741         l->pos--;
0742         l->len--;
0743         l->buf[l->len] = '\0';
0744         refreshLine(l);
0745     }
0746 }
0747 
0748 /* Delete the previosu word, maintaining the cursor at the start of the
0749  * current word. */
0750 void linenoiseEditDeletePrevWord(struct linenoiseState *l) {
0751     size_t old_pos = l->pos;
0752     size_t diff;
0753 
0754     while (l->pos > 0 && l->buf[l->pos-1] == ' ')
0755         l->pos--;
0756     while (l->pos > 0 && l->buf[l->pos-1] != ' ')
0757         l->pos--;
0758     diff = old_pos - l->pos;
0759     memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1);
0760     l->len -= diff;
0761     refreshLine(l);
0762 }
0763 
0764 /* This function is the core of the line editing capability of linenoise.
0765  * It expects 'fd' to be already in "raw mode" so that every key pressed
0766  * will be returned ASAP to read().
0767  *
0768  * The resulting string is put into 'buf' when the user type enter, or
0769  * when ctrl+d is typed.
0770  *
0771  * The function returns the length of the current buffer. */
0772 static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt)
0773 {
0774     struct linenoiseState l;
0775 
0776     /* Populate the linenoise state that we pass to functions implementing
0777      * specific editing functionalities. */
0778     l.ifd = stdin_fd;
0779     l.ofd = stdout_fd;
0780     l.buf = buf;
0781     l.buflen = buflen;
0782     l.prompt = prompt;
0783     l.plen = strlen(prompt);
0784     l.oldpos = l.pos = 0;
0785     l.len = 0;
0786     l.cols = getColumns(stdin_fd, stdout_fd);
0787     l.maxrows = 0;
0788     l.history_index = 0;
0789 
0790     /* Buffer starts empty. */
0791     l.buf[0] = '\0';
0792     l.buflen--; /* Make sure there is always space for the nulterm */
0793 
0794     /* The latest history entry is always our current buffer, that
0795      * initially is just an empty string. */
0796     linenoiseHistoryAdd("");
0797 
0798     if (write(l.ofd,prompt,l.plen) == -1) return -1;
0799     while(1) {
0800         char c;
0801         int nread;
0802         char seq[3];
0803 
0804         nread = read(l.ifd,&c,1);
0805         if (nread <= 0) return l.len;
0806 
0807         /* Only autocomplete when the callback is set. It returns < 0 when
0808          * there was an error reading from fd. Otherwise it will return the
0809          * character that should be handled next. */
0810         if (c == 9 && completionCallback != NULL) {
0811             c = completeLine(&l);
0812             /* Return on errors */
0813             if (c < 0) return l.len;
0814             /* Read next character when 0 */
0815             if (c == 0) continue;
0816         }
0817 
0818         switch(c) {
0819         case ENTER:    /* enter */
0820             history_len--;
0821             free(history[history_len]);
0822             if (mlmode) linenoiseEditMoveEnd(&l);
0823             if (hintsCallback) {
0824                 /* Force a refresh without hints to leave the previous
0825                  * line as the user typed it after a newline. */
0826                 linenoiseHintsCallback *hc = hintsCallback;
0827                 hintsCallback = NULL;
0828                 refreshLine(&l);
0829                 hintsCallback = hc;
0830             }
0831             return (int)l.len;
0832         case CTRL_C:     /* ctrl-c */
0833             errno = EAGAIN;
0834             return -1;
0835         case BACKSPACE:   /* backspace */
0836         case 8:     /* ctrl-h */
0837             linenoiseEditBackspace(&l);
0838             break;
0839         case CTRL_D:     /* ctrl-d, remove char at right of cursor, or if the
0840                             line is empty, act as end-of-file. */
0841             if (l.len > 0) {
0842                 linenoiseEditDelete(&l);
0843             } else {
0844                 history_len--;
0845                 free(history[history_len]);
0846                 ndrx_G_ctrl_d=1; /**< This is Mavimax extension */
0847                 return -1;
0848             }
0849             break;
0850         case CTRL_T:    /* ctrl-t, swaps current character with previous. */
0851             if (l.pos > 0 && l.pos < l.len) {
0852                 int aux = buf[l.pos-1];
0853                 buf[l.pos-1] = buf[l.pos];
0854                 buf[l.pos] = aux;
0855                 if (l.pos != l.len-1) l.pos++;
0856                 refreshLine(&l);
0857             }
0858             break;
0859         case CTRL_B:     /* ctrl-b */
0860             linenoiseEditMoveLeft(&l);
0861             break;
0862         case CTRL_F:     /* ctrl-f */
0863             linenoiseEditMoveRight(&l);
0864             break;
0865         case CTRL_P:    /* ctrl-p */
0866             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
0867             break;
0868         case CTRL_N:    /* ctrl-n */
0869             linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
0870             break;
0871         case ESC:    /* escape sequence */
0872             /* Read the next two bytes representing the escape sequence.
0873              * Use two calls to handle slow terminals returning the two
0874              * chars at different times. */
0875             if (read(l.ifd,seq,1) == -1) break;
0876             if (read(l.ifd,seq+1,1) == -1) break;
0877 
0878             /* ESC [ sequences. */
0879             if (seq[0] == '[') {
0880                 if (seq[1] >= '0' && seq[1] <= '9') {
0881                     /* Extended escape, read additional byte. */
0882                     if (read(l.ifd,seq+2,1) == -1) break;
0883                     if (seq[2] == '~') {
0884                         switch(seq[1]) {
0885                         case '3': /* Delete key. */
0886                             linenoiseEditDelete(&l);
0887                             break;
0888                         }
0889                     }
0890                 } else {
0891                     switch(seq[1]) {
0892                     case 'A': /* Up */
0893                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV);
0894                         break;
0895                     case 'B': /* Down */
0896                         linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT);
0897                         break;
0898                     case 'C': /* Right */
0899                         linenoiseEditMoveRight(&l);
0900                         break;
0901                     case 'D': /* Left */
0902                         linenoiseEditMoveLeft(&l);
0903                         break;
0904                     case 'H': /* Home */
0905                         linenoiseEditMoveHome(&l);
0906                         break;
0907                     case 'F': /* End*/
0908                         linenoiseEditMoveEnd(&l);
0909                         break;
0910                     }
0911                 }
0912             }
0913 
0914             /* ESC O sequences. */
0915             else if (seq[0] == 'O') {
0916                 switch(seq[1]) {
0917                 case 'H': /* Home */
0918                     linenoiseEditMoveHome(&l);
0919                     break;
0920                 case 'F': /* End*/
0921                     linenoiseEditMoveEnd(&l);
0922                     break;
0923                 }
0924             }
0925             break;
0926         default:
0927             if (linenoiseEditInsert(&l,c)) return -1;
0928             break;
0929         case CTRL_U: /* Ctrl+u, delete the whole line. */
0930             buf[0] = '\0';
0931             l.pos = l.len = 0;
0932             refreshLine(&l);
0933             break;
0934         case CTRL_K: /* Ctrl+k, delete from current to end of line. */
0935             buf[l.pos] = '\0';
0936             l.len = l.pos;
0937             refreshLine(&l);
0938             break;
0939         case CTRL_A: /* Ctrl+a, go to the start of the line */
0940             linenoiseEditMoveHome(&l);
0941             break;
0942         case CTRL_E: /* ctrl+e, go to the end of the line */
0943             linenoiseEditMoveEnd(&l);
0944             break;
0945         case CTRL_L: /* ctrl+l, clear screen */
0946             linenoiseClearScreen();
0947             refreshLine(&l);
0948             break;
0949         case CTRL_W: /* ctrl+w, delete previous word */
0950             linenoiseEditDeletePrevWord(&l);
0951             break;
0952         }
0953     }
0954     return l.len;
0955 }
0956 
0957 /* This special mode is used by linenoise in order to print scan codes
0958  * on screen for debugging / development purposes. It is implemented
0959  * by the linenoise_example program using the --keycodes option. */
0960 void linenoisePrintKeyCodes(void) {
0961     char quit[4];
0962 
0963     printf("Linenoise key codes debugging mode.\n"
0964             "Press keys to see scan codes. Type 'quit' at any time to exit.\n");
0965     if (enableRawMode(STDIN_FILENO) == -1) return;
0966     memset(quit,' ',4);
0967     while(1) {
0968         char c;
0969         int nread;
0970 
0971         nread = read(STDIN_FILENO,&c,1);
0972         if (nread <= 0) continue;
0973         memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */
0974         quit[sizeof(quit)-1] = c; /* Insert current char on the right. */
0975         if (memcmp(quit,"quit",sizeof(quit)) == 0) break;
0976 
0977         printf("'%c' %02x (%d) (type quit to exit)\n",
0978             isprint(c) ? c : '?', (int)c, (int)c);
0979         printf("\r"); /* Go left edge manually, we are in raw mode. */
0980         fflush(stdout);
0981     }
0982     disableRawMode(STDIN_FILENO);
0983 }
0984 
0985 /* This function calls the line editing function linenoiseEdit() using
0986  * the STDIN file descriptor set in raw mode. */
0987 static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) {
0988     int count;
0989 
0990     if (buflen == 0) {
0991         errno = EINVAL;
0992         return -1;
0993     }
0994 
0995     if (enableRawMode(STDIN_FILENO) == -1) return -1;
0996     count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt);
0997     disableRawMode(STDIN_FILENO);
0998     printf("\n");
0999     return count;
1000 }
1001 
1002 /* This function is called when linenoise() is called with the standard
1003  * input file descriptor not attached to a TTY. So for example when the
1004  * program using linenoise is called in pipe or with a file redirected
1005  * to its standard input. In this case, we want to be able to return the
1006  * line regardless of its length (by default we are limited to 4k). */
1007 static char *linenoiseNoTTY(void) {
1008     char *line = NULL;
1009     size_t len = 0, maxlen = 0;
1010 
1011     while(1) {
1012         if (len == maxlen) {
1013             if (maxlen == 0) maxlen = 16;
1014             maxlen *= 2;
1015             char *oldval = line;
1016             line = realloc(line,maxlen);
1017             if (line == NULL) {
1018                 if (oldval) free(oldval);
1019                 return NULL;
1020             }
1021         }
1022         int c = fgetc(stdin);
1023         if (c == EOF || c == '\n') {
1024             if (c == EOF && len == 0) {
1025                 free(line);
1026                 return NULL;
1027             } else {
1028                 line[len] = '\0';
1029                 return line;
1030             }
1031         } else {
1032             line[len] = c;
1033             len++;
1034         }
1035     }
1036 }
1037 
1038 /* The high level function that is the main API of the linenoise library.
1039  * This function checks if the terminal has basic capabilities, just checking
1040  * for a blacklist of stupid terminals, and later either calls the line
1041  * editing function or uses dummy fgets() so that you will be able to type
1042  * something even in the most desperate of the conditions. */
1043 char *linenoise(const char *prompt) {
1044     char buf[LINENOISE_MAX_LINE];
1045     int count;
1046 
1047     if (!isatty(STDIN_FILENO)) {
1048         /* Not a tty: read from file / pipe. In this mode we don't want any
1049          * limit to the line size, so we call a function to handle that. */
1050         return linenoiseNoTTY();
1051     } else if (isUnsupportedTerm()) {
1052         size_t len;
1053 
1054         printf("%s",prompt);
1055         fflush(stdout);
1056         if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL;
1057         len = strlen(buf);
1058         while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) {
1059             len--;
1060             buf[len] = '\0';
1061         }
1062         return strdup(buf);
1063     } else {
1064         count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt);
1065         if (count == -1) return NULL;
1066         return strdup(buf);
1067     }
1068 }
1069 
1070 /* This is just a wrapper the user may want to call in order to make sure
1071  * the linenoise returned buffer is freed with the same allocator it was
1072  * created with. Useful when the main program is using an alternative
1073  * allocator. */
1074 void linenoiseFree(void *ptr) {
1075     free(ptr);
1076 }
1077 
1078 /* ================================ History ================================= */
1079 
1080 /* Free the history, but does not reset it. Only used when we have to
1081  * exit() to avoid memory leaks are reported by valgrind & co. */
1082 static void freeHistory(void) {
1083     if (history) {
1084         int j;
1085 
1086         for (j = 0; j < history_len; j++)
1087             free(history[j]);
1088         free(history);
1089     }
1090 }
1091 
1092 /* At exit we'll try to fix the terminal to the initial conditions. */
1093 static void linenoiseAtExit(void) {
1094     disableRawMode(STDIN_FILENO);
1095     freeHistory();
1096 }
1097 
1098 /* This is the API call to add a new entry in the linenoise history.
1099  * It uses a fixed array of char pointers that are shifted (memmoved)
1100  * when the history max length is reached in order to remove the older
1101  * entry and make room for the new one, so it is not exactly suitable for huge
1102  * histories, but will work well for a few hundred of entries.
1103  *
1104  * Using a circular buffer is smarter, but a bit more complex to handle. */
1105 int linenoiseHistoryAdd(const char *line) {
1106     char *linecopy;
1107 
1108     if (history_max_len == 0) return 0;
1109 
1110     /* Initialization on first call. */
1111     if (history == NULL) {
1112         history = malloc(sizeof(char*)*history_max_len);
1113         if (history == NULL) return 0;
1114         memset(history,0,(sizeof(char*)*history_max_len));
1115     }
1116 
1117     /* Don't add duplicated lines. */
1118     if (history_len && !strcmp(history[history_len-1], line)) return 0;
1119 
1120     /* Add an heap allocated copy of the line in the history.
1121      * If we reached the max length, remove the older line. */
1122     linecopy = strdup(line);
1123     if (!linecopy) return 0;
1124     if (history_len == history_max_len) {
1125         free(history[0]);
1126         memmove(history,history+1,sizeof(char*)*(history_max_len-1));
1127         history_len--;
1128     }
1129     history[history_len] = linecopy;
1130     history_len++;
1131     return 1;
1132 }
1133 
1134 /* Set the maximum length for the history. This function can be called even
1135  * if there is already some history, the function will make sure to retain
1136  * just the latest 'len' elements if the new history length value is smaller
1137  * than the amount of items already inside the history. */
1138 int linenoiseHistorySetMaxLen(int len) {
1139     char **new;
1140 
1141     if (len < 1) return 0;
1142     if (history) {
1143         int tocopy = history_len;
1144 
1145         new = malloc(sizeof(char*)*len);
1146         if (new == NULL) return 0;
1147 
1148         /* If we can't copy everything, free the elements we'll not use. */
1149         if (len < tocopy) {
1150             int j;
1151 
1152             for (j = 0; j < tocopy-len; j++) free(history[j]);
1153             tocopy = len;
1154         }
1155         memset(new,0,sizeof(char*)*len);
1156         memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
1157         free(history);
1158         history = new;
1159     }
1160     history_max_len = len;
1161     if (history_len > history_max_len)
1162         history_len = history_max_len;
1163     return 1;
1164 }
1165 
1166 /* Save the history in the specified file. On success 0 is returned
1167  * otherwise -1 is returned. */
1168 int linenoiseHistorySave(const char *filename) {
1169     mode_t old_umask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
1170     FILE *fp;
1171     int j;
1172 
1173     fp = fopen(filename,"w");
1174     umask(old_umask);
1175     if (fp == NULL) return -1;
1176     chmod(filename,S_IRUSR|S_IWUSR);
1177     for (j = 0; j < history_len; j++)
1178         fprintf(fp,"%s\n",history[j]);
1179     fclose(fp);
1180     return 0;
1181 }
1182 
1183 /* Load the history from the specified file. If the file does not exist
1184  * zero is returned and no operation is performed.
1185  *
1186  * If the file exists and the operation succeeded 0 is returned, otherwise
1187  * on error -1 is returned. */
1188 int linenoiseHistoryLoad(const char *filename) {
1189     FILE *fp = fopen(filename,"r");
1190     char buf[LINENOISE_MAX_LINE];
1191 
1192     if (fp == NULL) return -1;
1193 
1194     while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
1195         char *p;
1196 
1197         p = strchr(buf,'\r');
1198         if (!p) p = strchr(buf,'\n');
1199         if (p) *p = '\0';
1200         linenoiseHistoryAdd(buf);
1201     }
1202     fclose(fp);
1203     return 0;
1204 }