Home | History | Annotate | Line # | Download | only in libedit
readline.c revision 1.154
      1 /*	$NetBSD: readline.c,v 1.154 2019/06/07 15:19:29 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jaromir Dolecek.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #include "config.h"
     33 #if !defined(lint) && !defined(SCCSID)
     34 __RCSID("$NetBSD: readline.c,v 1.154 2019/06/07 15:19:29 christos Exp $");
     35 #endif /* not lint && not SCCSID */
     36 
     37 #include <sys/types.h>
     38 #include <sys/stat.h>
     39 #include <ctype.h>
     40 #include <dirent.h>
     41 #include <errno.h>
     42 #include <fcntl.h>
     43 #include <limits.h>
     44 #include <pwd.h>
     45 #include <setjmp.h>
     46 #include <stdint.h>
     47 #include <stdio.h>
     48 #include <stdlib.h>
     49 #include <string.h>
     50 #include <unistd.h>
     51 #include <vis.h>
     52 
     53 #include "readline/readline.h"
     54 #include "el.h"
     55 #include "fcns.h"
     56 #include "filecomplete.h"
     57 
     58 void rl_prep_terminal(int);
     59 void rl_deprep_terminal(void);
     60 
     61 /* for rl_complete() */
     62 #define TAB		'\r'
     63 
     64 /* see comment at the #ifdef for sense of this */
     65 /* #define GDB_411_HACK */
     66 
     67 /* readline compatibility stuff - look at readline sources/documentation */
     68 /* to see what these variables mean */
     69 const char *rl_library_version = "EditLine wrapper";
     70 int rl_readline_version = RL_READLINE_VERSION;
     71 static char empty[] = { '\0' };
     72 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
     73 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
     74     '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
     75 const char *rl_readline_name = empty;
     76 FILE *rl_instream = NULL;
     77 FILE *rl_outstream = NULL;
     78 int rl_point = 0;
     79 int rl_end = 0;
     80 char *rl_line_buffer = NULL;
     81 rl_vcpfunc_t *rl_linefunc = NULL;
     82 int rl_done = 0;
     83 rl_hook_func_t *rl_event_hook = NULL;
     84 KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
     85     emacs_meta_keymap,
     86     emacs_ctlx_keymap;
     87 /*
     88  * The following is not implemented; we always catch signals in the
     89  * libedit fashion: set handlers on entry to el_gets() and clear them
     90  * on the way out. This simplistic approach works for most cases; if
     91  * it does not work for your application, please let us know.
     92  */
     93 int rl_catch_signals = 1;
     94 int rl_catch_sigwinch = 1;
     95 
     96 int history_base = 1;		/* probably never subject to change */
     97 int history_length = 0;
     98 int history_offset = 0;
     99 int max_input_history = 0;
    100 char history_expansion_char = '!';
    101 char history_subst_char = '^';
    102 char *history_no_expand_chars = expand_chars;
    103 Function *history_inhibit_expansion_function = NULL;
    104 char *history_arg_extract(int start, int end, const char *str);
    105 
    106 int rl_inhibit_completion = 0;
    107 int rl_attempted_completion_over = 0;
    108 const char *rl_basic_word_break_characters = break_chars;
    109 char *rl_completer_word_break_characters = NULL;
    110 const char *rl_completer_quote_characters = NULL;
    111 rl_compentry_func_t *rl_completion_entry_function = NULL;
    112 char *(*rl_completion_word_break_hook)(void) = NULL;
    113 rl_completion_func_t *rl_attempted_completion_function = NULL;
    114 Function *rl_pre_input_hook = NULL;
    115 Function *rl_startup1_hook = NULL;
    116 int (*rl_getc_function)(FILE *) = NULL;
    117 char *rl_terminal_name = NULL;
    118 int rl_already_prompted = 0;
    119 int rl_filename_completion_desired = 0;
    120 int rl_ignore_completion_duplicates = 0;
    121 int readline_echoing_p = 1;
    122 int _rl_print_completions_horizontally = 0;
    123 VFunction *rl_redisplay_function = NULL;
    124 Function *rl_startup_hook = NULL;
    125 int rl_did_startup_hook = 0;
    126 VFunction *rl_completion_display_matches_hook = NULL;
    127 VFunction *rl_prep_term_function = (VFunction *)rl_prep_terminal;
    128 VFunction *rl_deprep_term_function = (VFunction *)rl_deprep_terminal;
    129 KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
    130 
    131 /*
    132  * The current prompt string.
    133  */
    134 char *rl_prompt = NULL;
    135 /*
    136  * This is set to character indicating type of completion being done by
    137  * rl_complete_internal(); this is available for application completion
    138  * functions.
    139  */
    140 int rl_completion_type = 0;
    141 
    142 /*
    143  * If more than this number of items results from query for possible
    144  * completions, we ask user if they are sure to really display the list.
    145  */
    146 int rl_completion_query_items = 100;
    147 
    148 /*
    149  * List of characters which are word break characters, but should be left
    150  * in the parsed text when it is passed to the completion function.
    151  * Shell uses this to help determine what kind of completing to do.
    152  */
    153 const char *rl_special_prefixes = NULL;
    154 
    155 /*
    156  * This is the character appended to the completed words if at the end of
    157  * the line. Default is ' ' (a space).
    158  */
    159 int rl_completion_append_character = ' ';
    160 
    161 /* stuff below is used internally by libedit for readline emulation */
    162 
    163 static History *h = NULL;
    164 static EditLine *e = NULL;
    165 static rl_command_func_t *map[256];
    166 static jmp_buf topbuf;
    167 
    168 /* internal functions */
    169 static unsigned char	 _el_rl_complete(EditLine *, int);
    170 static unsigned char	 _el_rl_tstp(EditLine *, int);
    171 static char		*_get_prompt(EditLine *);
    172 static int		 _getc_function(EditLine *, wchar_t *);
    173 static int		 _history_expand_command(const char *, size_t, size_t,
    174     char **);
    175 static char		*_rl_compat_sub(const char *, const char *,
    176     const char *, int);
    177 static int		 _rl_event_read_char(EditLine *, wchar_t *);
    178 static void		 _rl_update_pos(void);
    179 
    180 static HIST_ENTRY rl_he;
    181 
    182 /* ARGSUSED */
    183 static char *
    184 _get_prompt(EditLine *el __attribute__((__unused__)))
    185 {
    186 	rl_already_prompted = 1;
    187 	return rl_prompt;
    188 }
    189 
    190 
    191 /*
    192  * read one key from user defined input function
    193  */
    194 static int
    195 /*ARGSUSED*/
    196 _getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c)
    197 {
    198 	int i;
    199 
    200 	i = (*rl_getc_function)(rl_instream);
    201 	if (i == -1)
    202 		return 0;
    203 	*c = (wchar_t)i;
    204 	return 1;
    205 }
    206 
    207 static void
    208 _resize_fun(EditLine *el, void *a)
    209 {
    210 	const LineInfo *li;
    211 	char **ap = a;
    212 
    213 	li = el_line(el);
    214 	/* a cheesy way to get rid of const cast. */
    215 	*ap = memchr(li->buffer, *li->buffer, (size_t)1);
    216 }
    217 
    218 static const char *
    219 _default_history_file(void)
    220 {
    221 	struct passwd *p;
    222 	static char *path;
    223 	size_t len;
    224 
    225 	if (path)
    226 		return path;
    227 
    228 	if ((p = getpwuid(getuid())) == NULL)
    229 		return NULL;
    230 
    231 	len = strlen(p->pw_dir) + sizeof("/.history");
    232 	if ((path = malloc(len)) == NULL)
    233 		return NULL;
    234 
    235 	(void)snprintf(path, len, "%s/.history", p->pw_dir);
    236 	return path;
    237 }
    238 
    239 /*
    240  * READLINE compatibility stuff
    241  */
    242 
    243 /*
    244  * Set the prompt
    245  */
    246 int
    247 rl_set_prompt(const char *prompt)
    248 {
    249 	char *p;
    250 
    251 	if (!prompt)
    252 		prompt = "";
    253 	if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
    254 		return 0;
    255 	if (rl_prompt)
    256 		el_free(rl_prompt);
    257 	rl_prompt = strdup(prompt);
    258 	if (rl_prompt == NULL)
    259 		return -1;
    260 
    261 	while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL) {
    262 		/* Remove adjacent end/start markers to avoid double-escapes. */
    263 		if (p[1] == RL_PROMPT_START_IGNORE) {
    264 			memmove(p, p + 2, 1 + strlen(p + 2));
    265 		} else {
    266 			*p = RL_PROMPT_START_IGNORE;
    267 		}
    268 	}
    269 
    270 	return 0;
    271 }
    272 
    273 /*
    274  * initialize rl compat stuff
    275  */
    276 int
    277 rl_initialize(void)
    278 {
    279 	HistEvent ev;
    280 	int editmode = 1;
    281 	struct termios t;
    282 
    283 	if (e != NULL)
    284 		el_end(e);
    285 	if (h != NULL)
    286 		history_end(h);
    287 
    288 	if (!rl_instream)
    289 		rl_instream = stdin;
    290 	if (!rl_outstream)
    291 		rl_outstream = stdout;
    292 
    293 	/*
    294 	 * See if we don't really want to run the editor
    295 	 */
    296 	if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
    297 		editmode = 0;
    298 
    299 	e = el_init_internal(rl_readline_name, rl_instream, rl_outstream,
    300 	    stderr, fileno(rl_instream), fileno(rl_outstream), fileno(stderr),
    301 	    NO_RESET);
    302 
    303 	if (!editmode)
    304 		el_set(e, EL_EDITMODE, 0);
    305 
    306 	h = history_init();
    307 	if (!e || !h)
    308 		return -1;
    309 
    310 	history(h, &ev, H_SETSIZE, INT_MAX);	/* unlimited */
    311 	history_length = 0;
    312 	max_input_history = INT_MAX;
    313 	el_set(e, EL_HIST, history, h);
    314 
    315 	/* Setup resize function */
    316 	el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
    317 
    318 	/* setup getc function if valid */
    319 	if (rl_getc_function)
    320 		el_set(e, EL_GETCFN, _getc_function);
    321 
    322 	/* for proper prompt printing in readline() */
    323 	if (rl_set_prompt("") == -1) {
    324 		history_end(h);
    325 		el_end(e);
    326 		return -1;
    327 	}
    328 	el_set(e, EL_PROMPT_ESC, _get_prompt, RL_PROMPT_START_IGNORE);
    329 	el_set(e, EL_SIGNAL, rl_catch_signals);
    330 
    331 	/* set default mode to "emacs"-style and read setting afterwards */
    332 	/* so this can be overridden */
    333 	el_set(e, EL_EDITOR, "emacs");
    334 	if (rl_terminal_name != NULL)
    335 		el_set(e, EL_TERMINAL, rl_terminal_name);
    336 	else
    337 		el_get(e, EL_TERMINAL, &rl_terminal_name);
    338 
    339 	/*
    340 	 * Word completion - this has to go AFTER rebinding keys
    341 	 * to emacs-style.
    342 	 */
    343 	el_set(e, EL_ADDFN, "rl_complete",
    344 	    "ReadLine compatible completion function",
    345 	    _el_rl_complete);
    346 	el_set(e, EL_BIND, "^I", "rl_complete", NULL);
    347 
    348 	/*
    349 	 * Send TSTP when ^Z is pressed.
    350 	 */
    351 	el_set(e, EL_ADDFN, "rl_tstp",
    352 	    "ReadLine compatible suspend function",
    353 	    _el_rl_tstp);
    354 	el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
    355 
    356 	/*
    357 	 * Set some readline compatible key-bindings.
    358 	 */
    359 	el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
    360 
    361 	/*
    362 	 * Allow the use of Home/End keys.
    363 	 */
    364 	el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
    365 	el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
    366 	el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
    367 	el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
    368 	el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
    369 	el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
    370 
    371 	/*
    372 	 * Allow the use of the Delete/Insert keys.
    373 	 */
    374 	el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
    375 	el_set(e, EL_BIND, "\\e[2~", "ed-quoted-insert", NULL);
    376 
    377 	/*
    378 	 * Ctrl-left-arrow and Ctrl-right-arrow for word moving.
    379 	 */
    380 	el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
    381 	el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
    382 	el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
    383 	el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
    384 	el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
    385 	el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
    386 
    387 	/* read settings from configuration file */
    388 	el_source(e, NULL);
    389 
    390 	/*
    391 	 * Unfortunately, some applications really do use rl_point
    392 	 * and rl_line_buffer directly.
    393 	 */
    394 	_resize_fun(e, &rl_line_buffer);
    395 	_rl_update_pos();
    396 
    397 	tty_end(e, TCSADRAIN);
    398 
    399 	return 0;
    400 }
    401 
    402 
    403 /*
    404  * read one line from input stream and return it, chomping
    405  * trailing newline (if there is any)
    406  */
    407 char *
    408 readline(const char *p)
    409 {
    410 	HistEvent ev;
    411 	const char * volatile prompt = p;
    412 	int count;
    413 	const char *ret;
    414 	char *buf;
    415 	static int used_event_hook;
    416 
    417 	if (e == NULL || h == NULL)
    418 		rl_initialize();
    419 	if (rl_did_startup_hook == 0 && rl_startup_hook) {
    420 		rl_did_startup_hook = 1;
    421 		(*rl_startup_hook)(NULL, 0);
    422 	}
    423 	tty_init(e);
    424 
    425 
    426 	rl_done = 0;
    427 
    428 	(void)setjmp(topbuf);
    429 	buf = NULL;
    430 
    431 	/* update prompt accordingly to what has been passed */
    432 	if (rl_set_prompt(prompt) == -1)
    433 		goto out;
    434 
    435 	if (rl_pre_input_hook)
    436 		(*rl_pre_input_hook)(NULL, 0);
    437 
    438 	if (rl_event_hook && !(e->el_flags & NO_TTY)) {
    439 		el_set(e, EL_GETCFN, _rl_event_read_char);
    440 		used_event_hook = 1;
    441 	}
    442 
    443 	if (!rl_event_hook && used_event_hook) {
    444 		el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
    445 		used_event_hook = 0;
    446 	}
    447 
    448 	rl_already_prompted = 0;
    449 
    450 	/* get one line from input stream */
    451 	ret = el_gets(e, &count);
    452 
    453 	if (ret && count > 0) {
    454 		int lastidx;
    455 
    456 		buf = strdup(ret);
    457 		if (buf == NULL)
    458 			goto out;
    459 		lastidx = count - 1;
    460 		if (buf[lastidx] == '\n')
    461 			buf[lastidx] = '\0';
    462 	} else
    463 		buf = NULL;
    464 
    465 	history(h, &ev, H_GETSIZE);
    466 	history_length = ev.num;
    467 
    468 out:
    469 	tty_end(e, TCSADRAIN);
    470 	return buf;
    471 }
    472 
    473 /*
    474  * history functions
    475  */
    476 
    477 /*
    478  * is normally called before application starts to use
    479  * history expansion functions
    480  */
    481 void
    482 using_history(void)
    483 {
    484 	if (h == NULL || e == NULL)
    485 		rl_initialize();
    486 	history_offset = history_length;
    487 }
    488 
    489 
    490 /*
    491  * substitute ``what'' with ``with'', returning resulting string; if
    492  * globally == 1, substitutes all occurrences of what, otherwise only the
    493  * first one
    494  */
    495 static char *
    496 _rl_compat_sub(const char *str, const char *what, const char *with,
    497     int globally)
    498 {
    499 	const	char	*s;
    500 	char	*r, *result;
    501 	size_t	len, with_len, what_len;
    502 
    503 	len = strlen(str);
    504 	with_len = strlen(with);
    505 	what_len = strlen(what);
    506 
    507 	/* calculate length we need for result */
    508 	s = str;
    509 	while (*s) {
    510 		if (*s == *what && !strncmp(s, what, what_len)) {
    511 			len += with_len - what_len;
    512 			if (!globally)
    513 				break;
    514 			s += what_len;
    515 		} else
    516 			s++;
    517 	}
    518 	r = result = el_malloc((len + 1) * sizeof(*r));
    519 	if (result == NULL)
    520 		return NULL;
    521 	s = str;
    522 	while (*s) {
    523 		if (*s == *what && !strncmp(s, what, what_len)) {
    524 			(void)strncpy(r, with, with_len);
    525 			r += with_len;
    526 			s += what_len;
    527 			if (!globally) {
    528 				(void)strcpy(r, s);
    529 				return result;
    530 			}
    531 		} else
    532 			*r++ = *s++;
    533 	}
    534 	*r = '\0';
    535 	return result;
    536 }
    537 
    538 static	char	*last_search_pat;	/* last !?pat[?] search pattern */
    539 static	char	*last_search_match;	/* last !?pat[?] that matched */
    540 
    541 const char *
    542 get_history_event(const char *cmd, int *cindex, int qchar)
    543 {
    544 	int idx, sign, sub, num, begin, ret;
    545 	size_t len;
    546 	char	*pat;
    547 	const char *rptr;
    548 	HistEvent ev;
    549 
    550 	idx = *cindex;
    551 	if (cmd[idx++] != history_expansion_char)
    552 		return NULL;
    553 
    554 	/* find out which event to take */
    555 	if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
    556 		if (history(h, &ev, H_FIRST) != 0)
    557 			return NULL;
    558 		*cindex = cmd[idx]? (idx + 1):idx;
    559 		return ev.str;
    560 	}
    561 	sign = 0;
    562 	if (cmd[idx] == '-') {
    563 		sign = 1;
    564 		idx++;
    565 	}
    566 
    567 	if ('0' <= cmd[idx] && cmd[idx] <= '9') {
    568 		HIST_ENTRY *he;
    569 
    570 		num = 0;
    571 		while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
    572 			num = num * 10 + cmd[idx] - '0';
    573 			idx++;
    574 		}
    575 		if (sign)
    576 			num = history_length - num + history_base;
    577 
    578 		if (!(he = history_get(num)))
    579 			return NULL;
    580 
    581 		*cindex = idx;
    582 		return he->line;
    583 	}
    584 	sub = 0;
    585 	if (cmd[idx] == '?') {
    586 		sub = 1;
    587 		idx++;
    588 	}
    589 	begin = idx;
    590 	while (cmd[idx]) {
    591 		if (cmd[idx] == '\n')
    592 			break;
    593 		if (sub && cmd[idx] == '?')
    594 			break;
    595 		if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
    596 				    || cmd[idx] == '\t' || cmd[idx] == qchar))
    597 			break;
    598 		idx++;
    599 	}
    600 	len = (size_t)idx - (size_t)begin;
    601 	if (sub && cmd[idx] == '?')
    602 		idx++;
    603 	if (sub && len == 0 && last_search_pat && *last_search_pat)
    604 		pat = last_search_pat;
    605 	else if (len == 0)
    606 		return NULL;
    607 	else {
    608 		if ((pat = el_malloc((len + 1) * sizeof(*pat))) == NULL)
    609 			return NULL;
    610 		(void)strncpy(pat, cmd + begin, len);
    611 		pat[len] = '\0';
    612 	}
    613 
    614 	if (history(h, &ev, H_CURR) != 0) {
    615 		if (pat != last_search_pat)
    616 			el_free(pat);
    617 		return NULL;
    618 	}
    619 	num = ev.num;
    620 
    621 	if (sub) {
    622 		if (pat != last_search_pat) {
    623 			if (last_search_pat)
    624 				el_free(last_search_pat);
    625 			last_search_pat = pat;
    626 		}
    627 		ret = history_search(pat, -1);
    628 	} else
    629 		ret = history_search_prefix(pat, -1);
    630 
    631 	if (ret == -1) {
    632 		/* restore to end of list on failed search */
    633 		history(h, &ev, H_FIRST);
    634 		(void)fprintf(rl_outstream, "%s: Event not found\n", pat);
    635 		if (pat != last_search_pat)
    636 			el_free(pat);
    637 		return NULL;
    638 	}
    639 
    640 	if (sub && len) {
    641 		if (last_search_match && last_search_match != pat)
    642 			el_free(last_search_match);
    643 		last_search_match = pat;
    644 	}
    645 
    646 	if (pat != last_search_pat)
    647 		el_free(pat);
    648 
    649 	if (history(h, &ev, H_CURR) != 0)
    650 		return NULL;
    651 	*cindex = idx;
    652 	rptr = ev.str;
    653 
    654 	/* roll back to original position */
    655 	(void)history(h, &ev, H_SET, num);
    656 
    657 	return rptr;
    658 }
    659 
    660 /*
    661  * the real function doing history expansion - takes as argument command
    662  * to do and data upon which the command should be executed
    663  * does expansion the way I've understood readline documentation
    664  *
    665  * returns 0 if data was not modified, 1 if it was and 2 if the string
    666  * should be only printed and not executed; in case of error,
    667  * returns -1 and *result points to NULL
    668  * it's the caller's responsibility to free() the string returned in *result
    669  */
    670 static int
    671 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
    672     char **result)
    673 {
    674 	char *tmp, *search = NULL, *aptr;
    675 	const char *ptr, *cmd;
    676 	static char *from = NULL, *to = NULL;
    677 	int start, end, idx, has_mods = 0;
    678 	int p_on = 0, g_on = 0;
    679 
    680 	*result = NULL;
    681 	aptr = NULL;
    682 	ptr = NULL;
    683 
    684 	/* First get event specifier */
    685 	idx = 0;
    686 
    687 	if (strchr(":^*$", command[offs + 1])) {
    688 		char str[4];
    689 		/*
    690 		* "!:" is shorthand for "!!:".
    691 		* "!^", "!*" and "!$" are shorthand for
    692 		* "!!:^", "!!:*" and "!!:$" respectively.
    693 		*/
    694 		str[0] = str[1] = '!';
    695 		str[2] = '0';
    696 		ptr = get_history_event(str, &idx, 0);
    697 		idx = (command[offs + 1] == ':')? 1:0;
    698 		has_mods = 1;
    699 	} else {
    700 		if (command[offs + 1] == '#') {
    701 			/* use command so far */
    702 			if ((aptr = el_malloc((offs + 1) * sizeof(*aptr)))
    703 			    == NULL)
    704 				return -1;
    705 			(void)strncpy(aptr, command, offs);
    706 			aptr[offs] = '\0';
    707 			idx = 1;
    708 		} else {
    709 			int	qchar;
    710 
    711 			qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
    712 			ptr = get_history_event(command + offs, &idx, qchar);
    713 		}
    714 		has_mods = command[offs + (size_t)idx] == ':';
    715 	}
    716 
    717 	if (ptr == NULL && aptr == NULL)
    718 		return -1;
    719 
    720 	if (!has_mods) {
    721 		*result = strdup(aptr ? aptr : ptr);
    722 		if (aptr)
    723 			el_free(aptr);
    724 		if (*result == NULL)
    725 			return -1;
    726 		return 1;
    727 	}
    728 
    729 	cmd = command + offs + idx + 1;
    730 
    731 	/* Now parse any word designators */
    732 
    733 	if (*cmd == '%')	/* last word matched by ?pat? */
    734 		tmp = strdup(last_search_match? last_search_match:"");
    735 	else if (strchr("^*$-0123456789", *cmd)) {
    736 		start = end = -1;
    737 		if (*cmd == '^')
    738 			start = end = 1, cmd++;
    739 		else if (*cmd == '$')
    740 			start = -1, cmd++;
    741 		else if (*cmd == '*')
    742 			start = 1, cmd++;
    743 	       else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
    744 			start = 0;
    745 			while (*cmd && '0' <= *cmd && *cmd <= '9')
    746 				start = start * 10 + *cmd++ - '0';
    747 
    748 			if (*cmd == '-') {
    749 				if (isdigit((unsigned char) cmd[1])) {
    750 					cmd++;
    751 					end = 0;
    752 					while (*cmd && '0' <= *cmd && *cmd <= '9')
    753 						end = end * 10 + *cmd++ - '0';
    754 				} else if (cmd[1] == '$') {
    755 					cmd += 2;
    756 					end = -1;
    757 				} else {
    758 					cmd++;
    759 					end = -2;
    760 				}
    761 			} else if (*cmd == '*')
    762 				end = -1, cmd++;
    763 			else
    764 				end = start;
    765 		}
    766 		tmp = history_arg_extract(start, end, aptr? aptr:ptr);
    767 		if (tmp == NULL) {
    768 			(void)fprintf(rl_outstream, "%s: Bad word specifier",
    769 			    command + offs + idx);
    770 			if (aptr)
    771 				el_free(aptr);
    772 			return -1;
    773 		}
    774 	} else
    775 		tmp = strdup(aptr? aptr:ptr);
    776 
    777 	if (aptr)
    778 		el_free(aptr);
    779 
    780 	if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
    781 		*result = tmp;
    782 		return 1;
    783 	}
    784 
    785 	for (; *cmd; cmd++) {
    786 		if (*cmd == ':')
    787 			continue;
    788 		else if (*cmd == 'h') {		/* remove trailing path */
    789 			if ((aptr = strrchr(tmp, '/')) != NULL)
    790 				*aptr = '\0';
    791 		} else if (*cmd == 't') {	/* remove leading path */
    792 			if ((aptr = strrchr(tmp, '/')) != NULL) {
    793 				aptr = strdup(aptr + 1);
    794 				el_free(tmp);
    795 				tmp = aptr;
    796 			}
    797 		} else if (*cmd == 'r') {	/* remove trailing suffix */
    798 			if ((aptr = strrchr(tmp, '.')) != NULL)
    799 				*aptr = '\0';
    800 		} else if (*cmd == 'e') {	/* remove all but suffix */
    801 			if ((aptr = strrchr(tmp, '.')) != NULL) {
    802 				aptr = strdup(aptr);
    803 				el_free(tmp);
    804 				tmp = aptr;
    805 			}
    806 		} else if (*cmd == 'p')		/* print only */
    807 			p_on = 1;
    808 		else if (*cmd == 'g')
    809 			g_on = 2;
    810 		else if (*cmd == 's' || *cmd == '&') {
    811 			char *what, *with, delim;
    812 			size_t len, from_len;
    813 			size_t size;
    814 
    815 			if (*cmd == '&' && (from == NULL || to == NULL))
    816 				continue;
    817 			else if (*cmd == 's') {
    818 				delim = *(++cmd), cmd++;
    819 				size = 16;
    820 				what = el_realloc(from, size * sizeof(*what));
    821 				if (what == NULL) {
    822 					el_free(from);
    823 					el_free(tmp);
    824 					return 0;
    825 				}
    826 				len = 0;
    827 				for (; *cmd && *cmd != delim; cmd++) {
    828 					if (*cmd == '\\' && cmd[1] == delim)
    829 						cmd++;
    830 					if (len >= size) {
    831 						char *nwhat;
    832 						nwhat = el_realloc(what,
    833 						    (size <<= 1) *
    834 						    sizeof(*nwhat));
    835 						if (nwhat == NULL) {
    836 							el_free(what);
    837 							el_free(tmp);
    838 							return 0;
    839 						}
    840 						what = nwhat;
    841 					}
    842 					what[len++] = *cmd;
    843 				}
    844 				what[len] = '\0';
    845 				from = what;
    846 				if (*what == '\0') {
    847 					el_free(what);
    848 					if (search) {
    849 						from = strdup(search);
    850 						if (from == NULL) {
    851 							el_free(tmp);
    852 							return 0;
    853 						}
    854 					} else {
    855 						from = NULL;
    856 						el_free(tmp);
    857 						return -1;
    858 					}
    859 				}
    860 				cmd++;	/* shift after delim */
    861 				if (!*cmd)
    862 					continue;
    863 
    864 				size = 16;
    865 				with = el_realloc(to, size * sizeof(*with));
    866 				if (with == NULL) {
    867 					el_free(to);
    868 					el_free(tmp);
    869 					return -1;
    870 				}
    871 				len = 0;
    872 				from_len = strlen(from);
    873 				for (; *cmd && *cmd != delim; cmd++) {
    874 					if (len + from_len + 1 >= size) {
    875 						char *nwith;
    876 						size += from_len + 1;
    877 						nwith = el_realloc(with,
    878 						    size * sizeof(*nwith));
    879 						if (nwith == NULL) {
    880 							el_free(with);
    881 							el_free(tmp);
    882 							return -1;
    883 						}
    884 						with = nwith;
    885 					}
    886 					if (*cmd == '&') {
    887 						/* safe */
    888 						(void)strcpy(&with[len], from);
    889 						len += from_len;
    890 						continue;
    891 					}
    892 					if (*cmd == '\\'
    893 					    && (*(cmd + 1) == delim
    894 						|| *(cmd + 1) == '&'))
    895 						cmd++;
    896 					with[len++] = *cmd;
    897 				}
    898 				with[len] = '\0';
    899 				to = with;
    900 			}
    901 
    902 			aptr = _rl_compat_sub(tmp, from, to, g_on);
    903 			if (aptr) {
    904 				el_free(tmp);
    905 				tmp = aptr;
    906 			}
    907 			g_on = 0;
    908 		}
    909 	}
    910 	*result = tmp;
    911 	return p_on? 2:1;
    912 }
    913 
    914 
    915 /*
    916  * csh-style history expansion
    917  */
    918 int
    919 history_expand(char *str, char **output)
    920 {
    921 	int ret = 0;
    922 	size_t idx, i, size;
    923 	char *tmp, *result;
    924 
    925 	if (h == NULL || e == NULL)
    926 		rl_initialize();
    927 
    928 	if (history_expansion_char == 0) {
    929 		*output = strdup(str);
    930 		return 0;
    931 	}
    932 
    933 	*output = NULL;
    934 	if (str[0] == history_subst_char) {
    935 		/* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
    936 		*output = el_malloc((strlen(str) + 4 + 1) * sizeof(**output));
    937 		if (*output == NULL)
    938 			return 0;
    939 		(*output)[0] = (*output)[1] = history_expansion_char;
    940 		(*output)[2] = ':';
    941 		(*output)[3] = 's';
    942 		(void)strcpy((*output) + 4, str);
    943 		str = *output;
    944 	} else {
    945 		*output = strdup(str);
    946 		if (*output == NULL)
    947 			return 0;
    948 	}
    949 
    950 #define ADD_STRING(what, len, fr)					\
    951 	{								\
    952 		if (idx + len + 1 > size) {				\
    953 			char *nresult = el_realloc(result,		\
    954 			    (size += len + 1) * sizeof(*nresult));	\
    955 			if (nresult == NULL) {				\
    956 				el_free(*output);			\
    957 				if (/*CONSTCOND*/fr)			\
    958 					el_free(tmp);			\
    959 				return 0;				\
    960 			}						\
    961 			result = nresult;				\
    962 		}							\
    963 		(void)strncpy(&result[idx], what, len);			\
    964 		idx += len;						\
    965 		result[idx] = '\0';					\
    966 	}
    967 
    968 	result = NULL;
    969 	size = idx = 0;
    970 	tmp = NULL;
    971 	for (i = 0; str[i];) {
    972 		int qchar, loop_again;
    973 		size_t len, start, j;
    974 
    975 		qchar = 0;
    976 		loop_again = 1;
    977 		start = j = i;
    978 loop:
    979 		for (; str[j]; j++) {
    980 			if (str[j] == '\\' &&
    981 			    str[j + 1] == history_expansion_char) {
    982 				len = strlen(&str[j + 1]) + 1;
    983 				memmove(&str[j], &str[j + 1], len);
    984 				continue;
    985 			}
    986 			if (!loop_again) {
    987 				if (isspace((unsigned char) str[j])
    988 				    || str[j] == qchar)
    989 					break;
    990 			}
    991 			if (str[j] == history_expansion_char
    992 			    && !strchr(history_no_expand_chars, str[j + 1])
    993 			    && (!history_inhibit_expansion_function ||
    994 			    (*history_inhibit_expansion_function)(str,
    995 			    (int)j) == 0))
    996 				break;
    997 		}
    998 
    999 		if (str[j] && loop_again) {
   1000 			i = j;
   1001 			qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
   1002 			j++;
   1003 			if (str[j] == history_expansion_char)
   1004 				j++;
   1005 			loop_again = 0;
   1006 			goto loop;
   1007 		}
   1008 		len = i - start;
   1009 		ADD_STRING(&str[start], len, 0);
   1010 
   1011 		if (str[i] == '\0' || str[i] != history_expansion_char) {
   1012 			len = j - i;
   1013 			ADD_STRING(&str[i], len, 0);
   1014 			if (start == 0)
   1015 				ret = 0;
   1016 			else
   1017 				ret = 1;
   1018 			break;
   1019 		}
   1020 		ret = _history_expand_command (str, i, (j - i), &tmp);
   1021 		if (ret > 0 && tmp) {
   1022 			len = strlen(tmp);
   1023 			ADD_STRING(tmp, len, 1);
   1024 		}
   1025 		if (tmp) {
   1026 			el_free(tmp);
   1027 			tmp = NULL;
   1028 		}
   1029 		i = j;
   1030 	}
   1031 
   1032 	/* ret is 2 for "print only" option */
   1033 	if (ret == 2) {
   1034 		add_history(result);
   1035 #ifdef GDB_411_HACK
   1036 		/* gdb 4.11 has been shipped with readline, where */
   1037 		/* history_expand() returned -1 when the line	  */
   1038 		/* should not be executed; in readline 2.1+	  */
   1039 		/* it should return 2 in such a case		  */
   1040 		ret = -1;
   1041 #endif
   1042 	}
   1043 	el_free(*output);
   1044 	*output = result;
   1045 
   1046 	return ret;
   1047 }
   1048 
   1049 /*
   1050 * Return a string consisting of arguments of "str" from "start" to "end".
   1051 */
   1052 char *
   1053 history_arg_extract(int start, int end, const char *str)
   1054 {
   1055 	size_t  i, len, max;
   1056 	char	**arr, *result = NULL;
   1057 
   1058 	arr = history_tokenize(str);
   1059 	if (!arr)
   1060 		return NULL;
   1061 	if (arr && *arr == NULL)
   1062 		goto out;
   1063 
   1064 	for (max = 0; arr[max]; max++)
   1065 		continue;
   1066 	max--;
   1067 
   1068 	if (start == '$')
   1069 		start = (int)max;
   1070 	if (end == '$')
   1071 		end = (int)max;
   1072 	if (end < 0)
   1073 		end = (int)max + end + 1;
   1074 	if (start < 0)
   1075 		start = end;
   1076 
   1077 	if (start < 0 || end < 0 || (size_t)start > max ||
   1078 	    (size_t)end > max || start > end)
   1079 		goto out;
   1080 
   1081 	for (i = (size_t)start, len = 0; i <= (size_t)end; i++)
   1082 		len += strlen(arr[i]) + 1;
   1083 	len++;
   1084 	result = el_malloc(len * sizeof(*result));
   1085 	if (result == NULL)
   1086 		goto out;
   1087 
   1088 	for (i = (size_t)start, len = 0; i <= (size_t)end; i++) {
   1089 		(void)strcpy(result + len, arr[i]);
   1090 		len += strlen(arr[i]);
   1091 		if (i < (size_t)end)
   1092 			result[len++] = ' ';
   1093 	}
   1094 	result[len] = '\0';
   1095 
   1096 out:
   1097 	for (i = 0; arr[i]; i++)
   1098 		el_free(arr[i]);
   1099 	el_free(arr);
   1100 
   1101 	return result;
   1102 }
   1103 
   1104 /*
   1105  * Parse the string into individual tokens,
   1106  * similar to how shell would do it.
   1107  */
   1108 char **
   1109 history_tokenize(const char *str)
   1110 {
   1111 	int size = 1, idx = 0, i, start;
   1112 	size_t len;
   1113 	char **result = NULL, *temp, delim = '\0';
   1114 
   1115 	for (i = 0; str[i];) {
   1116 		while (isspace((unsigned char) str[i]))
   1117 			i++;
   1118 		start = i;
   1119 		for (; str[i];) {
   1120 			if (str[i] == '\\') {
   1121 				if (str[i+1] != '\0')
   1122 					i++;
   1123 			} else if (str[i] == delim)
   1124 				delim = '\0';
   1125 			else if (!delim &&
   1126 				    (isspace((unsigned char) str[i]) ||
   1127 				strchr("()<>;&|$", str[i])))
   1128 				break;
   1129 			else if (!delim && strchr("'`\"", str[i]))
   1130 				delim = str[i];
   1131 			if (str[i])
   1132 				i++;
   1133 		}
   1134 
   1135 		if (idx + 2 >= size) {
   1136 			char **nresult;
   1137 			size <<= 1;
   1138 			nresult = el_realloc(result, (size_t)size * sizeof(*nresult));
   1139 			if (nresult == NULL) {
   1140 				el_free(result);
   1141 				return NULL;
   1142 			}
   1143 			result = nresult;
   1144 		}
   1145 		len = (size_t)i - (size_t)start;
   1146 		temp = el_malloc((size_t)(len + 1) * sizeof(*temp));
   1147 		if (temp == NULL) {
   1148 			for (i = 0; i < idx; i++)
   1149 				el_free(result[i]);
   1150 			el_free(result);
   1151 			return NULL;
   1152 		}
   1153 		(void)strncpy(temp, &str[start], len);
   1154 		temp[len] = '\0';
   1155 		result[idx++] = temp;
   1156 		result[idx] = NULL;
   1157 		if (str[i])
   1158 			i++;
   1159 	}
   1160 	return result;
   1161 }
   1162 
   1163 
   1164 /*
   1165  * limit size of history record to ``max'' events
   1166  */
   1167 void
   1168 stifle_history(int max)
   1169 {
   1170 	HistEvent ev;
   1171 	HIST_ENTRY *he;
   1172 
   1173 	if (h == NULL || e == NULL)
   1174 		rl_initialize();
   1175 
   1176 	if (history(h, &ev, H_SETSIZE, max) == 0) {
   1177 		max_input_history = max;
   1178 		if (history_length > max)
   1179 			history_base = history_length - max;
   1180 		while (history_length > max) {
   1181 			he = remove_history(0);
   1182 			el_free(he->data);
   1183 			el_free((void *)(unsigned long)he->line);
   1184 			el_free(he);
   1185 		}
   1186 	}
   1187 }
   1188 
   1189 
   1190 /*
   1191  * "unlimit" size of history - set the limit to maximum allowed int value
   1192  */
   1193 int
   1194 unstifle_history(void)
   1195 {
   1196 	HistEvent ev;
   1197 	int omax;
   1198 
   1199 	history(h, &ev, H_SETSIZE, INT_MAX);
   1200 	omax = max_input_history;
   1201 	max_input_history = INT_MAX;
   1202 	return omax;		/* some value _must_ be returned */
   1203 }
   1204 
   1205 
   1206 int
   1207 history_is_stifled(void)
   1208 {
   1209 
   1210 	/* cannot return true answer */
   1211 	return max_input_history != INT_MAX;
   1212 }
   1213 
   1214 static const char _history_tmp_template[] = "/tmp/.historyXXXXXX";
   1215 
   1216 int
   1217 history_truncate_file (const char *filename, int nlines)
   1218 {
   1219 	int ret = 0;
   1220 	FILE *fp, *tp;
   1221 	char template[sizeof(_history_tmp_template)];
   1222 	char buf[4096];
   1223 	int fd;
   1224 	char *cp;
   1225 	off_t off;
   1226 	int count = 0;
   1227 	ssize_t left = 0;
   1228 
   1229 	if (filename == NULL && (filename = _default_history_file()) == NULL)
   1230 		return errno;
   1231 	if ((fp = fopen(filename, "r+")) == NULL)
   1232 		return errno;
   1233 	strcpy(template, _history_tmp_template);
   1234 	if ((fd = mkstemp(template)) == -1) {
   1235 		ret = errno;
   1236 		goto out1;
   1237 	}
   1238 
   1239 	if ((tp = fdopen(fd, "r+")) == NULL) {
   1240 		close(fd);
   1241 		ret = errno;
   1242 		goto out2;
   1243 	}
   1244 
   1245 	for(;;) {
   1246 		if (fread(buf, sizeof(buf), (size_t)1, fp) != 1) {
   1247 			if (ferror(fp)) {
   1248 				ret = errno;
   1249 				break;
   1250 			}
   1251 			if (fseeko(fp, (off_t)sizeof(buf) * count, SEEK_SET) ==
   1252 			    (off_t)-1) {
   1253 				ret = errno;
   1254 				break;
   1255 			}
   1256 			left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), fp);
   1257 			if (ferror(fp)) {
   1258 				ret = errno;
   1259 				break;
   1260 			}
   1261 			if (left == 0) {
   1262 				count--;
   1263 				left = sizeof(buf);
   1264 			} else if (fwrite(buf, (size_t)left, (size_t)1, tp)
   1265 			    != 1) {
   1266 				ret = errno;
   1267 				break;
   1268 			}
   1269 			fflush(tp);
   1270 			break;
   1271 		}
   1272 		if (fwrite(buf, sizeof(buf), (size_t)1, tp) != 1) {
   1273 			ret = errno;
   1274 			break;
   1275 		}
   1276 		count++;
   1277 	}
   1278 	if (ret)
   1279 		goto out3;
   1280 	cp = buf + left - 1;
   1281 	if(*cp != '\n')
   1282 		cp++;
   1283 	for(;;) {
   1284 		while (--cp >= buf) {
   1285 			if (*cp == '\n') {
   1286 				if (--nlines == 0) {
   1287 					if (++cp >= buf + sizeof(buf)) {
   1288 						count++;
   1289 						cp = buf;
   1290 					}
   1291 					break;
   1292 				}
   1293 			}
   1294 		}
   1295 		if (nlines <= 0 || count == 0)
   1296 			break;
   1297 		count--;
   1298 		if (fseeko(tp, (off_t)sizeof(buf) * count, SEEK_SET) < 0) {
   1299 			ret = errno;
   1300 			break;
   1301 		}
   1302 		if (fread(buf, sizeof(buf), (size_t)1, tp) != 1) {
   1303 			if (ferror(tp)) {
   1304 				ret = errno;
   1305 				break;
   1306 			}
   1307 			ret = EAGAIN;
   1308 			break;
   1309 		}
   1310 		cp = buf + sizeof(buf);
   1311 	}
   1312 
   1313 	if (ret || nlines > 0)
   1314 		goto out3;
   1315 
   1316 	if (fseeko(fp, (off_t)0, SEEK_SET) == (off_t)-1) {
   1317 		ret = errno;
   1318 		goto out3;
   1319 	}
   1320 
   1321 	if (fseeko(tp, (off_t)sizeof(buf) * count + (cp - buf), SEEK_SET) ==
   1322 	    (off_t)-1) {
   1323 		ret = errno;
   1324 		goto out3;
   1325 	}
   1326 
   1327 	for(;;) {
   1328 		if ((left = (ssize_t)fread(buf, (size_t)1, sizeof(buf), tp)) == 0) {
   1329 			if (ferror(fp))
   1330 				ret = errno;
   1331 			break;
   1332 		}
   1333 		if (fwrite(buf, (size_t)left, (size_t)1, fp) != 1) {
   1334 			ret = errno;
   1335 			break;
   1336 		}
   1337 	}
   1338 	fflush(fp);
   1339 	if((off = ftello(fp)) > 0)
   1340 		(void)ftruncate(fileno(fp), off);
   1341 out3:
   1342 	fclose(tp);
   1343 out2:
   1344 	unlink(template);
   1345 out1:
   1346 	fclose(fp);
   1347 
   1348 	return ret;
   1349 }
   1350 
   1351 
   1352 /*
   1353  * read history from a file given
   1354  */
   1355 int
   1356 read_history(const char *filename)
   1357 {
   1358 	HistEvent ev;
   1359 
   1360 	if (h == NULL || e == NULL)
   1361 		rl_initialize();
   1362 	if (filename == NULL && (filename = _default_history_file()) == NULL)
   1363 		return errno;
   1364 	errno = 0;
   1365 	if (history(h, &ev, H_LOAD, filename) == -1)
   1366 	    return errno ? errno : EINVAL;
   1367 	if (history(h, &ev, H_GETSIZE) == 0)
   1368 		history_length = ev.num;
   1369 	if (history_length < 0)
   1370 		return EINVAL;
   1371 	return 0;
   1372 }
   1373 
   1374 
   1375 /*
   1376  * write history to a file given
   1377  */
   1378 int
   1379 write_history(const char *filename)
   1380 {
   1381 	HistEvent ev;
   1382 
   1383 	if (h == NULL || e == NULL)
   1384 		rl_initialize();
   1385 	if (filename == NULL && (filename = _default_history_file()) == NULL)
   1386 		return errno;
   1387 	return history(h, &ev, H_SAVE, filename) == -1 ?
   1388 	    (errno ? errno : EINVAL) : 0;
   1389 }
   1390 
   1391 int
   1392 append_history(int n, const char *filename)
   1393 {
   1394 	HistEvent ev;
   1395 	FILE *fp;
   1396 
   1397 	if (h == NULL || e == NULL)
   1398 		rl_initialize();
   1399 	if (filename == NULL && (filename = _default_history_file()) == NULL)
   1400 		return errno;
   1401 
   1402 	if ((fp = fopen(filename, "a")) == NULL)
   1403 		return errno;
   1404 
   1405 	if (history(h, &ev, H_NSAVE_FP, (size_t)n,  fp) == -1) {
   1406 		int serrno = errno ? errno : EINVAL;
   1407 		fclose(fp);
   1408 		return serrno;
   1409 	}
   1410 	fclose(fp);
   1411 	return 0;
   1412 }
   1413 
   1414 /*
   1415  * returns history ``num''th event
   1416  *
   1417  * returned pointer points to static variable
   1418  */
   1419 HIST_ENTRY *
   1420 history_get(int num)
   1421 {
   1422 	static HIST_ENTRY she;
   1423 	HistEvent ev;
   1424 	int curr_num;
   1425 
   1426 	if (h == NULL || e == NULL)
   1427 		rl_initialize();
   1428 
   1429 	if (num < history_base)
   1430 		return NULL;
   1431 
   1432 	/* save current position */
   1433 	if (history(h, &ev, H_CURR) != 0)
   1434 		return NULL;
   1435 	curr_num = ev.num;
   1436 
   1437 	/*
   1438 	 * use H_DELDATA to set to nth history (without delete) by passing
   1439 	 * (void **)-1  -- as in history_set_pos
   1440 	 */
   1441 	if (history(h, &ev, H_DELDATA, num - history_base, (void **)-1) != 0)
   1442 		goto out;
   1443 
   1444 	/* get current entry */
   1445 	if (history(h, &ev, H_CURR) != 0)
   1446 		goto out;
   1447 	if (history(h, &ev, H_NEXT_EVDATA, ev.num, &she.data) != 0)
   1448 		goto out;
   1449 	she.line = ev.str;
   1450 
   1451 	/* restore pointer to where it was */
   1452 	(void)history(h, &ev, H_SET, curr_num);
   1453 
   1454 	return &she;
   1455 
   1456 out:
   1457 	/* restore pointer to where it was */
   1458 	(void)history(h, &ev, H_SET, curr_num);
   1459 	return NULL;
   1460 }
   1461 
   1462 
   1463 /*
   1464  * add the line to history table
   1465  */
   1466 int
   1467 add_history(const char *line)
   1468 {
   1469 	HistEvent ev;
   1470 
   1471 	if (h == NULL || e == NULL)
   1472 		rl_initialize();
   1473 
   1474 	if (history(h, &ev, H_ENTER, line) == -1)
   1475 		return 0;
   1476 
   1477 	(void)history(h, &ev, H_GETSIZE);
   1478 	if (ev.num == history_length)
   1479 		history_base++;
   1480 	else
   1481 		history_length = ev.num;
   1482 	return 0;
   1483 }
   1484 
   1485 
   1486 /*
   1487  * remove the specified entry from the history list and return it.
   1488  */
   1489 HIST_ENTRY *
   1490 remove_history(int num)
   1491 {
   1492 	HIST_ENTRY *he;
   1493 	HistEvent ev;
   1494 
   1495 	if (h == NULL || e == NULL)
   1496 		rl_initialize();
   1497 
   1498 	if ((he = el_malloc(sizeof(*he))) == NULL)
   1499 		return NULL;
   1500 
   1501 	if (history(h, &ev, H_DELDATA, num, &he->data) != 0) {
   1502 		el_free(he);
   1503 		return NULL;
   1504 	}
   1505 
   1506 	he->line = ev.str;
   1507 	if (history(h, &ev, H_GETSIZE) == 0)
   1508 		history_length = ev.num;
   1509 
   1510 	return he;
   1511 }
   1512 
   1513 
   1514 /*
   1515  * replace the line and data of the num-th entry
   1516  */
   1517 HIST_ENTRY *
   1518 replace_history_entry(int num, const char *line, histdata_t data)
   1519 {
   1520 	HIST_ENTRY *he;
   1521 	HistEvent ev;
   1522 	int curr_num;
   1523 
   1524 	if (h == NULL || e == NULL)
   1525 		rl_initialize();
   1526 
   1527 	/* save current position */
   1528 	if (history(h, &ev, H_CURR) != 0)
   1529 		return NULL;
   1530 	curr_num = ev.num;
   1531 
   1532 	/* start from the oldest */
   1533 	if (history(h, &ev, H_LAST) != 0)
   1534 		return NULL;	/* error */
   1535 
   1536 	if ((he = el_malloc(sizeof(*he))) == NULL)
   1537 		return NULL;
   1538 
   1539 	/* look forwards for event matching specified offset */
   1540 	if (history(h, &ev, H_NEXT_EVDATA, num, &he->data))
   1541 		goto out;
   1542 
   1543 	he->line = strdup(ev.str);
   1544 	if (he->line == NULL)
   1545 		goto out;
   1546 
   1547 	if (history(h, &ev, H_REPLACE, line, data))
   1548 		goto out;
   1549 
   1550 	/* restore pointer to where it was */
   1551 	if (history(h, &ev, H_SET, curr_num))
   1552 		goto out;
   1553 
   1554 	return he;
   1555 out:
   1556 	el_free(he);
   1557 	return NULL;
   1558 }
   1559 
   1560 /*
   1561  * clear the history list - delete all entries
   1562  */
   1563 void
   1564 clear_history(void)
   1565 {
   1566 	HistEvent ev;
   1567 
   1568 	if (h == NULL || e == NULL)
   1569 		rl_initialize();
   1570 
   1571 	(void)history(h, &ev, H_CLEAR);
   1572 	history_offset = history_length = 0;
   1573 }
   1574 
   1575 
   1576 /*
   1577  * returns offset of the current history event
   1578  */
   1579 int
   1580 where_history(void)
   1581 {
   1582 	return history_offset;
   1583 }
   1584 
   1585 static HIST_ENTRY **_history_listp;
   1586 static HIST_ENTRY *_history_list;
   1587 
   1588 HIST_ENTRY **
   1589 history_list(void)
   1590 {
   1591 	HistEvent ev;
   1592 	HIST_ENTRY **nlp, *nl;
   1593 	int i;
   1594 
   1595 	if (history(h, &ev, H_LAST) != 0)
   1596 		return NULL;
   1597 
   1598 	if ((nlp = el_realloc(_history_listp,
   1599 	    ((size_t)history_length + 1) * sizeof(*nlp))) == NULL)
   1600 		return NULL;
   1601 	_history_listp = nlp;
   1602 
   1603 	if ((nl = el_realloc(_history_list,
   1604 	    (size_t)history_length * sizeof(*nl))) == NULL)
   1605 		return NULL;
   1606 	_history_list = nl;
   1607 
   1608 	i = 0;
   1609 	do {
   1610 		_history_listp[i] = &_history_list[i];
   1611 		_history_list[i].line = ev.str;
   1612 		_history_list[i].data = NULL;
   1613 		if (i++ == history_length)
   1614 			abort();
   1615 	} while (history(h, &ev, H_PREV) == 0);
   1616 	_history_listp[i] = NULL;
   1617 	return _history_listp;
   1618 }
   1619 
   1620 /*
   1621  * returns current history event or NULL if there is no such event
   1622  */
   1623 HIST_ENTRY *
   1624 current_history(void)
   1625 {
   1626 	HistEvent ev;
   1627 
   1628 	if (history(h, &ev, H_PREV_EVENT, history_offset + 1) != 0)
   1629 		return NULL;
   1630 
   1631 	rl_he.line = ev.str;
   1632 	rl_he.data = NULL;
   1633 	return &rl_he;
   1634 }
   1635 
   1636 
   1637 /*
   1638  * returns total number of bytes history events' data are using
   1639  */
   1640 int
   1641 history_total_bytes(void)
   1642 {
   1643 	HistEvent ev;
   1644 	int curr_num;
   1645 	size_t size;
   1646 
   1647 	if (history(h, &ev, H_CURR) != 0)
   1648 		return -1;
   1649 	curr_num = ev.num;
   1650 
   1651 	(void)history(h, &ev, H_FIRST);
   1652 	size = 0;
   1653 	do
   1654 		size += strlen(ev.str) * sizeof(*ev.str);
   1655 	while (history(h, &ev, H_NEXT) == 0);
   1656 
   1657 	/* get to the same position as before */
   1658 	history(h, &ev, H_PREV_EVENT, curr_num);
   1659 
   1660 	return (int)size;
   1661 }
   1662 
   1663 
   1664 /*
   1665  * sets the position in the history list to ``pos''
   1666  */
   1667 int
   1668 history_set_pos(int pos)
   1669 {
   1670 	if (pos >= history_length || pos < 0)
   1671 		return 0;
   1672 
   1673 	history_offset = pos;
   1674 	return 1;
   1675 }
   1676 
   1677 
   1678 /*
   1679  * returns previous event in history and shifts pointer accordingly
   1680  * Note that readline and editline define directions in opposite ways.
   1681  */
   1682 HIST_ENTRY *
   1683 previous_history(void)
   1684 {
   1685 	HistEvent ev;
   1686 
   1687 	if (history_offset == 0)
   1688 		return NULL;
   1689 
   1690 	if (history(h, &ev, H_LAST) != 0)
   1691 		return NULL;
   1692 
   1693 	history_offset--;
   1694 	return current_history();
   1695 }
   1696 
   1697 
   1698 /*
   1699  * returns next event in history and shifts pointer accordingly
   1700  */
   1701 HIST_ENTRY *
   1702 next_history(void)
   1703 {
   1704 	HistEvent ev;
   1705 
   1706 	if (history_offset >= history_length)
   1707 		return NULL;
   1708 
   1709 	if (history(h, &ev, H_LAST) != 0)
   1710 		return NULL;
   1711 
   1712 	history_offset++;
   1713 	return current_history();
   1714 }
   1715 
   1716 
   1717 /*
   1718  * searches for first history event containing the str
   1719  */
   1720 int
   1721 history_search(const char *str, int direction)
   1722 {
   1723 	HistEvent ev;
   1724 	const char *strp;
   1725 	int curr_num;
   1726 
   1727 	if (history(h, &ev, H_CURR) != 0)
   1728 		return -1;
   1729 	curr_num = ev.num;
   1730 
   1731 	for (;;) {
   1732 		if ((strp = strstr(ev.str, str)) != NULL)
   1733 			return (int)(strp - ev.str);
   1734 		if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
   1735 			break;
   1736 	}
   1737 	(void)history(h, &ev, H_SET, curr_num);
   1738 	return -1;
   1739 }
   1740 
   1741 
   1742 /*
   1743  * searches for first history event beginning with str
   1744  */
   1745 int
   1746 history_search_prefix(const char *str, int direction)
   1747 {
   1748 	HistEvent ev;
   1749 
   1750 	return (history(h, &ev, direction < 0 ?
   1751 	    H_PREV_STR : H_NEXT_STR, str));
   1752 }
   1753 
   1754 
   1755 /*
   1756  * search for event in history containing str, starting at offset
   1757  * abs(pos); continue backward, if pos<0, forward otherwise
   1758  */
   1759 /* ARGSUSED */
   1760 int
   1761 history_search_pos(const char *str,
   1762 		   int direction __attribute__((__unused__)), int pos)
   1763 {
   1764 	HistEvent ev;
   1765 	int curr_num, off;
   1766 
   1767 	off = (pos > 0) ? pos : -pos;
   1768 	pos = (pos > 0) ? 1 : -1;
   1769 
   1770 	if (history(h, &ev, H_CURR) != 0)
   1771 		return -1;
   1772 	curr_num = ev.num;
   1773 
   1774 	if (!history_set_pos(off) || history(h, &ev, H_CURR) != 0)
   1775 		return -1;
   1776 
   1777 	for (;;) {
   1778 		if (strstr(ev.str, str))
   1779 			return off;
   1780 		if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
   1781 			break;
   1782 	}
   1783 
   1784 	/* set "current" pointer back to previous state */
   1785 	(void)history(h, &ev,
   1786 	    pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
   1787 
   1788 	return -1;
   1789 }
   1790 
   1791 
   1792 /********************************/
   1793 /* completion functions */
   1794 
   1795 char *
   1796 tilde_expand(char *name)
   1797 {
   1798 	return fn_tilde_expand(name);
   1799 }
   1800 
   1801 char *
   1802 filename_completion_function(const char *name, int state)
   1803 {
   1804 	return fn_filename_completion_function(name, state);
   1805 }
   1806 
   1807 /*
   1808  * a completion generator for usernames; returns _first_ username
   1809  * which starts with supplied text
   1810  * text contains a partial username preceded by random character
   1811  * (usually '~'); state resets search from start (??? should we do that anyway)
   1812  * it's the caller's responsibility to free the returned value
   1813  */
   1814 char *
   1815 username_completion_function(const char *text, int state)
   1816 {
   1817 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
   1818 	struct passwd pwres;
   1819 	char pwbuf[1024];
   1820 #endif
   1821 	struct passwd *pass = NULL;
   1822 
   1823 	if (text[0] == '\0')
   1824 		return NULL;
   1825 
   1826 	if (*text == '~')
   1827 		text++;
   1828 
   1829 	if (state == 0)
   1830 		setpwent();
   1831 
   1832 	while (
   1833 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
   1834 	    getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pass) == 0 && pass != NULL
   1835 #else
   1836 	    (pass = getpwent()) != NULL
   1837 #endif
   1838 	    && text[0] == pass->pw_name[0]
   1839 	    && strcmp(text, pass->pw_name) == 0)
   1840 		continue;
   1841 
   1842 	if (pass == NULL) {
   1843 		endpwent();
   1844 		return NULL;
   1845 	}
   1846 	return strdup(pass->pw_name);
   1847 }
   1848 
   1849 
   1850 /*
   1851  * el-compatible wrapper to send TSTP on ^Z
   1852  */
   1853 /* ARGSUSED */
   1854 static unsigned char
   1855 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
   1856 {
   1857 	(void)kill(0, SIGTSTP);
   1858 	return CC_NORM;
   1859 }
   1860 
   1861 static const char *
   1862 /*ARGSUSED*/
   1863 _rl_completion_append_character_function(const char *dummy
   1864     __attribute__((__unused__)))
   1865 {
   1866 	static char buf[2];
   1867 	buf[0] = (char)rl_completion_append_character;
   1868 	buf[1] = '\0';
   1869 	return buf;
   1870 }
   1871 
   1872 
   1873 /*
   1874  * Display list of strings in columnar format on readline's output stream.
   1875  * 'matches' is list of strings, 'len' is number of strings in 'matches',
   1876  * 'max' is maximum length of string in 'matches'.
   1877  */
   1878 void
   1879 rl_display_match_list(char **matches, int len, int max)
   1880 {
   1881 
   1882 	fn_display_match_list(e, matches, (size_t)len, (size_t)max,
   1883 		_rl_completion_append_character_function);
   1884 }
   1885 
   1886 /*
   1887  * complete word at current point
   1888  */
   1889 /* ARGSUSED */
   1890 int
   1891 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
   1892 {
   1893 	static ct_buffer_t wbreak_conv, sprefix_conv;
   1894 	const char *breakchars;
   1895 
   1896 	if (h == NULL || e == NULL)
   1897 		rl_initialize();
   1898 
   1899 	if (rl_inhibit_completion) {
   1900 		char arr[2];
   1901 		arr[0] = (char)invoking_key;
   1902 		arr[1] = '\0';
   1903 		el_insertstr(e, arr);
   1904 		return CC_REFRESH;
   1905 	}
   1906 
   1907 	if (rl_completion_word_break_hook != NULL)
   1908 		breakchars = (*rl_completion_word_break_hook)();
   1909 	else
   1910 		breakchars = rl_basic_word_break_characters;
   1911 
   1912 	_rl_update_pos();
   1913 
   1914 	/* Just look at how many global variables modify this operation! */
   1915 	return fn_complete(e,
   1916 	    (rl_compentry_func_t *)rl_completion_entry_function,
   1917 	    rl_attempted_completion_function,
   1918 	    ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
   1919 	    ct_decode_string(breakchars, &sprefix_conv),
   1920 	    _rl_completion_append_character_function,
   1921 	    (size_t)rl_completion_query_items,
   1922 	    &rl_completion_type, &rl_attempted_completion_over,
   1923 	    &rl_point, &rl_end);
   1924 
   1925 
   1926 }
   1927 
   1928 
   1929 /* ARGSUSED */
   1930 static unsigned char
   1931 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
   1932 {
   1933 	return (unsigned char)rl_complete(0, ch);
   1934 }
   1935 
   1936 /*
   1937  * misc other functions
   1938  */
   1939 
   1940 /*
   1941  * bind key c to readline-type function func
   1942  */
   1943 int
   1944 rl_bind_key(int c, rl_command_func_t *func)
   1945 {
   1946 	int retval = -1;
   1947 
   1948 	if (h == NULL || e == NULL)
   1949 		rl_initialize();
   1950 
   1951 	if (func == rl_insert) {
   1952 		/* XXX notice there is no range checking of ``c'' */
   1953 		e->el_map.key[c] = ED_INSERT;
   1954 		retval = 0;
   1955 	}
   1956 	return retval;
   1957 }
   1958 
   1959 
   1960 /*
   1961  * read one key from input - handles chars pushed back
   1962  * to input stream also
   1963  */
   1964 int
   1965 rl_read_key(void)
   1966 {
   1967 	char fooarr[2 * sizeof(int)];
   1968 
   1969 	if (e == NULL || h == NULL)
   1970 		rl_initialize();
   1971 
   1972 	return el_getc(e, fooarr);
   1973 }
   1974 
   1975 
   1976 /*
   1977  * reset the terminal
   1978  */
   1979 /* ARGSUSED */
   1980 int
   1981 rl_reset_terminal(const char *p __attribute__((__unused__)))
   1982 {
   1983 
   1984 	if (h == NULL || e == NULL)
   1985 		rl_initialize();
   1986 	el_reset(e);
   1987 	return 0;
   1988 }
   1989 
   1990 
   1991 /*
   1992  * insert character ``c'' back into input stream, ``count'' times
   1993  */
   1994 int
   1995 rl_insert(int count, int c)
   1996 {
   1997 	char arr[2];
   1998 
   1999 	if (h == NULL || e == NULL)
   2000 		rl_initialize();
   2001 
   2002 	/* XXX - int -> char conversion can lose on multichars */
   2003 	arr[0] = (char)c;
   2004 	arr[1] = '\0';
   2005 
   2006 	for (; count > 0; count--)
   2007 		el_push(e, arr);
   2008 
   2009 	return 0;
   2010 }
   2011 
   2012 int
   2013 rl_insert_text(const char *text)
   2014 {
   2015 	if (!text || *text == 0)
   2016 		return 0;
   2017 
   2018 	if (h == NULL || e == NULL)
   2019 		rl_initialize();
   2020 
   2021 	if (el_insertstr(e, text) < 0)
   2022 		return 0;
   2023 	return (int)strlen(text);
   2024 }
   2025 
   2026 /*ARGSUSED*/
   2027 int
   2028 rl_newline(int count __attribute__((__unused__)),
   2029     int c __attribute__((__unused__)))
   2030 {
   2031 	/*
   2032 	 * Readline-4.0 appears to ignore the args.
   2033 	 */
   2034 	return rl_insert(1, '\n');
   2035 }
   2036 
   2037 /*ARGSUSED*/
   2038 static unsigned char
   2039 rl_bind_wrapper(EditLine *el __attribute__((__unused__)), unsigned char c)
   2040 {
   2041 	if (map[c] == NULL)
   2042 	    return CC_ERROR;
   2043 
   2044 	_rl_update_pos();
   2045 
   2046 	(*map[c])(1, c);
   2047 
   2048 	/* If rl_done was set by the above call, deal with it here */
   2049 	if (rl_done)
   2050 		return CC_EOF;
   2051 
   2052 	return CC_NORM;
   2053 }
   2054 
   2055 int
   2056 rl_add_defun(const char *name, rl_command_func_t *fun, int c)
   2057 {
   2058 	char dest[8];
   2059 	if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
   2060 		return -1;
   2061 	map[(unsigned char)c] = fun;
   2062 	el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
   2063 	vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
   2064 	el_set(e, EL_BIND, dest, name, NULL);
   2065 	return 0;
   2066 }
   2067 
   2068 void
   2069 rl_callback_read_char(void)
   2070 {
   2071 	int count = 0, done = 0;
   2072 	const char *buf = el_gets(e, &count);
   2073 	char *wbuf;
   2074 
   2075 	if (buf == NULL || count-- <= 0)
   2076 		return;
   2077 	if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
   2078 		done = 1;
   2079 	if (buf[count] == '\n' || buf[count] == '\r')
   2080 		done = 2;
   2081 
   2082 	if (done && rl_linefunc != NULL) {
   2083 		el_set(e, EL_UNBUFFERED, 0);
   2084 		if (done == 2) {
   2085 			if ((wbuf = strdup(buf)) != NULL)
   2086 				wbuf[count] = '\0';
   2087 		} else
   2088 			wbuf = NULL;
   2089 		(*(void (*)(const char *))rl_linefunc)(wbuf);
   2090 		el_set(e, EL_UNBUFFERED, 1);
   2091 	}
   2092 }
   2093 
   2094 void
   2095 rl_callback_handler_install(const char *prompt, rl_vcpfunc_t *linefunc)
   2096 {
   2097 	if (e == NULL) {
   2098 		rl_initialize();
   2099 	}
   2100 	(void)rl_set_prompt(prompt);
   2101 	rl_linefunc = linefunc;
   2102 	el_set(e, EL_UNBUFFERED, 1);
   2103 }
   2104 
   2105 void
   2106 rl_callback_handler_remove(void)
   2107 {
   2108 	rl_linefunc = NULL;
   2109 	el_end(e);
   2110 	e = NULL;
   2111 }
   2112 
   2113 void
   2114 rl_redisplay(void)
   2115 {
   2116 	char a[2];
   2117 	a[0] = (char)e->el_tty.t_c[TS_IO][C_REPRINT];
   2118 	a[1] = '\0';
   2119 	el_push(e, a);
   2120 }
   2121 
   2122 int
   2123 rl_get_previous_history(int count, int key)
   2124 {
   2125 	char a[2];
   2126 	a[0] = (char)key;
   2127 	a[1] = '\0';
   2128 	while (count--)
   2129 		el_push(e, a);
   2130 	return 0;
   2131 }
   2132 
   2133 void
   2134 /*ARGSUSED*/
   2135 rl_prep_terminal(int meta_flag __attribute__((__unused__)))
   2136 {
   2137 	el_set(e, EL_PREP_TERM, 1);
   2138 }
   2139 
   2140 void
   2141 rl_deprep_terminal(void)
   2142 {
   2143 	el_set(e, EL_PREP_TERM, 0);
   2144 }
   2145 
   2146 int
   2147 rl_read_init_file(const char *s)
   2148 {
   2149 	return el_source(e, s);
   2150 }
   2151 
   2152 int
   2153 rl_parse_and_bind(const char *line)
   2154 {
   2155 	const char **argv;
   2156 	int argc;
   2157 	Tokenizer *tok;
   2158 
   2159 	tok = tok_init(NULL);
   2160 	tok_str(tok, line, &argc, &argv);
   2161 	argc = el_parse(e, argc, argv);
   2162 	tok_end(tok);
   2163 	return argc ? 1 : 0;
   2164 }
   2165 
   2166 int
   2167 rl_variable_bind(const char *var, const char *value)
   2168 {
   2169 	/*
   2170 	 * The proper return value is undocument, but this is what the
   2171 	 * readline source seems to do.
   2172 	 */
   2173 	return el_set(e, EL_BIND, "", var, value, NULL) == -1 ? 1 : 0;
   2174 }
   2175 
   2176 int
   2177 rl_stuff_char(int c)
   2178 {
   2179 	char buf[2];
   2180 
   2181 	buf[0] = (char)c;
   2182 	buf[1] = '\0';
   2183 	el_insertstr(e, buf);
   2184 	return 1;
   2185 }
   2186 
   2187 static int
   2188 _rl_event_read_char(EditLine *el, wchar_t *wc)
   2189 {
   2190 	char	ch;
   2191 	int	n;
   2192 	ssize_t num_read = 0;
   2193 
   2194 	ch = '\0';
   2195 	*wc = L'\0';
   2196 	while (rl_event_hook) {
   2197 
   2198 		(*rl_event_hook)();
   2199 
   2200 #if defined(FIONREAD)
   2201 		if (ioctl(el->el_infd, FIONREAD, &n) < 0)
   2202 			return -1;
   2203 		if (n)
   2204 			num_read = read(el->el_infd, &ch, (size_t)1);
   2205 		else
   2206 			num_read = 0;
   2207 #elif defined(F_SETFL) && defined(O_NDELAY)
   2208 		if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
   2209 			return -1;
   2210 		if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
   2211 			return -1;
   2212 		num_read = read(el->el_infd, &ch, 1);
   2213 		if (fcntl(el->el_infd, F_SETFL, n))
   2214 			return -1;
   2215 #else
   2216 		/* not non-blocking, but what you gonna do? */
   2217 		num_read = read(el->el_infd, &ch, 1);
   2218 		return -1;
   2219 #endif
   2220 
   2221 		if (num_read < 0 && errno == EAGAIN)
   2222 			continue;
   2223 		if (num_read == 0)
   2224 			continue;
   2225 		break;
   2226 	}
   2227 	if (!rl_event_hook)
   2228 		el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
   2229 	*wc = (wchar_t)ch;
   2230 	return (int)num_read;
   2231 }
   2232 
   2233 static void
   2234 _rl_update_pos(void)
   2235 {
   2236 	const LineInfo *li = el_line(e);
   2237 
   2238 	rl_point = (int)(li->cursor - li->buffer);
   2239 	rl_end = (int)(li->lastchar - li->buffer);
   2240 }
   2241 
   2242 void
   2243 rl_get_screen_size(int *rows, int *cols)
   2244 {
   2245 	if (rows)
   2246 		el_get(e, EL_GETTC, "li", rows);
   2247 	if (cols)
   2248 		el_get(e, EL_GETTC, "co", cols);
   2249 }
   2250 
   2251 void
   2252 rl_set_screen_size(int rows, int cols)
   2253 {
   2254 	char buf[64];
   2255 	(void)snprintf(buf, sizeof(buf), "%d", rows);
   2256 	el_set(e, EL_SETTC, "li", buf, NULL);
   2257 	(void)snprintf(buf, sizeof(buf), "%d", cols);
   2258 	el_set(e, EL_SETTC, "co", buf, NULL);
   2259 }
   2260 
   2261 char **
   2262 rl_completion_matches(const char *str, rl_compentry_func_t *fun)
   2263 {
   2264 	size_t len, max, i, j, min;
   2265 	char **list, *match, *a, *b;
   2266 
   2267 	len = 1;
   2268 	max = 10;
   2269 	if ((list = el_malloc(max * sizeof(*list))) == NULL)
   2270 		return NULL;
   2271 
   2272 	while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
   2273 		list[len++] = match;
   2274 		if (len == max) {
   2275 			char **nl;
   2276 			max += 10;
   2277 			if ((nl = el_realloc(list, max * sizeof(*nl))) == NULL)
   2278 				goto out;
   2279 			list = nl;
   2280 		}
   2281 	}
   2282 	if (len == 1)
   2283 		goto out;
   2284 	list[len] = NULL;
   2285 	if (len == 2) {
   2286 		if ((list[0] = strdup(list[1])) == NULL)
   2287 			goto out;
   2288 		return list;
   2289 	}
   2290 	qsort(&list[1], len - 1, sizeof(*list),
   2291 	    (int (*)(const void *, const void *)) strcmp);
   2292 	min = SIZE_MAX;
   2293 	for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
   2294 		b = list[i + 1];
   2295 		for (j = 0; a[j] && a[j] == b[j]; j++)
   2296 			continue;
   2297 		if (min > j)
   2298 			min = j;
   2299 	}
   2300 	if (min == 0 && *str) {
   2301 		if ((list[0] = strdup(str)) == NULL)
   2302 			goto out;
   2303 	} else {
   2304 		if ((list[0] = el_malloc((min + 1) * sizeof(*list[0]))) == NULL)
   2305 			goto out;
   2306 		(void)memcpy(list[0], list[1], min);
   2307 		list[0][min] = '\0';
   2308 	}
   2309 	return list;
   2310 
   2311 out:
   2312 	el_free(list);
   2313 	return NULL;
   2314 }
   2315 
   2316 char *
   2317 rl_filename_completion_function (const char *text, int state)
   2318 {
   2319 	return fn_filename_completion_function(text, state);
   2320 }
   2321 
   2322 void
   2323 rl_forced_update_display(void)
   2324 {
   2325 	el_set(e, EL_REFRESH);
   2326 }
   2327 
   2328 int
   2329 _rl_abort_internal(void)
   2330 {
   2331 	el_beep(e);
   2332 	longjmp(topbuf, 1);
   2333 	/*NOTREACHED*/
   2334 }
   2335 
   2336 int
   2337 _rl_qsort_string_compare(char **s1, char **s2)
   2338 {
   2339 	return strcoll(*s1, *s2);
   2340 }
   2341 
   2342 HISTORY_STATE *
   2343 history_get_history_state(void)
   2344 {
   2345 	HISTORY_STATE *hs;
   2346 
   2347 	if ((hs = el_malloc(sizeof(*hs))) == NULL)
   2348 		return NULL;
   2349 	hs->length = history_length;
   2350 	return hs;
   2351 }
   2352 
   2353 int
   2354 /*ARGSUSED*/
   2355 rl_kill_text(int from __attribute__((__unused__)),
   2356     int to __attribute__((__unused__)))
   2357 {
   2358 	return 0;
   2359 }
   2360 
   2361 Keymap
   2362 rl_make_bare_keymap(void)
   2363 {
   2364 	return NULL;
   2365 }
   2366 
   2367 Keymap
   2368 rl_get_keymap(void)
   2369 {
   2370 	return NULL;
   2371 }
   2372 
   2373 void
   2374 /*ARGSUSED*/
   2375 rl_set_keymap(Keymap k __attribute__((__unused__)))
   2376 {
   2377 }
   2378 
   2379 int
   2380 /*ARGSUSED*/
   2381 rl_generic_bind(int type __attribute__((__unused__)),
   2382     const char * keyseq __attribute__((__unused__)),
   2383     const char * data __attribute__((__unused__)),
   2384     Keymap k __attribute__((__unused__)))
   2385 {
   2386 	return 0;
   2387 }
   2388 
   2389 int
   2390 /*ARGSUSED*/
   2391 rl_bind_key_in_map(int key __attribute__((__unused__)),
   2392     rl_command_func_t *fun __attribute__((__unused__)),
   2393     Keymap k __attribute__((__unused__)))
   2394 {
   2395 	return 0;
   2396 }
   2397 
   2398 /* unsupported, but needed by python */
   2399 void
   2400 rl_cleanup_after_signal(void)
   2401 {
   2402 }
   2403 
   2404 int
   2405 rl_on_new_line(void)
   2406 {
   2407 	return 0;
   2408 }
   2409 
   2410 void
   2411 rl_free_line_state(void)
   2412 {
   2413 }
   2414 
   2415 int
   2416 /*ARGSUSED*/
   2417 rl_set_keyboard_input_timeout(int u __attribute__((__unused__)))
   2418 {
   2419 	return 0;
   2420 }
   2421 
   2422 void
   2423 rl_resize_terminal(void)
   2424 {
   2425 	el_resize(e);
   2426 }
   2427 
   2428 void
   2429 rl_reset_after_signal(void)
   2430 {
   2431 	if (rl_prep_term_function)
   2432 		(*rl_prep_term_function)();
   2433 }
   2434 
   2435 void
   2436 rl_echo_signal_char(int sig)
   2437 {
   2438 	int c = tty_get_signal_character(e, sig);
   2439 	if (c == -1)
   2440 		return;
   2441 	re_putc(e, c, 0);
   2442 }
   2443