Home | History | Annotate | Line # | Download | only in libedit
readline.c revision 1.58
      1 /*	$NetBSD: readline.c,v 1.58 2005/07/14 15:00:58 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  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include "config.h"
     40 #if !defined(lint) && !defined(SCCSID)
     41 __RCSID("$NetBSD: readline.c,v 1.58 2005/07/14 15:00:58 christos Exp $");
     42 #endif /* not lint && not SCCSID */
     43 
     44 #include <sys/types.h>
     45 #include <sys/stat.h>
     46 #include <stdio.h>
     47 #include <dirent.h>
     48 #include <string.h>
     49 #include <pwd.h>
     50 #include <ctype.h>
     51 #include <stdlib.h>
     52 #include <unistd.h>
     53 #include <limits.h>
     54 #include <errno.h>
     55 #include <fcntl.h>
     56 #ifdef HAVE_VIS_H
     57 #include <vis.h>
     58 #else
     59 #include "np/vis.h"
     60 #endif
     61 #ifdef HAVE_ALLOCA_H
     62 #include <alloca.h>
     63 #endif
     64 #include "el.h"
     65 #include "fcns.h"		/* for EL_NUM_FCNS */
     66 #include "histedit.h"
     67 #include "readline/readline.h"
     68 #include "filecomplete.h"
     69 
     70 /* for rl_complete() */
     71 #define TAB		'\r'
     72 
     73 /* see comment at the #ifdef for sense of this */
     74 /* #define GDB_411_HACK */
     75 
     76 /* readline compatibility stuff - look at readline sources/documentation */
     77 /* to see what these variables mean */
     78 const char *rl_library_version = "EditLine wrapper";
     79 static char empty[] = { '\0' };
     80 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
     81 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
     82     '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
     83 char *rl_readline_name = empty;
     84 FILE *rl_instream = NULL;
     85 FILE *rl_outstream = NULL;
     86 int rl_point = 0;
     87 int rl_end = 0;
     88 char *rl_line_buffer = NULL;
     89 VCPFunction *rl_linefunc = NULL;
     90 int rl_done = 0;
     91 VFunction *rl_event_hook = NULL;
     92 
     93 int history_base = 1;		/* probably never subject to change */
     94 int history_length = 0;
     95 int max_input_history = 0;
     96 char history_expansion_char = '!';
     97 char history_subst_char = '^';
     98 char *history_no_expand_chars = expand_chars;
     99 Function *history_inhibit_expansion_function = NULL;
    100 char *history_arg_extract(int start, int end, const char *str);
    101 
    102 int rl_inhibit_completion = 0;
    103 int rl_attempted_completion_over = 0;
    104 char *rl_basic_word_break_characters = break_chars;
    105 char *rl_completer_word_break_characters = NULL;
    106 char *rl_completer_quote_characters = NULL;
    107 Function *rl_completion_entry_function = NULL;
    108 CPPFunction *rl_attempted_completion_function = NULL;
    109 Function *rl_pre_input_hook = NULL;
    110 Function *rl_startup1_hook = NULL;
    111 Function *rl_getc_function = NULL;
    112 char *rl_terminal_name = NULL;
    113 int rl_already_prompted = 0;
    114 int rl_filename_completion_desired = 0;
    115 int rl_ignore_completion_duplicates = 0;
    116 int rl_catch_signals = 1;
    117 VFunction *rl_redisplay_function = NULL;
    118 Function *rl_startup_hook = NULL;
    119 VFunction *rl_completion_display_matches_hook = NULL;
    120 VFunction *rl_prep_term_function = NULL;
    121 VFunction *rl_deprep_term_function = NULL;
    122 
    123 /*
    124  * The current prompt string.
    125  */
    126 char *rl_prompt = NULL;
    127 /*
    128  * This is set to character indicating type of completion being done by
    129  * rl_complete_internal(); this is available for application completion
    130  * functions.
    131  */
    132 int rl_completion_type = 0;
    133 
    134 /*
    135  * If more than this number of items results from query for possible
    136  * completions, we ask user if they are sure to really display the list.
    137  */
    138 int rl_completion_query_items = 100;
    139 
    140 /*
    141  * List of characters which are word break characters, but should be left
    142  * in the parsed text when it is passed to the completion function.
    143  * Shell uses this to help determine what kind of completing to do.
    144  */
    145 char *rl_special_prefixes = NULL;
    146 
    147 /*
    148  * This is the character appended to the completed words if at the end of
    149  * the line. Default is ' ' (a space).
    150  */
    151 int rl_completion_append_character = ' ';
    152 
    153 /* stuff below is used internally by libedit for readline emulation */
    154 
    155 static History *h = NULL;
    156 static EditLine *e = NULL;
    157 static Function *map[256];
    158 
    159 /* internal functions */
    160 static unsigned char	 _el_rl_complete(EditLine *, int);
    161 static unsigned char	 _el_rl_tstp(EditLine *, int);
    162 static char		*_get_prompt(EditLine *);
    163 static HIST_ENTRY	*_move_history(int);
    164 static int		 _history_expand_command(const char *, size_t, size_t,
    165     char **);
    166 static char		*_rl_compat_sub(const char *, const char *,
    167     const char *, int);
    168 static int		 _rl_event_read_char(EditLine *, char *);
    169 static void		 _rl_update_pos(void);
    170 
    171 
    172 /* ARGSUSED */
    173 static char *
    174 _get_prompt(EditLine *el __attribute__((__unused__)))
    175 {
    176 	rl_already_prompted = 1;
    177 	return (rl_prompt);
    178 }
    179 
    180 
    181 /*
    182  * generic function for moving around history
    183  */
    184 static HIST_ENTRY *
    185 _move_history(int op)
    186 {
    187 	HistEvent ev;
    188 	static HIST_ENTRY rl_he;
    189 
    190 	if (history(h, &ev, op) != 0)
    191 		return (HIST_ENTRY *) NULL;
    192 
    193 	rl_he.line = ev.str;
    194 	rl_he.data = NULL;
    195 
    196 	return (&rl_he);
    197 }
    198 
    199 
    200 /*
    201  * READLINE compatibility stuff
    202  */
    203 
    204 /*
    205  * initialize rl compat stuff
    206  */
    207 int
    208 rl_initialize(void)
    209 {
    210 	HistEvent ev;
    211 	const LineInfo *li;
    212 	int editmode = 1;
    213 	struct termios t;
    214 
    215 	if (e != NULL)
    216 		el_end(e);
    217 	if (h != NULL)
    218 		history_end(h);
    219 
    220 	if (!rl_instream)
    221 		rl_instream = stdin;
    222 	if (!rl_outstream)
    223 		rl_outstream = stdout;
    224 
    225 	/*
    226 	 * See if we don't really want to run the editor
    227 	 */
    228 	if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
    229 		editmode = 0;
    230 
    231 	e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
    232 
    233 	if (!editmode)
    234 		el_set(e, EL_EDITMODE, 0);
    235 
    236 	h = history_init();
    237 	if (!e || !h)
    238 		return (-1);
    239 
    240 	history(h, &ev, H_SETSIZE, INT_MAX);	/* unlimited */
    241 	history_length = 0;
    242 	max_input_history = INT_MAX;
    243 	el_set(e, EL_HIST, history, h);
    244 
    245 	/* for proper prompt printing in readline() */
    246 	rl_prompt = strdup("");
    247 	if (rl_prompt == NULL) {
    248 		history_end(h);
    249 		el_end(e);
    250 		return -1;
    251 	}
    252 	el_set(e, EL_PROMPT, _get_prompt);
    253 	el_set(e, EL_SIGNAL, rl_catch_signals);
    254 
    255 	/* set default mode to "emacs"-style and read setting afterwards */
    256 	/* so this can be overriden */
    257 	el_set(e, EL_EDITOR, "emacs");
    258 	if (rl_terminal_name != NULL)
    259 		el_set(e, EL_TERMINAL, rl_terminal_name);
    260 	else
    261 		el_get(e, EL_TERMINAL, &rl_terminal_name);
    262 
    263 	/*
    264 	 * Word completion - this has to go AFTER rebinding keys
    265 	 * to emacs-style.
    266 	 */
    267 	el_set(e, EL_ADDFN, "rl_complete",
    268 	    "ReadLine compatible completion function",
    269 	    _el_rl_complete);
    270 	el_set(e, EL_BIND, "^I", "rl_complete", NULL);
    271 
    272 	/*
    273 	 * Send TSTP when ^Z is pressed.
    274 	 */
    275 	el_set(e, EL_ADDFN, "rl_tstp",
    276 	    "ReadLine compatible suspend function",
    277 	    _el_rl_tstp);
    278 	el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
    279 
    280 	/* read settings from configuration file */
    281 	el_source(e, NULL);
    282 
    283 	/*
    284 	 * Unfortunately, some applications really do use rl_point
    285 	 * and rl_line_buffer directly.
    286 	 */
    287 	li = el_line(e);
    288 	/* a cheesy way to get rid of const cast. */
    289 	rl_line_buffer = memchr(li->buffer, *li->buffer, 1);
    290 	_rl_update_pos();
    291 
    292 	if (rl_startup_hook)
    293 		(*rl_startup_hook)(NULL, 0);
    294 
    295 	return (0);
    296 }
    297 
    298 
    299 /*
    300  * read one line from input stream and return it, chomping
    301  * trailing newline (if there is any)
    302  */
    303 char *
    304 readline(const char *prompt)
    305 {
    306 	HistEvent ev;
    307 	int count;
    308 	const char *ret;
    309 	char *buf;
    310 	static int used_event_hook;
    311 
    312 	if (e == NULL || h == NULL)
    313 		rl_initialize();
    314 
    315 	rl_done = 0;
    316 
    317 	/* update prompt accordingly to what has been passed */
    318 	if (!prompt)
    319 		prompt = "";
    320 	if (strcmp(rl_prompt, prompt) != 0) {
    321 		free(rl_prompt);
    322 		rl_prompt = strdup(prompt);
    323 		if (rl_prompt == NULL)
    324 			return NULL;
    325 	}
    326 
    327 	if (rl_pre_input_hook)
    328 		(*rl_pre_input_hook)(NULL, 0);
    329 
    330 	if (rl_event_hook && !(e->el_flags&NO_TTY)) {
    331 		el_set(e, EL_GETCFN, _rl_event_read_char);
    332 		used_event_hook = 1;
    333 	}
    334 
    335 	if (!rl_event_hook && used_event_hook) {
    336 		el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
    337 		used_event_hook = 0;
    338 	}
    339 
    340 	rl_already_prompted = 0;
    341 
    342 	/* get one line from input stream */
    343 	ret = el_gets(e, &count);
    344 
    345 	if (ret && count > 0) {
    346 		int lastidx;
    347 
    348 		buf = strdup(ret);
    349 		if (buf == NULL)
    350 			return NULL;
    351 		lastidx = count - 1;
    352 		if (buf[lastidx] == '\n')
    353 			buf[lastidx] = '\0';
    354 	} else
    355 		buf = NULL;
    356 
    357 	history(h, &ev, H_GETSIZE);
    358 	history_length = ev.num;
    359 
    360 	return buf;
    361 }
    362 
    363 /*
    364  * history functions
    365  */
    366 
    367 /*
    368  * is normally called before application starts to use
    369  * history expansion functions
    370  */
    371 void
    372 using_history(void)
    373 {
    374 	if (h == NULL || e == NULL)
    375 		rl_initialize();
    376 }
    377 
    378 
    379 /*
    380  * substitute ``what'' with ``with'', returning resulting string; if
    381  * globally == 1, substitutes all occurrences of what, otherwise only the
    382  * first one
    383  */
    384 static char *
    385 _rl_compat_sub(const char *str, const char *what, const char *with,
    386     int globally)
    387 {
    388 	const	char	*s;
    389 	char	*r, *result;
    390 	size_t	len, with_len, what_len;
    391 
    392 	len = strlen(str);
    393 	with_len = strlen(with);
    394 	what_len = strlen(what);
    395 
    396 	/* calculate length we need for result */
    397 	s = str;
    398 	while (*s) {
    399 		if (*s == *what && !strncmp(s, what, what_len)) {
    400 			len += with_len - what_len;
    401 			if (!globally)
    402 				break;
    403 			s += what_len;
    404 		} else
    405 			s++;
    406 	}
    407 	r = result = malloc(len + 1);
    408 	if (result == NULL)
    409 		return NULL;
    410 	s = str;
    411 	while (*s) {
    412 		if (*s == *what && !strncmp(s, what, what_len)) {
    413 			(void)strncpy(r, with, with_len);
    414 			r += with_len;
    415 			s += what_len;
    416 			if (!globally) {
    417 				(void)strcpy(r, s);
    418 				return(result);
    419 			}
    420 		} else
    421 			*r++ = *s++;
    422 	}
    423 	*r = 0;
    424 	return(result);
    425 }
    426 
    427 static	char	*last_search_pat;	/* last !?pat[?] search pattern */
    428 static	char	*last_search_match;	/* last !?pat[?] that matched */
    429 
    430 const char *
    431 get_history_event(const char *cmd, int *cindex, int qchar)
    432 {
    433 	int idx, sign, sub, num, begin, ret;
    434 	size_t len;
    435 	char	*pat;
    436 	const char *rptr;
    437 	HistEvent ev;
    438 
    439 	idx = *cindex;
    440 	if (cmd[idx++] != history_expansion_char)
    441 		return(NULL);
    442 
    443 	/* find out which event to take */
    444 	if (cmd[idx] == history_expansion_char || cmd[idx] == 0) {
    445 		if (history(h, &ev, H_FIRST) != 0)
    446 			return(NULL);
    447 		*cindex = cmd[idx]? (idx + 1):idx;
    448 		return(ev.str);
    449 	}
    450 	sign = 0;
    451 	if (cmd[idx] == '-') {
    452 		sign = 1;
    453 		idx++;
    454 	}
    455 
    456 	if ('0' <= cmd[idx] && cmd[idx] <= '9') {
    457 		HIST_ENTRY *rl_he;
    458 
    459 		num = 0;
    460 		while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
    461 			num = num * 10 + cmd[idx] - '0';
    462 			idx++;
    463 		}
    464 		if (sign)
    465 			num = history_length - num + 1;
    466 
    467 		if (!(rl_he = history_get(num)))
    468 			return(NULL);
    469 
    470 		*cindex = idx;
    471 		return(rl_he->line);
    472 	}
    473 	sub = 0;
    474 	if (cmd[idx] == '?') {
    475 		sub = 1;
    476 		idx++;
    477 	}
    478 	begin = idx;
    479 	while (cmd[idx]) {
    480 		if (cmd[idx] == '\n')
    481 			break;
    482 		if (sub && cmd[idx] == '?')
    483 			break;
    484 		if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
    485 				    || cmd[idx] == '\t' || cmd[idx] == qchar))
    486 			break;
    487 		idx++;
    488 	}
    489 	len = idx - begin;
    490 	if (sub && cmd[idx] == '?')
    491 		idx++;
    492 	if (sub && len == 0 && last_search_pat && *last_search_pat)
    493 		pat = last_search_pat;
    494 	else if (len == 0)
    495 		return(NULL);
    496 	else {
    497 		if ((pat = malloc(len + 1)) == NULL)
    498 			return NULL;
    499 		(void)strncpy(pat, cmd + begin, len);
    500 		pat[len] = '\0';
    501 	}
    502 
    503 	if (history(h, &ev, H_CURR) != 0) {
    504 		if (pat != last_search_pat)
    505 			free(pat);
    506 		return (NULL);
    507 	}
    508 	num = ev.num;
    509 
    510 	if (sub) {
    511 		if (pat != last_search_pat) {
    512 			if (last_search_pat)
    513 				free(last_search_pat);
    514 			last_search_pat = pat;
    515 		}
    516 		ret = history_search(pat, -1);
    517 	} else
    518 		ret = history_search_prefix(pat, -1);
    519 
    520 	if (ret == -1) {
    521 		/* restore to end of list on failed search */
    522 		history(h, &ev, H_FIRST);
    523 		(void)fprintf(rl_outstream, "%s: Event not found\n", pat);
    524 		if (pat != last_search_pat)
    525 			free(pat);
    526 		return(NULL);
    527 	}
    528 
    529 	if (sub && len) {
    530 		if (last_search_match && last_search_match != pat)
    531 			free(last_search_match);
    532 		last_search_match = pat;
    533 	}
    534 
    535 	if (pat != last_search_pat)
    536 		free(pat);
    537 
    538 	if (history(h, &ev, H_CURR) != 0)
    539 		return(NULL);
    540 	*cindex = idx;
    541 	rptr = ev.str;
    542 
    543 	/* roll back to original position */
    544 	(void)history(h, &ev, H_SET, num);
    545 
    546 	return rptr;
    547 }
    548 
    549 /*
    550  * the real function doing history expansion - takes as argument command
    551  * to do and data upon which the command should be executed
    552  * does expansion the way I've understood readline documentation
    553  *
    554  * returns 0 if data was not modified, 1 if it was and 2 if the string
    555  * should be only printed and not executed; in case of error,
    556  * returns -1 and *result points to NULL
    557  * it's callers responsibility to free() string returned in *result
    558  */
    559 static int
    560 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
    561     char **result)
    562 {
    563 	char *tmp, *search = NULL, *aptr;
    564 	const char *ptr, *cmd;
    565 	static char *from = NULL, *to = NULL;
    566 	int start, end, idx, has_mods = 0;
    567 	int p_on = 0, g_on = 0;
    568 
    569 	*result = NULL;
    570 	aptr = NULL;
    571 	ptr = NULL;
    572 
    573 	/* First get event specifier */
    574 	idx = 0;
    575 
    576 	if (strchr(":^*$", command[offs + 1])) {
    577 		char str[4];
    578 		/*
    579 		* "!:" is shorthand for "!!:".
    580 		* "!^", "!*" and "!$" are shorthand for
    581 		* "!!:^", "!!:*" and "!!:$" respectively.
    582 		*/
    583 		str[0] = str[1] = '!';
    584 		str[2] = '0';
    585 		ptr = get_history_event(str, &idx, 0);
    586 		idx = (command[offs + 1] == ':')? 1:0;
    587 		has_mods = 1;
    588 	} else {
    589 		if (command[offs + 1] == '#') {
    590 			/* use command so far */
    591 			if ((aptr = malloc(offs + 1)) == NULL)
    592 				return -1;
    593 			(void)strncpy(aptr, command, offs);
    594 			aptr[offs] = '\0';
    595 			idx = 1;
    596 		} else {
    597 			int	qchar;
    598 
    599 			qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
    600 			ptr = get_history_event(command + offs, &idx, qchar);
    601 		}
    602 		has_mods = command[offs + idx] == ':';
    603 	}
    604 
    605 	if (ptr == NULL && aptr == NULL)
    606 		return(-1);
    607 
    608 	if (!has_mods) {
    609 		*result = strdup(aptr? aptr : ptr);
    610 		if (aptr)
    611 			free(aptr);
    612 		return(1);
    613 	}
    614 
    615 	cmd = command + offs + idx + 1;
    616 
    617 	/* Now parse any word designators */
    618 
    619 	if (*cmd == '%')	/* last word matched by ?pat? */
    620 		tmp = strdup(last_search_match? last_search_match:"");
    621 	else if (strchr("^*$-0123456789", *cmd)) {
    622 		start = end = -1;
    623 		if (*cmd == '^')
    624 			start = end = 1, cmd++;
    625 		else if (*cmd == '$')
    626 			start = -1, cmd++;
    627 		else if (*cmd == '*')
    628 			start = 1, cmd++;
    629 	       else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
    630 			start = 0;
    631 			while (*cmd && '0' <= *cmd && *cmd <= '9')
    632 				start = start * 10 + *cmd++ - '0';
    633 
    634 			if (*cmd == '-') {
    635 				if (isdigit((unsigned char) cmd[1])) {
    636 					cmd++;
    637 					end = 0;
    638 					while (*cmd && '0' <= *cmd && *cmd <= '9')
    639 						end = end * 10 + *cmd++ - '0';
    640 				} else if (cmd[1] == '$') {
    641 					cmd += 2;
    642 					end = -1;
    643 				} else {
    644 					cmd++;
    645 					end = -2;
    646 				}
    647 			} else if (*cmd == '*')
    648 				end = -1, cmd++;
    649 			else
    650 				end = start;
    651 		}
    652 		tmp = history_arg_extract(start, end, aptr? aptr:ptr);
    653 		if (tmp == NULL) {
    654 			(void)fprintf(rl_outstream, "%s: Bad word specifier",
    655 			    command + offs + idx);
    656 			if (aptr)
    657 				free(aptr);
    658 			return(-1);
    659 		}
    660 	} else
    661 		tmp = strdup(aptr? aptr:ptr);
    662 
    663 	if (aptr)
    664 		free(aptr);
    665 
    666 	if (*cmd == 0 || (cmd - (command + offs) >= cmdlen)) {
    667 		*result = tmp;
    668 		return(1);
    669 	}
    670 
    671 	for (; *cmd; cmd++) {
    672 		if (*cmd == ':')
    673 			continue;
    674 		else if (*cmd == 'h') {		/* remove trailing path */
    675 			if ((aptr = strrchr(tmp, '/')) != NULL)
    676 				*aptr = 0;
    677 		} else if (*cmd == 't') {	/* remove leading path */
    678 			if ((aptr = strrchr(tmp, '/')) != NULL) {
    679 				aptr = strdup(aptr + 1);
    680 				free(tmp);
    681 				tmp = aptr;
    682 			}
    683 		} else if (*cmd == 'r') {	/* remove trailing suffix */
    684 			if ((aptr = strrchr(tmp, '.')) != NULL)
    685 				*aptr = 0;
    686 		} else if (*cmd == 'e') {	/* remove all but suffix */
    687 			if ((aptr = strrchr(tmp, '.')) != NULL) {
    688 				aptr = strdup(aptr);
    689 				free(tmp);
    690 				tmp = aptr;
    691 			}
    692 		} else if (*cmd == 'p')		/* print only */
    693 			p_on = 1;
    694 		else if (*cmd == 'g')
    695 			g_on = 2;
    696 		else if (*cmd == 's' || *cmd == '&') {
    697 			char *what, *with, delim;
    698 			size_t len, from_len;
    699 			size_t size;
    700 
    701 			if (*cmd == '&' && (from == NULL || to == NULL))
    702 				continue;
    703 			else if (*cmd == 's') {
    704 				delim = *(++cmd), cmd++;
    705 				size = 16;
    706 				what = realloc(from, size);
    707 				if (what == NULL) {
    708 					free(from);
    709 					return 0;
    710 				}
    711 				len = 0;
    712 				for (; *cmd && *cmd != delim; cmd++) {
    713 					if (*cmd == '\\' && cmd[1] == delim)
    714 						cmd++;
    715 					if (len >= size) {
    716 						char *nwhat;
    717 						nwhat = realloc(what,
    718 								(size <<= 1));
    719 						if (nwhat == NULL) {
    720 							free(what);
    721 							return 0;
    722 						}
    723 						what = nwhat;
    724 					}
    725 					what[len++] = *cmd;
    726 				}
    727 				what[len] = '\0';
    728 				from = what;
    729 				if (*what == '\0') {
    730 					free(what);
    731 					if (search) {
    732 						from = strdup(search);
    733 						if (from == NULL)
    734 							return 0;
    735 					} else {
    736 						from = NULL;
    737 						return (-1);
    738 					}
    739 				}
    740 				cmd++;	/* shift after delim */
    741 				if (!*cmd)
    742 					continue;
    743 
    744 				size = 16;
    745 				with = realloc(to, size);
    746 				if (with == NULL) {
    747 					free(to);
    748 					return -1;
    749 				}
    750 				len = 0;
    751 				from_len = strlen(from);
    752 				for (; *cmd && *cmd != delim; cmd++) {
    753 					if (len + from_len + 1 >= size) {
    754 						char *nwith;
    755 						size += from_len + 1;
    756 						nwith = realloc(with, size);
    757 						if (nwith == NULL) {
    758 							free(with);
    759 							return -1;
    760 						}
    761 						with = nwith;
    762 					}
    763 					if (*cmd == '&') {
    764 						/* safe */
    765 						(void)strcpy(&with[len], from);
    766 						len += from_len;
    767 						continue;
    768 					}
    769 					if (*cmd == '\\'
    770 					    && (*(cmd + 1) == delim
    771 						|| *(cmd + 1) == '&'))
    772 						cmd++;
    773 					with[len++] = *cmd;
    774 				}
    775 				with[len] = '\0';
    776 				to = with;
    777 			}
    778 
    779 			aptr = _rl_compat_sub(tmp, from, to, g_on);
    780 			if (aptr) {
    781 				free(tmp);
    782 				tmp = aptr;
    783 			}
    784 			g_on = 0;
    785 		}
    786 	}
    787 	*result = tmp;
    788 	return (p_on? 2:1);
    789 }
    790 
    791 
    792 /*
    793  * csh-style history expansion
    794  */
    795 int
    796 history_expand(char *str, char **output)
    797 {
    798 	int ret = 0;
    799 	size_t idx, i, size;
    800 	char *tmp, *result;
    801 
    802 	if (h == NULL || e == NULL)
    803 		rl_initialize();
    804 
    805 	if (history_expansion_char == 0) {
    806 		*output = strdup(str);
    807 		return(0);
    808 	}
    809 
    810 	*output = NULL;
    811 	if (str[0] == history_subst_char) {
    812 		/* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
    813 		*output = malloc(strlen(str) + 4 + 1);
    814 		if (*output == NULL)
    815 			return 0;
    816 		(*output)[0] = (*output)[1] = history_expansion_char;
    817 		(*output)[2] = ':';
    818 		(*output)[3] = 's';
    819 		(void)strcpy((*output) + 4, str);
    820 		str = *output;
    821 	} else {
    822 		*output = strdup(str);
    823 		if (*output == NULL)
    824 			return 0;
    825 	}
    826 
    827 #define ADD_STRING(what, len)						\
    828 	{								\
    829 		if (idx + len + 1 > size) {				\
    830 			char *nresult = realloc(result, (size += len + 1));\
    831 			if (nresult == NULL) {				\
    832 				free(*output);				\
    833 				return 0;				\
    834 			}						\
    835 			result = nresult;				\
    836 		}							\
    837 		(void)strncpy(&result[idx], what, len);			\
    838 		idx += len;						\
    839 		result[idx] = '\0';					\
    840 	}
    841 
    842 	result = NULL;
    843 	size = idx = 0;
    844 	for (i = 0; str[i];) {
    845 		int qchar, loop_again;
    846 		size_t len, start, j;
    847 
    848 		qchar = 0;
    849 		loop_again = 1;
    850 		start = j = i;
    851 loop:
    852 		for (; str[j]; j++) {
    853 			if (str[j] == '\\' &&
    854 			    str[j + 1] == history_expansion_char) {
    855 				(void)strcpy(&str[j], &str[j + 1]);
    856 				continue;
    857 			}
    858 			if (!loop_again) {
    859 				if (isspace((unsigned char) str[j])
    860 				    || str[j] == qchar)
    861 					break;
    862 			}
    863 			if (str[j] == history_expansion_char
    864 			    && !strchr(history_no_expand_chars, str[j + 1])
    865 			    && (!history_inhibit_expansion_function ||
    866 			    (*history_inhibit_expansion_function)(str,
    867 			    (int)j) == 0))
    868 				break;
    869 		}
    870 
    871 		if (str[j] && loop_again) {
    872 			i = j;
    873 			qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
    874 			j++;
    875 			if (str[j] == history_expansion_char)
    876 				j++;
    877 			loop_again = 0;
    878 			goto loop;
    879 		}
    880 		len = i - start;
    881 		tmp = &str[start];
    882 		ADD_STRING(tmp, len);
    883 
    884 		if (str[i] == '\0' || str[i] != history_expansion_char) {
    885 			len = j - i;
    886 			tmp = &str[i];
    887 			ADD_STRING(tmp, len);
    888 			if (start == 0)
    889 				ret = 0;
    890 			else
    891 				ret = 1;
    892 			break;
    893 		}
    894 		ret = _history_expand_command (str, i, (j - i), &tmp);
    895 		if (ret > 0 && tmp) {
    896 			len = strlen(tmp);
    897 			ADD_STRING(tmp, len);
    898 			free(tmp);
    899 		}
    900 		i = j;
    901 	}
    902 
    903 	/* ret is 2 for "print only" option */
    904 	if (ret == 2) {
    905 		add_history(result);
    906 #ifdef GDB_411_HACK
    907 		/* gdb 4.11 has been shipped with readline, where */
    908 		/* history_expand() returned -1 when the line	  */
    909 		/* should not be executed; in readline 2.1+	  */
    910 		/* it should return 2 in such a case		  */
    911 		ret = -1;
    912 #endif
    913 	}
    914 	free(*output);
    915 	*output = result;
    916 
    917 	return (ret);
    918 }
    919 
    920 /*
    921 * Return a string consisting of arguments of "str" from "start" to "end".
    922 */
    923 char *
    924 history_arg_extract(int start, int end, const char *str)
    925 {
    926 	size_t  i, len, max;
    927 	char	**arr, *result;
    928 
    929 	arr = history_tokenize(str);
    930 	if (!arr)
    931 		return(NULL);
    932 	if (arr && *arr == NULL) {
    933 		free(arr);
    934 		return(NULL);
    935 	}
    936 
    937 	for (max = 0; arr[max]; max++)
    938 		continue;
    939 	max--;
    940 
    941 	if (start == '$')
    942 		start = max;
    943 	if (end == '$')
    944 		end = max;
    945 	if (end < 0)
    946 		end = max + end + 1;
    947 	if (start < 0)
    948 		start = end;
    949 
    950 	if (start < 0 || end < 0 || start > max || end > max || start > end)
    951 		return(NULL);
    952 
    953 	for (i = start, len = 0; i <= end; i++)
    954 		len += strlen(arr[i]) + 1;
    955 	len++;
    956 	result = malloc(len);
    957 	if (result == NULL)
    958 		return NULL;
    959 
    960 	for (i = start, len = 0; i <= end; i++) {
    961 		(void)strcpy(result + len, arr[i]);
    962 		len += strlen(arr[i]);
    963 		if (i < end)
    964 			result[len++] = ' ';
    965 	}
    966 	result[len] = 0;
    967 
    968 	for (i = 0; arr[i]; i++)
    969 		free(arr[i]);
    970 	free(arr);
    971 
    972 	return(result);
    973 }
    974 
    975 /*
    976  * Parse the string into individual tokens,
    977  * similar to how shell would do it.
    978  */
    979 char **
    980 history_tokenize(const char *str)
    981 {
    982 	int size = 1, idx = 0, i, start;
    983 	size_t len;
    984 	char **result = NULL, *temp, delim = '\0';
    985 
    986 	for (i = 0; str[i];) {
    987 		while (isspace((unsigned char) str[i]))
    988 			i++;
    989 		start = i;
    990 		for (; str[i];) {
    991 			if (str[i] == '\\') {
    992 				if (str[i+1] != '\0')
    993 					i++;
    994 			} else if (str[i] == delim)
    995 				delim = '\0';
    996 			else if (!delim &&
    997 				    (isspace((unsigned char) str[i]) ||
    998 				strchr("()<>;&|$", str[i])))
    999 				break;
   1000 			else if (!delim && strchr("'`\"", str[i]))
   1001 				delim = str[i];
   1002 			if (str[i])
   1003 				i++;
   1004 		}
   1005 
   1006 		if (idx + 2 >= size) {
   1007 			char **nresult;
   1008 			size <<= 1;
   1009 			nresult = realloc(result, size * sizeof(char *));
   1010 			if (nresult == NULL) {
   1011 				free(result);
   1012 				return NULL;
   1013 			}
   1014 			result = nresult;
   1015 		}
   1016 		len = i - start;
   1017 		temp = malloc(len + 1);
   1018 		if (temp == NULL) {
   1019 			for (i = 0; i < idx; i++)
   1020 				free(result[i]);
   1021 			free(result);
   1022 			return NULL;
   1023 		}
   1024 		(void)strncpy(temp, &str[start], len);
   1025 		temp[len] = '\0';
   1026 		result[idx++] = temp;
   1027 		result[idx] = NULL;
   1028 		if (str[i])
   1029 			i++;
   1030 	}
   1031 	return (result);
   1032 }
   1033 
   1034 
   1035 /*
   1036  * limit size of history record to ``max'' events
   1037  */
   1038 void
   1039 stifle_history(int max)
   1040 {
   1041 	HistEvent ev;
   1042 
   1043 	if (h == NULL || e == NULL)
   1044 		rl_initialize();
   1045 
   1046 	if (history(h, &ev, H_SETSIZE, max) == 0)
   1047 		max_input_history = max;
   1048 }
   1049 
   1050 
   1051 /*
   1052  * "unlimit" size of history - set the limit to maximum allowed int value
   1053  */
   1054 int
   1055 unstifle_history(void)
   1056 {
   1057 	HistEvent ev;
   1058 	int omax;
   1059 
   1060 	history(h, &ev, H_SETSIZE, INT_MAX);
   1061 	omax = max_input_history;
   1062 	max_input_history = INT_MAX;
   1063 	return (omax);		/* some value _must_ be returned */
   1064 }
   1065 
   1066 
   1067 int
   1068 history_is_stifled(void)
   1069 {
   1070 
   1071 	/* cannot return true answer */
   1072 	return (max_input_history != INT_MAX);
   1073 }
   1074 
   1075 
   1076 /*
   1077  * read history from a file given
   1078  */
   1079 int
   1080 read_history(const char *filename)
   1081 {
   1082 	HistEvent ev;
   1083 
   1084 	if (h == NULL || e == NULL)
   1085 		rl_initialize();
   1086 	return (history(h, &ev, H_LOAD, filename));
   1087 }
   1088 
   1089 
   1090 /*
   1091  * write history to a file given
   1092  */
   1093 int
   1094 write_history(const char *filename)
   1095 {
   1096 	HistEvent ev;
   1097 
   1098 	if (h == NULL || e == NULL)
   1099 		rl_initialize();
   1100 	return (history(h, &ev, H_SAVE, filename));
   1101 }
   1102 
   1103 
   1104 /*
   1105  * returns history ``num''th event
   1106  *
   1107  * returned pointer points to static variable
   1108  */
   1109 HIST_ENTRY *
   1110 history_get(int num)
   1111 {
   1112 	static HIST_ENTRY she;
   1113 	HistEvent ev;
   1114 	int curr_num;
   1115 
   1116 	if (h == NULL || e == NULL)
   1117 		rl_initialize();
   1118 
   1119 	/* save current position */
   1120 	if (history(h, &ev, H_CURR) != 0)
   1121 		return (NULL);
   1122 	curr_num = ev.num;
   1123 
   1124 	/* start from most recent */
   1125 	if (history(h, &ev, H_FIRST) != 0)
   1126 		return (NULL);	/* error */
   1127 
   1128 	/* look backwards for event matching specified offset */
   1129 	if (history(h, &ev, H_NEXT_EVENT, num))
   1130 		return (NULL);
   1131 
   1132 	she.line = ev.str;
   1133 	she.data = NULL;
   1134 
   1135 	/* restore pointer to where it was */
   1136 	(void)history(h, &ev, H_SET, curr_num);
   1137 
   1138 	return (&she);
   1139 }
   1140 
   1141 
   1142 /*
   1143  * add the line to history table
   1144  */
   1145 int
   1146 add_history(const char *line)
   1147 {
   1148 	HistEvent ev;
   1149 
   1150 	if (h == NULL || e == NULL)
   1151 		rl_initialize();
   1152 
   1153 	(void)history(h, &ev, H_ENTER, line);
   1154 	if (history(h, &ev, H_GETSIZE) == 0)
   1155 		history_length = ev.num;
   1156 
   1157 	return (!(history_length > 0)); /* return 0 if all is okay */
   1158 }
   1159 
   1160 
   1161 /*
   1162  * remove the specified entry from the history list and return it.
   1163  */
   1164 HIST_ENTRY *
   1165 remove_history(int num)
   1166 {
   1167 	static HIST_ENTRY she;
   1168 	HistEvent ev;
   1169 
   1170 	if (h == NULL || e == NULL)
   1171 		rl_initialize();
   1172 
   1173 	if (history(h, &ev, H_DEL, num) != 0)
   1174 		return NULL;
   1175 
   1176 	she.line = ev.str;
   1177 	she.data = NULL;
   1178 
   1179 	return &she;
   1180 }
   1181 
   1182 
   1183 /*
   1184  * clear the history list - delete all entries
   1185  */
   1186 void
   1187 clear_history(void)
   1188 {
   1189 	HistEvent ev;
   1190 
   1191 	history(h, &ev, H_CLEAR);
   1192 }
   1193 
   1194 
   1195 /*
   1196  * returns offset of the current history event
   1197  */
   1198 int
   1199 where_history(void)
   1200 {
   1201 	HistEvent ev;
   1202 	int curr_num, off;
   1203 
   1204 	if (history(h, &ev, H_CURR) != 0)
   1205 		return (0);
   1206 	curr_num = ev.num;
   1207 
   1208 	history(h, &ev, H_FIRST);
   1209 	off = 1;
   1210 	while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
   1211 		off++;
   1212 
   1213 	return (off);
   1214 }
   1215 
   1216 
   1217 /*
   1218  * returns current history event or NULL if there is no such event
   1219  */
   1220 HIST_ENTRY *
   1221 current_history(void)
   1222 {
   1223 
   1224 	return (_move_history(H_CURR));
   1225 }
   1226 
   1227 
   1228 /*
   1229  * returns total number of bytes history events' data are using
   1230  */
   1231 int
   1232 history_total_bytes(void)
   1233 {
   1234 	HistEvent ev;
   1235 	int curr_num, size;
   1236 
   1237 	if (history(h, &ev, H_CURR) != 0)
   1238 		return (-1);
   1239 	curr_num = ev.num;
   1240 
   1241 	history(h, &ev, H_FIRST);
   1242 	size = 0;
   1243 	do
   1244 		size += strlen(ev.str);
   1245 	while (history(h, &ev, H_NEXT) == 0);
   1246 
   1247 	/* get to the same position as before */
   1248 	history(h, &ev, H_PREV_EVENT, curr_num);
   1249 
   1250 	return (size);
   1251 }
   1252 
   1253 
   1254 /*
   1255  * sets the position in the history list to ``pos''
   1256  */
   1257 int
   1258 history_set_pos(int pos)
   1259 {
   1260 	HistEvent ev;
   1261 	int curr_num;
   1262 
   1263 	if (pos > history_length || pos < 0)
   1264 		return (-1);
   1265 
   1266 	history(h, &ev, H_CURR);
   1267 	curr_num = ev.num;
   1268 
   1269 	if (history(h, &ev, H_SET, pos)) {
   1270 		history(h, &ev, H_SET, curr_num);
   1271 		return(-1);
   1272 	}
   1273 	return (0);
   1274 }
   1275 
   1276 
   1277 /*
   1278  * returns previous event in history and shifts pointer accordingly
   1279  */
   1280 HIST_ENTRY *
   1281 previous_history(void)
   1282 {
   1283 
   1284 	return (_move_history(H_PREV));
   1285 }
   1286 
   1287 
   1288 /*
   1289  * returns next event in history and shifts pointer accordingly
   1290  */
   1291 HIST_ENTRY *
   1292 next_history(void)
   1293 {
   1294 
   1295 	return (_move_history(H_NEXT));
   1296 }
   1297 
   1298 
   1299 /*
   1300  * searches for first history event containing the str
   1301  */
   1302 int
   1303 history_search(const char *str, int direction)
   1304 {
   1305 	HistEvent ev;
   1306 	const char *strp;
   1307 	int curr_num;
   1308 
   1309 	if (history(h, &ev, H_CURR) != 0)
   1310 		return (-1);
   1311 	curr_num = ev.num;
   1312 
   1313 	for (;;) {
   1314 		if ((strp = strstr(ev.str, str)) != NULL)
   1315 			return (int) (strp - ev.str);
   1316 		if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
   1317 			break;
   1318 	}
   1319 	history(h, &ev, H_SET, curr_num);
   1320 	return (-1);
   1321 }
   1322 
   1323 
   1324 /*
   1325  * searches for first history event beginning with str
   1326  */
   1327 int
   1328 history_search_prefix(const char *str, int direction)
   1329 {
   1330 	HistEvent ev;
   1331 
   1332 	return (history(h, &ev, direction < 0? H_PREV_STR:H_NEXT_STR, str));
   1333 }
   1334 
   1335 
   1336 /*
   1337  * search for event in history containing str, starting at offset
   1338  * abs(pos); continue backward, if pos<0, forward otherwise
   1339  */
   1340 /* ARGSUSED */
   1341 int
   1342 history_search_pos(const char *str,
   1343 		   int direction __attribute__((__unused__)), int pos)
   1344 {
   1345 	HistEvent ev;
   1346 	int curr_num, off;
   1347 
   1348 	off = (pos > 0) ? pos : -pos;
   1349 	pos = (pos > 0) ? 1 : -1;
   1350 
   1351 	if (history(h, &ev, H_CURR) != 0)
   1352 		return (-1);
   1353 	curr_num = ev.num;
   1354 
   1355 	if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
   1356 		return (-1);
   1357 
   1358 
   1359 	for (;;) {
   1360 		if (strstr(ev.str, str))
   1361 			return (off);
   1362 		if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
   1363 			break;
   1364 	}
   1365 
   1366 	/* set "current" pointer back to previous state */
   1367 	history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
   1368 
   1369 	return (-1);
   1370 }
   1371 
   1372 
   1373 /********************************/
   1374 /* completion functions */
   1375 
   1376 char *
   1377 tilde_expand(char *name)
   1378 {
   1379 	return fn_tilde_expand(name);
   1380 }
   1381 
   1382 char *
   1383 filename_completion_function(const char *name, int state)
   1384 {
   1385 	return fn_filename_completion_function(name, state);
   1386 }
   1387 
   1388 /*
   1389  * a completion generator for usernames; returns _first_ username
   1390  * which starts with supplied text
   1391  * text contains a partial username preceded by random character
   1392  * (usually '~'); state is ignored
   1393  * it's callers responsibility to free returned value
   1394  */
   1395 char *
   1396 username_completion_function(const char *text, int state)
   1397 {
   1398 	struct passwd *pwd, pwres;
   1399 	char pwbuf[1024];
   1400 
   1401 	if (text[0] == '\0')
   1402 		return (NULL);
   1403 
   1404 	if (*text == '~')
   1405 		text++;
   1406 
   1407 	if (state == 0)
   1408 		setpwent();
   1409 
   1410 	while (getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pwd) == 0
   1411 	    && pwd != NULL && text[0] == pwd->pw_name[0]
   1412 	    && strcmp(text, pwd->pw_name) == 0);
   1413 
   1414 	if (pwd == NULL) {
   1415 		endpwent();
   1416 		return (NULL);
   1417 	}
   1418 	return (strdup(pwd->pw_name));
   1419 }
   1420 
   1421 
   1422 /*
   1423  * el-compatible wrapper to send TSTP on ^Z
   1424  */
   1425 /* ARGSUSED */
   1426 static unsigned char
   1427 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
   1428 {
   1429 	(void)kill(0, SIGTSTP);
   1430 	return CC_NORM;
   1431 }
   1432 
   1433 /*
   1434  * Display list of strings in columnar format on readline's output stream.
   1435  * 'matches' is list of strings, 'len' is number of strings in 'matches',
   1436  * 'max' is maximum length of string in 'matches'.
   1437  */
   1438 void
   1439 rl_display_match_list(char **matches, int len, int max)
   1440 {
   1441 
   1442 	fn_display_match_list(e, matches, len, max);
   1443 }
   1444 
   1445 static const char *
   1446 /*ARGSUSED*/
   1447 _rl_completion_append_character_function(const char *dummy
   1448     __attribute__((__unused__)))
   1449 {
   1450 	static char buf[2];
   1451 	buf[1] = rl_completion_append_character;
   1452 	return buf;
   1453 }
   1454 
   1455 
   1456 /*
   1457  * complete word at current point
   1458  */
   1459 /* ARGSUSED */
   1460 int
   1461 rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
   1462 {
   1463 	if (h == NULL || e == NULL)
   1464 		rl_initialize();
   1465 
   1466 	if (rl_inhibit_completion) {
   1467 		char arr[2];
   1468 		arr[0] = (char)invoking_key;
   1469 		arr[1] = '\0';
   1470 		el_insertstr(e, arr);
   1471 		return (CC_REFRESH);
   1472 	}
   1473 
   1474 	/* Just look at how many global variables modify this operation! */
   1475 	return fn_complete(e,
   1476 	    (CPFunction *)rl_completion_entry_function,
   1477 	    rl_attempted_completion_function,
   1478 	    rl_basic_word_break_characters, rl_special_prefixes,
   1479 	    _rl_completion_append_character_function, rl_completion_query_items,
   1480 	    &rl_completion_type, &rl_attempted_completion_over,
   1481 	    &rl_point, &rl_end);
   1482 }
   1483 
   1484 
   1485 /* ARGSUSED */
   1486 static unsigned char
   1487 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
   1488 {
   1489 	return (unsigned char)rl_complete(0, ch);
   1490 }
   1491 
   1492 /*
   1493  * misc other functions
   1494  */
   1495 
   1496 /*
   1497  * bind key c to readline-type function func
   1498  */
   1499 int
   1500 rl_bind_key(int c, int func(int, int))
   1501 {
   1502 	int retval = -1;
   1503 
   1504 	if (h == NULL || e == NULL)
   1505 		rl_initialize();
   1506 
   1507 	if (func == rl_insert) {
   1508 		/* XXX notice there is no range checking of ``c'' */
   1509 		e->el_map.key[c] = ED_INSERT;
   1510 		retval = 0;
   1511 	}
   1512 	return (retval);
   1513 }
   1514 
   1515 
   1516 /*
   1517  * read one key from input - handles chars pushed back
   1518  * to input stream also
   1519  */
   1520 int
   1521 rl_read_key(void)
   1522 {
   1523 	char fooarr[2 * sizeof(int)];
   1524 
   1525 	if (e == NULL || h == NULL)
   1526 		rl_initialize();
   1527 
   1528 	return (el_getc(e, fooarr));
   1529 }
   1530 
   1531 
   1532 /*
   1533  * reset the terminal
   1534  */
   1535 /* ARGSUSED */
   1536 void
   1537 rl_reset_terminal(const char *p __attribute__((__unused__)))
   1538 {
   1539 
   1540 	if (h == NULL || e == NULL)
   1541 		rl_initialize();
   1542 	el_reset(e);
   1543 }
   1544 
   1545 
   1546 /*
   1547  * insert character ``c'' back into input stream, ``count'' times
   1548  */
   1549 int
   1550 rl_insert(int count, int c)
   1551 {
   1552 	char arr[2];
   1553 
   1554 	if (h == NULL || e == NULL)
   1555 		rl_initialize();
   1556 
   1557 	/* XXX - int -> char conversion can lose on multichars */
   1558 	arr[0] = c;
   1559 	arr[1] = '\0';
   1560 
   1561 	for (; count > 0; count--)
   1562 		el_push(e, arr);
   1563 
   1564 	return (0);
   1565 }
   1566 
   1567 /*ARGSUSED*/
   1568 int
   1569 rl_newline(int count, int c)
   1570 {
   1571 	/*
   1572 	 * Readline-4.0 appears to ignore the args.
   1573 	 */
   1574 	return rl_insert(1, '\n');
   1575 }
   1576 
   1577 /*ARGSUSED*/
   1578 static unsigned char
   1579 rl_bind_wrapper(EditLine *el, unsigned char c)
   1580 {
   1581 	if (map[c] == NULL)
   1582 	    return CC_ERROR;
   1583 
   1584 	_rl_update_pos();
   1585 
   1586 	(*map[c])(NULL, c);
   1587 
   1588 	/* If rl_done was set by the above call, deal with it here */
   1589 	if (rl_done)
   1590 		return CC_EOF;
   1591 
   1592 	return CC_NORM;
   1593 }
   1594 
   1595 int
   1596 rl_add_defun(const char *name, Function *fun, int c)
   1597 {
   1598 	char dest[8];
   1599 	if (c >= sizeof(map) / sizeof(map[0]) || c < 0)
   1600 		return -1;
   1601 	map[(unsigned char)c] = fun;
   1602 	el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
   1603 	vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
   1604 	el_set(e, EL_BIND, dest, name);
   1605 	return 0;
   1606 }
   1607 
   1608 void
   1609 rl_callback_read_char()
   1610 {
   1611 	int count = 0, done = 0;
   1612 	const char *buf = el_gets(e, &count);
   1613 	char *wbuf;
   1614 
   1615 	if (buf == NULL || count-- <= 0)
   1616 		return;
   1617 	if (count == 0 && buf[0] == CTRL('d'))
   1618 		done = 1;
   1619 	if (buf[count] == '\n' || buf[count] == '\r')
   1620 		done = 2;
   1621 
   1622 	if (done && rl_linefunc != NULL) {
   1623 		el_set(e, EL_UNBUFFERED, 0);
   1624 		if (done == 2) {
   1625 		    if ((wbuf = strdup(buf)) != NULL)
   1626 			wbuf[count] = '\0';
   1627 		} else
   1628 			wbuf = NULL;
   1629 		(*(void (*)(const char *))rl_linefunc)(wbuf);
   1630 		el_set(e, EL_UNBUFFERED, 1);
   1631 	}
   1632 }
   1633 
   1634 void
   1635 rl_callback_handler_install (const char *prompt, VCPFunction *linefunc)
   1636 {
   1637 	if (e == NULL) {
   1638 		rl_initialize();
   1639 	}
   1640 	if (rl_prompt)
   1641 		free(rl_prompt);
   1642 	rl_prompt = prompt ? strdup(strchr(prompt, *prompt)) : NULL;
   1643 	rl_linefunc = linefunc;
   1644 	el_set(e, EL_UNBUFFERED, 1);
   1645 }
   1646 
   1647 void
   1648 rl_callback_handler_remove(void)
   1649 {
   1650 	el_set(e, EL_UNBUFFERED, 0);
   1651 }
   1652 
   1653 void
   1654 rl_redisplay(void)
   1655 {
   1656 	char a[2];
   1657 	a[0] = CTRL('r');
   1658 	a[1] = '\0';
   1659 	el_push(e, a);
   1660 }
   1661 
   1662 int
   1663 rl_get_previous_history(int count, int key)
   1664 {
   1665 	char a[2];
   1666 	a[0] = key;
   1667 	a[1] = '\0';
   1668 	while (count--)
   1669 		el_push(e, a);
   1670 	return 0;
   1671 }
   1672 
   1673 void
   1674 /*ARGSUSED*/
   1675 rl_prep_terminal(int meta_flag)
   1676 {
   1677 	el_set(e, EL_PREP_TERM, 1);
   1678 }
   1679 
   1680 void
   1681 rl_deprep_terminal()
   1682 {
   1683 	el_set(e, EL_PREP_TERM, 0);
   1684 }
   1685 
   1686 int
   1687 rl_read_init_file(const char *s)
   1688 {
   1689 	return(el_source(e, s));
   1690 }
   1691 
   1692 int
   1693 rl_parse_and_bind(const char *line)
   1694 {
   1695 	const char **argv;
   1696 	int argc;
   1697 	Tokenizer *tok;
   1698 
   1699 	tok = tok_init(NULL);
   1700 	tok_str(tok, line, &argc, &argv);
   1701 	argc = el_parse(e, argc, argv);
   1702 	tok_end(tok);
   1703 	return (argc ? 1 : 0);
   1704 }
   1705 
   1706 int
   1707 rl_variable_bind(const char *var, const char *value)
   1708 {
   1709 	/*
   1710 	 * The proper return value is undocument, but this is what the
   1711 	 * readline source seems to do.
   1712 	 */
   1713 	return ((el_set(e, EL_BIND, "", var, value) == -1) ? 1 : 0);
   1714 }
   1715 
   1716 void
   1717 rl_stuff_char(int c)
   1718 {
   1719 	char buf[2];
   1720 
   1721 	buf[0] = c;
   1722 	buf[1] = '\0';
   1723 	el_insertstr(e, buf);
   1724 }
   1725 
   1726 static int
   1727 _rl_event_read_char(EditLine *el, char *cp)
   1728 {
   1729 	int	n, num_read = 0;
   1730 
   1731 	*cp = 0;
   1732 	while (rl_event_hook) {
   1733 
   1734 		(*rl_event_hook)();
   1735 
   1736 #if defined(FIONREAD)
   1737 		if (ioctl(el->el_infd, FIONREAD, &n) < 0)
   1738 			return(-1);
   1739 		if (n)
   1740 			num_read = read(el->el_infd, cp, 1);
   1741 		else
   1742 			num_read = 0;
   1743 #elif defined(F_SETFL) && defined(O_NDELAY)
   1744 		if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
   1745 			return(-1);
   1746 		if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
   1747 			return(-1);
   1748 		num_read = read(el->el_infd, cp, 1);
   1749 		if (fcntl(el->el_infd, F_SETFL, n))
   1750 			return(-1);
   1751 #else
   1752 		/* not non-blocking, but what you gonna do? */
   1753 		num_read = read(el->el_infd, cp, 1);
   1754 		return(-1);
   1755 #endif
   1756 
   1757 		if (num_read < 0 && errno == EAGAIN)
   1758 			continue;
   1759 		if (num_read == 0)
   1760 			continue;
   1761 		break;
   1762 	}
   1763 	if (!rl_event_hook)
   1764 		el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
   1765 	return(num_read);
   1766 }
   1767 
   1768 static void
   1769 _rl_update_pos(void)
   1770 {
   1771 	const LineInfo *li = el_line(e);
   1772 
   1773 	rl_point = li->cursor - li->buffer;
   1774 	rl_end = li->lastchar - li->buffer;
   1775 }
   1776