#ifdef _WIN32
#include <windows.h>
#include <fcntl.h>
#define USE_WINCONSOLE
#ifdef __MINGW32__
#define HAVE_UNISTD_H
#endif
#else
#include <termios.h>
#include <sys/ioctl.h>
#include <poll.h>
#define USE_TERMIOS
#define HAVE_UNISTD_H
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#if defined(_WIN32) && !defined(__MINGW32__)
#define strdup _strdup
#define snprintf _snprintf
#endif
#include "linenoise.h"
#ifndef STRINGBUF_H
#include "stringbuf.h"
#endif
#ifndef UTF8_UTIL_H
#include "utf8.h"
#endif
#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
#define ctrl(C) ((C) - '@')
#define meta(C) ((C) | 0x80)
enum {
SPECIAL_NONE,
SPECIAL_UP = -20,
SPECIAL_DOWN = -21,
SPECIAL_LEFT = -22,
SPECIAL_RIGHT = -23,
SPECIAL_DELETE = -24,
SPECIAL_HOME = -25,
SPECIAL_END = -26,
SPECIAL_INSERT = -27,
SPECIAL_PAGE_UP = -28,
SPECIAL_PAGE_DOWN = -29,
CHAR_ESCAPE = 27,
CHAR_DELETE = 127,
};
static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
static int history_len = 0;
static int history_index = 0;
static char **history = NULL;
struct current {
stringbuf *buf;
int pos;
int cols;
int nrows;
int rpos;
int colsright;
int colsleft;
const char *prompt;
stringbuf *capture;
stringbuf *output;
#if defined(USE_TERMIOS)
int fd;
int pending;
#elif defined(USE_WINCONSOLE)
HANDLE outh;
HANDLE inh;
int rows;
int x;
int y;
#ifdef USE_UTF8
#define UBUF_MAX_CHARS 132
WORD ubuf[UBUF_MAX_CHARS + 1];
int ubuflen;
int ubufcols;
#endif
#endif
};
static int fd_read(struct current *current);
static int getWindowSize(struct current *current);
static void cursorDown(struct current *current, int n);
static void cursorUp(struct current *current, int n);
static void eraseEol(struct current *current);
static void refreshLine(struct current *current);
static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos);
static void setCursorPos(struct current *current, int x);
static void setOutputHighlight(struct current *current, const int *props, int nprops);
static void set_current(struct current *current, const char *str);
static int fd_isatty(struct current *current)
{
#ifdef USE_TERMIOS
return isatty(current->fd);
#else
(void)current;
return 0;
#endif
}
void linenoiseHistoryFree(void) {
if (history) {
int j;
for (j = 0; j < history_len; j++)
free(history[j]);
free(history);
history = NULL;
history_len = 0;
}
}
typedef enum {
EP_START,
EP_ESC,
EP_DIGITS,
EP_PROPS,
EP_END,
EP_ERROR,
} ep_state_t;
struct esc_parser {
ep_state_t state;
int props[5];
int maxprops;
int numprops;
int termchar;
int current;
};
static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
{
parser->state = EP_START;
parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
parser->numprops = 0;
parser->current = 0;
parser->termchar = termchar;
}
static int parseEscapeSequence(struct esc_parser *parser, int ch)
{
switch (parser->state) {
case EP_START:
parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
break;
case EP_ESC:
parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
break;
case EP_PROPS:
if (ch == ';') {
parser->state = EP_DIGITS;
donedigits:
if (parser->numprops + 1 < parser->maxprops) {
parser->props[parser->numprops++] = parser->current;
parser->current = 0;
}
break;
}
case EP_DIGITS:
if (ch >= '0' && ch <= '9') {
parser->current = parser->current * 10 + (ch - '0');
parser->state = EP_PROPS;
break;
}
if (parser->termchar != ch) {
if (parser->termchar != 0 || !((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
parser->state = EP_ERROR;
break;
}
}
parser->state = EP_END;
goto donedigits;
case EP_END:
parser->state = EP_ERROR;
break;
case EP_ERROR:
break;
}
return parser->state;
}
#ifdef DEBUG_REFRESHLINE
#define DRL(ARGS...) fprintf(dfh, ARGS)
static FILE *dfh;
static void DRL_CHAR(int ch)
{
if (ch < ' ') {
DRL("^%c", ch + '@');
}
else if (ch > 127) {
DRL("\\u%04x", ch);
}
else {
DRL("%c", ch);
}
}
static void DRL_STR(const char *str)
{
while (*str) {
int ch;
int n = utf8_tounicode(str, &ch);
str += n;
DRL_CHAR(ch);
}
}
#else
#define DRL(...)
#define DRL_CHAR(ch)
#define DRL_STR(str)
#endif
#if defined(USE_WINCONSOLE)
#include "linenoise-win32.c"
#endif
#if defined(USE_TERMIOS)
static void linenoiseAtExit(void);
static struct termios orig_termios;
static int rawmode = 0;
static int atexit_registered = 0;
static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
static int isUnsupportedTerm(void) {
char *term = getenv("TERM");
if (term) {
int j;
for (j = 0; unsupported_term[j]; j++) {
if (strcmp(term, unsupported_term[j]) == 0) {
return 1;
}
}
}
return 0;
}
static int enableRawMode(struct current *current) {
struct termios raw;
current->fd = STDIN_FILENO;
current->cols = 0;
if (!isatty(current->fd) || isUnsupportedTerm() ||
tcgetattr(current->fd, &orig_termios) == -1) {
fatal:
errno = ENOTTY;
return -1;
}
if (!atexit_registered) {
atexit(linenoiseAtExit);
atexit_registered = 1;
}
raw = orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0;
if (tcsetattr(current->fd,TCSANOW,&raw) < 0) {
goto fatal;
}
rawmode = 1;
return 0;
}
static void disableRawMode(struct current *current) {
if (rawmode && tcsetattr(current->fd,TCSANOW,&orig_termios) != -1)
rawmode = 0;
}
static void linenoiseAtExit(void) {
if (rawmode) {
tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios);
}
linenoiseHistoryFree();
}
#define IGNORE_RC(EXPR) if (EXPR) {}
static void outputChars(struct current *current, const char *buf, int len)
{
if (len < 0) {
len = strlen(buf);
}
if (current->output) {
sb_append_len(current->output, buf, len);
}
else {
IGNORE_RC(write(current->fd, buf, len));
}
}
static void outputFormatted(struct current *current, const char *format, ...)
{
va_list args;
char buf[64];
int n;
va_start(args, format);
n = vsnprintf(buf, sizeof(buf), format, args);
assert(n < (int)sizeof(buf));
va_end(args);
outputChars(current, buf, n);
}
static void cursorToLeft(struct current *current)
{
outputChars(current, "\r", -1);
}
static void setOutputHighlight(struct current *current, const int *props, int nprops)
{
outputChars(current, "\x1b[", -1);
while (nprops--) {
outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
props++;
}
}
static void eraseEol(struct current *current)
{
outputChars(current, "\x1b[0K", -1);
}
static void setCursorPos(struct current *current, int x)
{
if (x == 0) {
cursorToLeft(current);
}
else {
outputFormatted(current, "\r\x1b[%dC", x);
}
}
static void cursorUp(struct current *current, int n)
{
if (n) {
outputFormatted(current, "\x1b[%dA", n);
}
}
static void cursorDown(struct current *current, int n)
{
if (n) {
outputFormatted(current, "\x1b[%dB", n);
}
}
void linenoiseClearScreen(void)
{
IGNORE_RC(write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7));
}
static int fd_read_char(struct current *current, int timeout)
{
struct pollfd p;
unsigned char c;
if (current->pending) {
c = current->pending;
current->pending = 0;
return c;
}
p.fd = current->fd;
p.events = POLLIN;
if (poll(&p, 1, timeout) == 0) {
return -1;
}
if (read(current->fd, &c, 1) != 1) {
return -1;
}
return c;
}
static int fd_read(struct current *current)
{
#ifdef USE_UTF8
char buf[MAX_UTF8_LEN];
int n;
int i;
int c;
if (current->pending) {
buf[0] = current->pending;
current->pending = 0;
}
else if (read(current->fd, &buf[0], 1) != 1) {
return -1;
}
n = utf8_charlen(buf[0]);
if (n < 1) {
return -1;
}
for (i = 1; i < n; i++) {
if (read(current->fd, &buf[i], 1) != 1) {
return -1;
}
}
utf8_tounicode(buf, &c);
return c;
#else
return fd_read_char(current, -1);
#endif
}
static int queryCursor(struct current *current, int* cols)
{
struct esc_parser parser;
int ch;
static int query_cursor_failed;
if (query_cursor_failed) {
return 0;
}
assert(current->output == NULL);
outputChars(current, "\x1b[6n", -1);
initParseEscapeSeq(&parser, 'R');
while ((ch = fd_read_char(current, 100)) > 0) {
switch (parseEscapeSequence(&parser, ch)) {
default:
continue;
case EP_END:
if (parser.numprops == 2 && parser.props[1] < 1000) {
*cols = parser.props[1];
return 1;
}
break;
case EP_ERROR:
current->pending = ch;
break;
}
break;
}
query_cursor_failed = 1;
return 0;
}
static int getWindowSize(struct current *current)
{
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
current->cols = ws.ws_col;
return 0;
}
if (current->cols == 0) {
int here;
current->cols = 80;
if (queryCursor (current, &here)) {
setCursorPos(current, 999);
if (queryCursor (current, ¤t->cols)) {
if (current->cols > here) {
setCursorPos(current, here);
}
}
}
}
return 0;
}
static int check_special(struct current *current)
{
int c = fd_read_char(current, 50);
int c2;
if (c < 0) {
return CHAR_ESCAPE;
}
else if (c >= 'a' && c <= 'z') {
return meta(c);
}
c2 = fd_read_char(current, 50);
if (c2 < 0) {
return c2;
}
if (c == '[' || c == 'O') {
switch (c2) {
case 'A':
return SPECIAL_UP;
case 'B':
return SPECIAL_DOWN;
case 'C':
return SPECIAL_RIGHT;
case 'D':
return SPECIAL_LEFT;
case 'F':
return SPECIAL_END;
case 'H':
return SPECIAL_HOME;
}
}
if (c == '[' && c2 >= '1' && c2 <= '8') {
c = fd_read_char(current, 50);
if (c == '~') {
switch (c2) {
case '2':
return SPECIAL_INSERT;
case '3':
return SPECIAL_DELETE;
case '5':
return SPECIAL_PAGE_UP;
case '6':
return SPECIAL_PAGE_DOWN;
case '7':
return SPECIAL_HOME;
case '8':
return SPECIAL_END;
}
}
while (c != -1 && c != '~') {
c = fd_read_char(current, 50);
}
}
return SPECIAL_NONE;
}
#endif
static void clearOutputHighlight(struct current *current)
{
int nohighlight = 0;
setOutputHighlight(current, &nohighlight, 1);
}
static void outputControlChar(struct current *current, char ch)
{
int reverse = 7;
setOutputHighlight(current, &reverse, 1);
outputChars(current, "^", 1);
outputChars(current, &ch, 1);
clearOutputHighlight(current);
}
#ifndef utf8_getchars
static int utf8_getchars(char *buf, int c)
{
#ifdef USE_UTF8
return utf8_fromunicode(buf, c);
#else
*buf = c;
return 1;
#endif
}
#endif
static int get_char(struct current *current, int pos)
{
if (pos >= 0 && pos < sb_chars(current->buf)) {
int c;
int i = utf8_index(sb_str(current->buf), pos);
(void)utf8_tounicode(sb_str(current->buf) + i, &c);
return c;
}
return -1;
}
static int char_display_width(int ch)
{
if (ch < ' ') {
return 2;
}
else {
return utf8_width(ch);
}
}
#ifndef NO_COMPLETION
static linenoiseCompletionCallback *completionCallback = NULL;
static void *completionUserdata = NULL;
static int showhints = 1;
static linenoiseHintsCallback *hintsCallback = NULL;
static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
static void *hintsUserdata = NULL;
static void beep(void) {
#ifdef USE_TERMIOS
fprintf(stderr, "\x7");
fflush(stderr);
#endif
}
static void freeCompletions(linenoiseCompletions *lc) {
size_t i;
for (i = 0; i < lc->len; i++)
free(lc->cvec[i]);
free(lc->cvec);
}
static int completeLine(struct current *current) {
linenoiseCompletions lc = { 0, NULL };
int c = 0;
completionCallback(sb_str(current->buf),&lc,completionUserdata);
if (lc.len == 0) {
beep();
} else {
size_t stop = 0, i = 0;
while(!stop) {
if (i < lc.len) {
int chars = utf8_strlen(lc.cvec[i], -1);
refreshLineAlt(current, current->prompt, lc.cvec[i], chars);
} else {
refreshLine(current);
}
c = fd_read(current);
if (c == -1) {
break;
}
switch(c) {
case '\t':
i = (i+1) % (lc.len+1);
if (i == lc.len) beep();
break;
case CHAR_ESCAPE:
if (i < lc.len) {
refreshLine(current);
}
stop = 1;
break;
default:
if (i < lc.len) {
set_current(current,lc.cvec[i]);
}
stop = 1;
break;
}
}
}
freeCompletions(&lc);
return c;
}
linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
linenoiseCompletionCallback * old = completionCallback;
completionCallback = fn;
completionUserdata = userdata;
return old;
}
void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
lc->cvec[lc->len++] = strdup(str);
}
void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
{
hintsCallback = callback;
hintsUserdata = userdata;
}
void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
{
freeHintsCallback = callback;
}
#endif
static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
{
int needcols = 0;
int pos = 0;
int new_cursor_pos = *cursor_pos;
const char *pt = buf;
DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);
while (*pt) {
int ch;
int n = utf8_tounicode(pt, &ch);
pt += n;
needcols += char_display_width(ch);
while (needcols >= availcols - 3) {
n = utf8_tounicode(buf, &ch);
buf += n;
needcols -= char_display_width(ch);
DRL_CHAR(ch);
new_cursor_pos--;
if (buf == pt) {
break;
}
}
if (pos++ == *cursor_pos) {
break;
}
}
DRL("<snip>");
DRL_STR(buf);
DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);
*cursor_pos = new_cursor_pos;
return buf;
}
static int mlmode = 0;
void linenoiseSetMultiLine(int enableml)
{
mlmode = enableml;
}
static int refreshShowHints(struct current *current, const char *buf, int availcols, int display)
{
int rc = 0;
if (showhints && hintsCallback && availcols > 0) {
int bold = 0;
int color = -1;
char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
if (hint) {
rc = 1;
if (display) {
const char *pt;
if (bold == 1 && color == -1) color = 37;
if (bold || color > 0) {
int props[3] = { bold, color, 49 };
setOutputHighlight(current, props, 3);
}
DRL("<hint bold=%d,color=%d>", bold, color);
pt = hint;
while (*pt) {
int ch;
int n = utf8_tounicode(pt, &ch);
int width = char_display_width(ch);
if (width >= availcols) {
DRL("<hinteol>");
break;
}
DRL_CHAR(ch);
availcols -= width;
outputChars(current, pt, n);
pt += n;
}
if (bold || color > 0) {
clearOutputHighlight(current);
}
if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
}
}
}
return rc;
}
#ifdef USE_TERMIOS
static void refreshStart(struct current *current)
{
assert(current->output == NULL);
current->output = sb_alloc();
}
static void refreshEnd(struct current *current)
{
IGNORE_RC(write(current->fd, sb_str(current->output), sb_len(current->output)));
sb_free(current->output);
current->output = NULL;
}
static void refreshStartChars(struct current *current)
{
(void)current;
}
static void refreshNewline(struct current *current)
{
DRL("<nl>");
outputChars(current, "\n", 1);
}
static void refreshEndChars(struct current *current)
{
(void)current;
}
#endif
static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
{
int i;
const char *pt;
int displaycol;
int displayrow;
int visible;
int currentpos;
int notecursor;
int cursorcol = 0;
int cursorrow = 0;
int hint;
struct esc_parser parser;
#ifdef DEBUG_REFRESHLINE
dfh = fopen("linenoise.debuglog", "a");
#endif
getWindowSize(current);
refreshStart(current);
DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);
cursorDown(current, current->nrows - current->rpos - 1);
DRL("<cud=%d>", current->nrows - current->rpos - 1);
for (i = 0; i < current->nrows; i++) {
if (i) {
DRL("<cup>");
cursorUp(current, 1);
}
DRL("<clearline>");
cursorToLeft(current);
eraseEol(current);
}
DRL("\n");
pt = prompt;
displaycol = 0;
displayrow = 0;
visible = 1;
refreshStartChars(current);
while (*pt) {
int width;
int ch;
int n = utf8_tounicode(pt, &ch);
if (visible && ch == CHAR_ESCAPE) {
visible = 0;
initParseEscapeSeq(&parser, 'm');
DRL("<esc-seq-start>");
}
if (ch == '\n' || ch == '\r') {
refreshNewline(current);
displaycol = 0;
displayrow++;
}
else {
width = visible * utf8_width(ch);
displaycol += width;
if (displaycol >= current->cols) {
refreshNewline(current);
displaycol = width;
displayrow++;
}
DRL_CHAR(ch);
#ifdef USE_WINCONSOLE
if (visible) {
outputChars(current, pt, n);
}
#else
outputChars(current, pt, n);
#endif
}
pt += n;
if (!visible) {
switch (parseEscapeSequence(&parser, ch)) {
case EP_END:
visible = 1;
setOutputHighlight(current, parser.props, parser.numprops);
DRL("<esc-seq-end,numprops=%d>", parser.numprops);
break;
case EP_ERROR:
DRL("<esc-seq-err>");
visible = 1;
break;
}
}
}
DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);
if (mlmode == 0) {
pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
}
else {
pt = buf;
}
currentpos = 0;
notecursor = -1;
while (*pt) {
int ch;
int n = utf8_tounicode(pt, &ch);
int width = char_display_width(ch);
if (currentpos == cursor_pos) {
notecursor = 1;
}
if (displaycol + width >= current->cols) {
if (mlmode == 0) {
DRL("<slmode>");
break;
}
refreshNewline(current);
displaycol = 0;
displayrow++;
}
if (notecursor == 1) {
cursorcol = displaycol;
cursorrow = displayrow;
notecursor = 0;
DRL("<cursor>");
}
displaycol += width;
if (ch < ' ') {
outputControlChar(current, ch + '@');
}
else {
outputChars(current, pt, n);
}
DRL_CHAR(ch);
if (width != 1) {
DRL("<w=%d>", width);
}
pt += n;
currentpos++;
}
if (notecursor) {
DRL("<cursor>");
cursorcol = displaycol;
cursorrow = displayrow;
}
DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n", displaycol, displayrow, cursorcol, cursorrow);
hint = refreshShowHints(current, buf, current->cols - displaycol, 1);
if (prompt == current->prompt && hint == 0) {
current->colsright = current->cols - displaycol;
current->colsleft = displaycol;
}
else {
current->colsright = 0;
current->colsleft = 0;
}
DRL("\nafter hints: colsleft=%d, colsright=%d\n\n", current->colsleft, current->colsright);
refreshEndChars(current);
cursorUp(current, displayrow - cursorrow);
setCursorPos(current, cursorcol);
if (displayrow >= current->nrows) {
current->nrows = displayrow + 1;
}
current->rpos = cursorrow;
refreshEnd(current);
#ifdef DEBUG_REFRESHLINE
fclose(dfh);
#endif
}
static void refreshLine(struct current *current)
{
refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
}
static void set_current(struct current *current, const char *str)
{
sb_clear(current->buf);
sb_append(current->buf, str);
current->pos = sb_chars(current->buf);
}
static int remove_char(struct current *current, int pos)
{
if (pos >= 0 && pos < sb_chars(current->buf)) {
int offset = utf8_index(sb_str(current->buf), pos);
int nbytes = utf8_index(sb_str(current->buf) + offset, 1);
int rc = 1;
if (current->output && current->pos == pos + 1 && current->pos == sb_chars(current->buf) && pos > 0) {
#ifdef USE_UTF8
char last = sb_str(current->buf)[offset];
#else
char last = 0;
#endif
if (current->colsleft > 0 && (last & 0x80) == 0) {
current->colsleft--;
current->colsright++;
rc = 2;
}
}
sb_delete(current->buf, offset, nbytes);
if (current->pos > pos) {
current->pos--;
}
if (rc == 2) {
if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
rc = 1;
}
else {
outputChars(current, "\b \b", 3);
}
}
return rc;
return 1;
}
return 0;
}
static int insert_char(struct current *current, int pos, int ch)
{
if (pos >= 0 && pos <= sb_chars(current->buf)) {
char buf[MAX_UTF8_LEN + 1];
int offset = utf8_index(sb_str(current->buf), pos);
int n = utf8_getchars(buf, ch);
int rc = 1;
buf[n] = 0;
if (current->output && pos == current->pos && pos == sb_chars(current->buf)) {
int width = char_display_width(ch);
if (current->colsright > width) {
current->colsright -= width;
current->colsleft -= width;
rc = 2;
}
}
sb_insert(current->buf, offset, buf);
if (current->pos >= pos) {
current->pos++;
}
if (rc == 2) {
if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
rc = 1;
}
else {
outputChars(current, buf, n);
}
}
return rc;
}
return 0;
}
static void capture_chars(struct current *current, int pos, int nchars)
{
if (pos >= 0 && (pos + nchars - 1) < sb_chars(current->buf)) {
int offset = utf8_index(sb_str(current->buf), pos);
int nbytes = utf8_index(sb_str(current->buf) + offset, nchars);
if (nbytes > 0) {
if (current->capture) {
sb_clear(current->capture);
}
else {
current->capture = sb_alloc();
}
sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
}
}
}
static int remove_chars(struct current *current, int pos, int n)
{
int removed = 0;
capture_chars(current, pos, n);
while (n-- && remove_char(current, pos)) {
removed++;
}
return removed;
}
static int insert_chars(struct current *current, int pos, const char *chars)
{
int inserted = 0;
while (*chars) {
int ch;
int n = utf8_tounicode(chars, &ch);
if (insert_char(current, pos, ch) == 0) {
break;
}
inserted++;
pos++;
chars += n;
}
return inserted;
}
static int skip_space_nonspace(struct current *current, int dir, int check_is_space)
{
int moved = 0;
int checkoffset = (dir < 0) ? -1 : 0;
int limit = (dir < 0) ? 0 : sb_chars(current->buf);
while (current->pos != limit && (get_char(current, current->pos + checkoffset) == ' ') == check_is_space) {
current->pos += dir;
moved++;
}
return moved;
}
static int skip_space(struct current *current, int dir)
{
return skip_space_nonspace(current, dir, 1);
}
static int skip_nonspace(struct current *current, int dir)
{
return skip_space_nonspace(current, dir, 0);
}
static void set_history_index(struct current *current, int new_index)
{
if (history_len > 1) {
free(history[history_len - 1 - history_index]);
history[history_len - 1 - history_index] = strdup(sb_str(current->buf));
history_index = new_index;
if (history_index < 0) {
history_index = 0;
} else if (history_index >= history_len) {
history_index = history_len - 1;
} else {
set_current(current, history[history_len - 1 - history_index]);
refreshLine(current);
}
}
}
static int reverseIncrementalSearch(struct current *current)
{
char rbuf[50];
char rprompt[80];
int rchars = 0;
int rlen = 0;
int searchpos = history_len - 1;
int c;
rbuf[0] = 0;
while (1) {
int n = 0;
const char *p = NULL;
int skipsame = 0;
int searchdir = -1;
snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
refreshLineAlt(current, rprompt, sb_str(current->buf), current->pos);
c = fd_read(current);
if (c == ctrl('H') || c == CHAR_DELETE) {
if (rchars) {
int p_ind = utf8_index(rbuf, --rchars);
rbuf[p_ind] = 0;
rlen = strlen(rbuf);
}
continue;
}
#ifdef USE_TERMIOS
if (c == CHAR_ESCAPE) {
c = check_special(current);
}
#endif
if (c == ctrl('R')) {
if (searchpos > 0) {
searchpos--;
}
skipsame = 1;
}
else if (c == ctrl('S')) {
if (searchpos < history_len) {
searchpos++;
}
searchdir = 1;
skipsame = 1;
}
else if (c == ctrl('P') || c == SPECIAL_UP) {
set_history_index(current, history_len - searchpos);
c = 0;
break;
}
else if (c == ctrl('N') || c == SPECIAL_DOWN) {
set_history_index(current, history_len - searchpos - 2);
c = 0;
break;
}
else if (c >= ' ' && c <= '~') {
if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
continue;
}
n = utf8_getchars(rbuf + rlen, c);
rlen += n;
rchars++;
rbuf[rlen] = 0;
searchpos = history_len - 1;
}
else {
break;
}
for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
p = strstr(history[searchpos], rbuf);
if (p) {
if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
continue;
}
history_index = history_len - 1 - searchpos;
set_current(current,history[searchpos]);
current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
break;
}
}
if (!p && n) {
rchars--;
rlen -= n;
rbuf[rlen] = 0;
}
}
if (c == ctrl('G') || c == ctrl('C')) {
set_current(current, "");
history_index = 0;
c = 0;
}
else if (c == ctrl('J')) {
history_index = 0;
c = 0;
}
refreshLine(current);
return c;
}
static int linenoiseEdit(struct current *current) {
history_index = 0;
refreshLine(current);
while(1) {
int c = fd_read(current);
#ifndef NO_COMPLETION
if (c == '\t' && current->pos == sb_chars(current->buf) && completionCallback != NULL) {
c = completeLine(current);
}
#endif
if (c == ctrl('R')) {
c = reverseIncrementalSearch(current);
}
#ifdef USE_TERMIOS
if (c == CHAR_ESCAPE) {
c = check_special(current);
}
#endif
if (c == -1) {
return sb_len(current->buf);
}
switch(c) {
case SPECIAL_NONE:
break;
case '\r':
case '\n':
history_len--;
free(history[history_len]);
current->pos = sb_chars(current->buf);
if (mlmode || hintsCallback) {
showhints = 0;
refreshLine(current);
showhints = 1;
}
return sb_len(current->buf);
case ctrl('C'):
errno = EAGAIN;
return -1;
case ctrl('Z'):
#ifdef SIGTSTP
disableRawMode(current);
raise(SIGTSTP);
enableRawMode(current);
refreshLine(current);
#endif
continue;
case CHAR_DELETE:
case ctrl('H'):
if (remove_char(current, current->pos - 1) == 1) {
refreshLine(current);
}
break;
case ctrl('D'):
if (sb_len(current->buf) == 0) {
history_len--;
free(history[history_len]);
return -1;
}
case SPECIAL_DELETE:
if (remove_char(current, current->pos) == 1) {
refreshLine(current);
}
break;
case SPECIAL_INSERT:
break;
case meta('b'):
if (skip_nonspace(current, -1)) {
refreshLine(current);
}
else if (skip_space(current, -1)) {
skip_nonspace(current, -1);
refreshLine(current);
}
break;
case meta('f'):
if (skip_space(current, 1)) {
refreshLine(current);
}
else if (skip_nonspace(current, 1)) {
skip_space(current, 1);
refreshLine(current);
}
break;
case ctrl('W'):
{
int pos = current->pos;
while (pos > 0 && get_char(current, pos - 1) == ' ') {
pos--;
}
while (pos > 0 && get_char(current, pos - 1) != ' ') {
pos--;
}
if (remove_chars(current, pos, current->pos - pos)) {
refreshLine(current);
}
}
break;
case ctrl('T'):
if (current->pos > 0 && current->pos <= sb_chars(current->buf)) {
int fixer = (current->pos == sb_chars(current->buf));
c = get_char(current, current->pos - fixer);
remove_char(current, current->pos - fixer);
insert_char(current, current->pos - 1, c);
refreshLine(current);
}
break;
case ctrl('V'):
if (insert_char(current, current->pos, c)) {
refreshLine(current);
c = fd_read(current);
remove_char(current, current->pos - 1);
if (c > 0) {
insert_char(current, current->pos, c);
}
refreshLine(current);
}
break;
case ctrl('B'):
case SPECIAL_LEFT:
if (current->pos > 0) {
current->pos--;
refreshLine(current);
}
break;
case ctrl('F'):
case SPECIAL_RIGHT:
if (current->pos < sb_chars(current->buf)) {
current->pos++;
refreshLine(current);
}
break;
case SPECIAL_PAGE_UP:
set_history_index(current, history_len - 1);
break;
case SPECIAL_PAGE_DOWN:
set_history_index(current, 0);
break;
case ctrl('P'):
case SPECIAL_UP:
set_history_index(current, history_index + 1);
break;
case ctrl('N'):
case SPECIAL_DOWN:
set_history_index(current, history_index - 1);
break;
case ctrl('A'):
case SPECIAL_HOME:
current->pos = 0;
refreshLine(current);
break;
case ctrl('E'):
case SPECIAL_END:
current->pos = sb_chars(current->buf);
refreshLine(current);
break;
case ctrl('U'):
if (remove_chars(current, 0, current->pos)) {
refreshLine(current);
}
break;
case ctrl('K'):
if (remove_chars(current, current->pos, sb_chars(current->buf) - current->pos)) {
refreshLine(current);
}
break;
case ctrl('Y'):
if (current->capture && insert_chars(current, current->pos, sb_str(current->capture))) {
refreshLine(current);
}
break;
case ctrl('L'):
linenoiseClearScreen();
current->cols = 0;
current->rpos = 0;
refreshLine(current);
break;
default:
if (c >= meta('a') && c <= meta('z')) {
break;
}
if (c == '\t' || c >= ' ') {
if (insert_char(current, current->pos, c) == 1) {
refreshLine(current);
}
}
break;
}
}
return sb_len(current->buf);
}
int linenoiseColumns(void)
{
struct current current;
current.output = NULL;
enableRawMode (¤t);
getWindowSize (¤t);
disableRawMode (¤t);
return current.cols;
}
static stringbuf *sb_getline(FILE *fh)
{
stringbuf *sb = sb_alloc();
int c;
int n = 0;
while ((c = getc(fh)) != EOF) {
char ch;
n++;
if (c == '\r') {
continue;
}
if (c == '\n' || c == '\r') {
break;
}
ch = c;
sb_append_len(sb, &ch, 1);
}
if (n == 0 || sb->data == NULL) {
sb_free(sb);
return NULL;
}
return sb;
}
char *linenoiseWithInitial(const char *prompt, const char *initial)
{
int count;
struct current current;
stringbuf *sb;
memset(¤t, 0, sizeof(current));
if (enableRawMode(¤t) == -1) {
printf("%s", prompt);
fflush(stdout);
sb = sb_getline(stdin);
if (sb && !fd_isatty(¤t)) {
printf("%s\n", sb_str(sb));
fflush(stdout);
}
}
else {
current.buf = sb_alloc();
current.pos = 0;
current.nrows = 1;
current.prompt = prompt;
linenoiseHistoryAdd(initial);
set_current(¤t, initial);
count = linenoiseEdit(¤t);
disableRawMode(¤t);
printf("\n");
sb_free(current.capture);
if (count == -1) {
sb_free(current.buf);
return NULL;
}
sb = current.buf;
}
return sb ? sb_to_string(sb) : NULL;
}
char *linenoise(const char *prompt)
{
return linenoiseWithInitial(prompt, "");
}
static int linenoiseHistoryAddAllocated(char *line) {
if (history_max_len == 0) {
notinserted:
free(line);
return 0;
}
if (history == NULL) {
history = (char **)calloc(sizeof(char*), history_max_len);
}
if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
goto notinserted;
}
if (history_len == history_max_len) {
free(history[0]);
memmove(history,history+1,sizeof(char*)*(history_max_len-1));
history_len--;
}
history[history_len] = line;
history_len++;
return 1;
}
int linenoiseHistoryAdd(const char *line) {
return linenoiseHistoryAddAllocated(strdup(line));
}
int linenoiseHistoryGetMaxLen(void) {
return history_max_len;
}
int linenoiseHistorySetMaxLen(int len) {
char **newHistory;
if (len < 1) return 0;
if (history) {
int tocopy = history_len;
newHistory = (char **)calloc(sizeof(char*), len);
if (len < tocopy) {
int j;
for (j = 0; j < tocopy-len; j++) free(history[j]);
tocopy = len;
}
memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
free(history);
history = newHistory;
}
history_max_len = len;
if (history_len > history_max_len)
history_len = history_max_len;
return 1;
}
int linenoiseHistorySave(const char *filename) {
FILE *fp = fopen(filename,"w");
int j;
if (fp == NULL) return -1;
for (j = 0; j < history_len; j++) {
const char *str = history[j];
while (*str) {
if (*str == '\\') {
fputs("\\\\", fp);
}
else if (*str == '\n') {
fputs("\\n", fp);
}
else if (*str == '\r') {
fputs("\\r", fp);
}
else {
fputc(*str, fp);
}
str++;
}
fputc('\n', fp);
}
fclose(fp);
return 0;
}
int linenoiseHistoryLoad(const char *filename) {
FILE *fp = fopen(filename,"r");
stringbuf *sb;
if (fp == NULL) return -1;
while ((sb = sb_getline(fp)) != NULL) {
char *buf = sb_to_string(sb);
char *dest = buf;
const char *src;
for (src = buf; *src; src++) {
char ch = *src;
if (ch == '\\') {
src++;
if (*src == 'n') {
ch = '\n';
}
else if (*src == 'r') {
ch = '\r';
} else {
ch = *src;
}
}
*dest++ = ch;
}
*dest = 0;
linenoiseHistoryAddAllocated(buf);
}
fclose(fp);
return 0;
}
char **linenoiseHistory(int *len) {
if (len) {
*len = history_len;
}
return history;
}