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