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