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