linenoise.c revision 199767f8919635c4928607450d9e0abb932109ce
/* linenoise.c -- VERSION 1.0
*
* Guerrilla line editing library against the idea that a line editing lib
* needs to be 20,000 lines of C code.
*
* You can find the latest source code at:
*
*
* Does a number of crazy assumptions that happen to be true in 99.9999% of
* the 2010 UNIX computers around.
*
* ------------------------------------------------------------------------
*
* Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ------------------------------------------------------------------------
*
* References:
*
* Todo list:
* - Filter bogus Ctrl+<char> combinations.
* - Win32 support
*
* Bloat:
* - History search like Ctrl+r in readline?
*
* List of escape sequences used by this program, we do everything just
* with three sequences. In order to be so cheap we may have some
* flickering effect with some slow terminal, but the lesser sequences
* the more compatible.
*
* EL (Erase Line)
* Sequence: ESC [ n K
* Effect: if n is 0 or missing, clear from cursor to end of line
* Effect: if n is 1, clear from beginning of line to cursor
* Effect: if n is 2, clear entire line
*
* CUF (CUrsor Forward)
* Sequence: ESC [ n C
* Effect: moves cursor forward n chars
*
* CUB (CUrsor Backward)
* Sequence: ESC [ n D
* Effect: moves cursor backward n chars
*
* The following is used to get the terminal width if getting
* the width with the TIOCGWINSZ ioctl fails
*
* DSR (Device Status Report)
* Sequence: ESC [ 6 n
* Effect: reports the current cusor position as ESC [ n ; m R
* where n is the row and m is the column
*
* When multi line mode is enabled, we also use an additional escape
* sequence. However multi line editing is disabled by default.
*
* CUU (Cursor Up)
* Sequence: ESC [ n A
* Effect: moves cursor up of n chars.
*
* CUD (Cursor Down)
* Sequence: ESC [ n B
* Effect: moves cursor down of n chars.
*
* When linenoiseClearScreen() is called, two additional escape sequences
* are used in order to clear the screen and position the cursor at home
* position.
*
* CUP (Cursor position)
* Sequence: ESC [ H
* Effect: moves the cursor to upper left corner
*
* ED (Erase display)
* Sequence: ESC [ 2 J
* Effect: clear the whole screen
*
*/
#include <stand.h>
#include "linenoise.h"
#include "bootstrap.h"
#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
#define LINENOISE_MAX_LINE 256
static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
static int history_len = 0;
/* The linenoiseState structure represents the state during line editing.
* We pass this state to functions implementing specific editing
* functionalities. */
struct linenoiseState {
char *buf; /* Edited line buffer. */
const char *prompt; /* Prompt to display. */
int history_index; /* The history index we are currently editing. */
};
enum KEY_ACTION{
KEY_NULL = 0, /* NULL */
};
static void refreshLine(struct linenoiseState *l);
/* ======================= Low level terminal handling ====================== */
static int
{
int i;
if (s == NULL)
return -1;
for (i = 0; i < len; i++)
putchar(s[i]);
return (i);
}
/* Set if to use or not the multi line mode. */
void linenoiseSetMultiLine(int ml) {
}
/* Clear the screen. Used to handle ctrl+l */
void linenoiseClearScreen(void) {
/* nothing to do, just to avoid warning. */
}
}
static int
getColumns(void)
{
return (80);
}
/* Beep, used for completion when there is nothing to complete or when all
* the choices were already shown. */
static void linenoiseBeep(void) {
}
/* ============================== Completion ================================ */
/* Free a list of completion option populated by linenoiseAddCompletion(). */
size_t i;
}
/* This is an helper function for linenoiseEdit() and is called when the
* user types the <tab> key in order to complete the string currently in the
* input.
*
* The state of the editing is encapsulated into the pointed linenoiseState
* structure as described in the structure definition. */
int nwritten;
char c = 0;
} else {
while(!stop) {
/* Show completion or original buffer */
} else {
}
c = getchar();
if (c <= 0) {
return -1;
}
switch(c) {
case 9: /* tab */
break;
case 27: /* escape */
/* Re-show original buffer */
stop = 1;
break;
default:
/* Update buffer and return */
}
stop = 1;
break;
}
}
}
return c; /* Return last read character */
}
/* Register a callback function to be called for tab-completion. */
}
/* This function is used by the callback function registered by the user
* in order to add completion options given the input string when the
* user typed <tab>. See the example.c source code for a very easy to
* understand example. */
return;
}
}
/* =========================== Line editing ================================= */
/* We define a very simple "append buffer" structure, that is an heap
* allocated string where we can append to. This is useful in order to
* write all the escape sequences in a buffer and flush them to the standard
* output in a single call, to avoid flickering effects. */
struct abuf {
char *b;
int len;
};
}
}
}
/* Single line low level line refresh.
*
* Rewrite the currently edited line accordingly to the buffer content,
* cursor position, and number of columns of the terminal. */
static void refreshSingleLine(struct linenoiseState *l) {
char seq[64];
buf++;
len--;
pos--;
}
len--;
}
/* Cursor to left edge */
/* Write the prompt and the current buffer content */
/* Erase to right */
/* Move cursor to original position. */
}
/* Multi line low level line refresh.
*
* Rewrite the currently edited line accordingly to the buffer content,
* cursor position, and number of columns of the terminal. */
static void refreshMultiLine(struct linenoiseState *l) {
char seq[64];
int rpos2; /* rpos after refresh. */
int col; /* colum position, zero-based. */
int j;
/* Update maxrows if needed. */
/* First step: clear all the lines used before. To do so start by
* going to the last row. */
}
/* Now for every row clear it, go up. */
for (j = 0; j < old_rows-1; j++) {
}
/* Clean the top line. */
/* Write the prompt and the current buffer content */
/* If we are at the very end of the screen with our prompt, we need to
* emit a newline and move the prompt to the first column. */
if (l->pos &&
{
rows++;
}
/* Move cursor to right position. */
/* Go up till we reach the expected positon. */
}
/* Set column. */
if (col)
else
}
/* Calls the two low level functions refreshSingleLine() or
* refreshMultiLine() according to the selected mode. */
static void refreshLine(struct linenoiseState *l) {
if (mlmode)
refreshMultiLine(l);
else
}
/* Insert the character 'c' at cursor current position.
*
* On error writing to the terminal -1 is returned, otherwise 0. */
static int
linenoiseEditInsert(struct linenoiseState *l, char c) {
l->pos++;
l->len++;
/* Avoid a full update of the line in the
* trivial case. */
putchar(c);
} else {
refreshLine(l);
}
} else {
l->len++;
l->pos++;
refreshLine(l);
}
}
return 0;
}
/* Move cursor on the left. */
static void
linenoiseEditMoveLeft(struct linenoiseState *l) {
if (l->pos > 0) {
l->pos--;
refreshLine(l);
}
}
/* Move cursor on the right. */
static void
linenoiseEditMoveRight(struct linenoiseState *l) {
l->pos++;
refreshLine(l);
}
}
/* Move cursor to the start of the line. */
static void
linenoiseEditMoveHome(struct linenoiseState *l) {
if (l->pos != 0) {
l->pos = 0;
refreshLine(l);
}
}
/* Move cursor to the end of the line. */
static void
linenoiseEditMoveEnd(struct linenoiseState *l) {
refreshLine(l);
}
}
/* Substitute the currently edited line with the next or previous history
* entry as specified by 'dir'. */
#define LINENOISE_HISTORY_NEXT 0
#define LINENOISE_HISTORY_PREV 1
static void
if (history_len > 1) {
/* Update the current history entry before to
* overwrite it with the next one. */
/* Show the new entry */
if (l->history_index < 0) {
l->history_index = 0;
return;
} else if (l->history_index >= history_len) {
return;
}
refreshLine(l);
}
}
/* Delete the character at the right of the cursor without altering the cursor
* position. Basically this is what happens with the "Delete" keyboard key. */
static void
linenoiseEditDelete(struct linenoiseState *l) {
l->len--;
refreshLine(l);
}
}
/* Backspace implementation. */
static void
linenoiseEditBackspace(struct linenoiseState *l) {
l->pos--;
l->len--;
refreshLine(l);
}
}
/* Delete the previosu word, maintaining the cursor at the start of the
* current word. */
static void
linenoiseEditDeletePrevWord(struct linenoiseState *l) {
l->pos--;
l->pos--;
refreshLine(l);
}
/* This function is the core of the line editing capability of linenoise.
* It expects 'fd' to be already in "raw mode" so that every key pressed
* will be returned ASAP to read().
*
* The resulting string is put into 'buf' when the user type enter, or
* when ctrl+d is typed.
*
* The function returns the length of the current buffer. */
{
struct linenoiseState l;
/* Populate the linenoise state that we pass to functions implementing
* specific editing functionalities. */
l.len = 0;
l.cols = getColumns();
l.maxrows = 0;
l.history_index = 0;
/* Buffer starts empty. */
l.buf[0] = '\0';
l.buflen--; /* Make sure there is always space for the nulterm */
/* The latest history entry is always our current buffer, that
* initially is just an empty string. */
linenoiseHistoryAdd("");
while(1) {
char c;
char seq[3];
c = getchar();
if (c == -1)
continue;
/* Only autocomplete when the callback is set. It returns < 0 when
* there was an error reading from fd. Otherwise it will return the
* character that should be handled next. */
c = completeLine(&l);
/* Return on errors */
if (c < 0) return l.len;
/* Read next character when 0 */
if (c == 0) continue;
}
switch(c) {
case ENTER: /* enter */
history_len--;
if (mlmode) linenoiseEditMoveEnd(&l);
return (int)l.len;
case CTRL_C: /* ctrl-c */
buf[0] = '\0';
refreshLine(&l);
case BACKSPACE: /* backspace */
case 8: /* ctrl-h */
break;
case CTRL_D: /* ctrl-d, remove char at right of cursor. */
if (l.len > 0) {
linenoiseEditDelete(&l);
}
break;
case CTRL_T: /* ctrl-t, swaps current character with previous. */
refreshLine(&l);
}
break;
case CTRL_B: /* ctrl-b */
break;
case CTRL_F: /* ctrl-f */
break;
case CTRL_P: /* ctrl-p */
break;
case CTRL_N: /* ctrl-n */
break;
case ESC: /* escape sequence */
/* Read the next two bytes representing the escape sequence.
* Use two calls to handle slow terminals returning the two
* chars at different times. */
/* ESC [ sequences. */
if (seq[0] == '[') {
/* Extended escape, read additional byte. */
switch(seq[1]) {
case '3': /* Delete key. */
linenoiseEditDelete(&l);
break;
}
}
} else {
switch(seq[1]) {
case 'A': /* Up */
break;
case 'B': /* Down */
break;
case 'C': /* Right */
break;
case 'D': /* Left */
break;
case 'H': /* Home */
break;
case 'F': /* End*/
linenoiseEditMoveEnd(&l);
break;
}
}
}
/* ESC O sequences. */
else if (seq[0] == 'O') {
switch(seq[1]) {
case 'H': /* Home */
break;
case 'F': /* End*/
linenoiseEditMoveEnd(&l);
break;
}
}
break;
default:
if (linenoiseEditInsert(&l,c)) return -1;
break;
case CTRL_U: /* Ctrl+u, delete the whole line. */
buf[0] = '\0';
refreshLine(&l);
break;
case CTRL_K: /* Ctrl+k, delete from current to end of line. */
refreshLine(&l);
break;
case CTRL_A: /* Ctrl+a, go to the start of the line */
break;
case CTRL_E: /* ctrl+e, go to the end of the line */
linenoiseEditMoveEnd(&l);
break;
case CTRL_L: /* ctrl+l, clear screen */
refreshLine(&l);
break;
case CTRL_W: /* ctrl+w, delete previous word */
break;
}
}
return l.len;
}
/* The high level function that is the main API of the linenoise library.
* This function checks if the terminal has basic capabilities, just checking
* for a blacklist of stupid terminals, and later either calls the line
* editing function or uses dummy fgets() so that you will be able to type
* something even in the most desperate of the conditions. */
char buf[LINENOISE_MAX_LINE];
int count;
cons_mode(0);
printf("\n");
}
/* ================================ History ================================= */
/* This is the API call to add a new entry in the linenoise history.
* It uses a fixed array of char pointers that are shifted (memmoved)
* when the history max length is reached in order to remove the older
* entry and make room for the new one, so it is not exactly suitable for huge
* histories, but will work well for a few hundred of entries.
*
* Using a circular buffer is smarter, but a bit more complex to handle. */
int linenoiseHistoryAdd(const char *line) {
char *linecopy;
if (history_max_len == 0) return 0;
/* Initialization on first call. */
}
/* Don't add duplicated lines. */
/* Add an heap allocated copy of the line in the history.
* If we reached the max length, remove the older line. */
if (!linecopy) return 0;
if (history_len == history_max_len) {
history_len--;
}
history_len++;
return 1;
}
/* Set the maximum length for the history. This function can be called even
* if there is already some history, the function will make sure to retain
* just the latest 'len' elements if the new history length value is smaller
* than the amount of items already inside the history. */
int linenoiseHistorySetMaxLen(int len) {
char **new;
if (len < 1) return 0;
if (history) {
int tocopy = history_len;
/* If we can't copy everything, free the elements we'll not use. */
int j;
}
}
if (history_len > history_max_len)
return 1;
}