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