Home | History | Annotate | Line # | Download | only in libedit
readline.c revision 1.43
      1 /*	$NetBSD: readline.c,v 1.43 2003/11/03 03:22:55 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.43 2003/11/03 03:22:55 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 "histedit.h"
     65 #include "readline/readline.h"
     66 #include "el.h"
     67 #include "tokenizer.h"
     68 #include "fcns.h"		/* for EL_NUM_FCNS */
     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 VFunction *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 = (char *)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 /* if not zero, non-unique completions always show list of possible matches */
    156 static int _rl_complete_show_all = 0;
    157 
    158 static History *h = NULL;
    159 static EditLine *e = NULL;
    160 static Function *map[256];
    161 static int el_rl_complete_cmdnum = 0;
    162 
    163 /* internal functions */
    164 static unsigned char	 _el_rl_complete(EditLine *, int);
    165 static char		*_get_prompt(EditLine *);
    166 static HIST_ENTRY	*_move_history(int);
    167 static int		 _history_expand_command(const char *, size_t, size_t,
    168     char **);
    169 static char		*_rl_compat_sub(const char *, const char *,
    170     const char *, int);
    171 static int		 rl_complete_internal(int);
    172 static int		 _rl_qsort_string_compare(const void *, const void *);
    173 static int		 _rl_event_read_char(EditLine *, char *);
    174 
    175 
    176 /* ARGSUSED */
    177 static char *
    178 _get_prompt(EditLine *el __attribute__((__unused__)))
    179 {
    180 	rl_already_prompted = 1;
    181 	return (rl_prompt);
    182 }
    183 
    184 
    185 /*
    186  * generic function for moving around history
    187  */
    188 static HIST_ENTRY *
    189 _move_history(int op)
    190 {
    191 	HistEvent ev;
    192 	static HIST_ENTRY rl_he;
    193 
    194 	if (history(h, &ev, op) != 0)
    195 		return (HIST_ENTRY *) NULL;
    196 
    197 	rl_he.line = ev.str;
    198 	rl_he.data = NULL;
    199 
    200 	return (&rl_he);
    201 }
    202 
    203 
    204 /*
    205  * READLINE compatibility stuff
    206  */
    207 
    208 /*
    209  * initialize rl compat stuff
    210  */
    211 int
    212 rl_initialize(void)
    213 {
    214 	HistEvent ev;
    215 	const LineInfo *li;
    216 	int i;
    217 	int editmode = 1;
    218 	struct termios t;
    219 
    220 	if (e != NULL)
    221 		el_end(e);
    222 	if (h != NULL)
    223 		history_end(h);
    224 
    225 	if (!rl_instream)
    226 		rl_instream = stdin;
    227 	if (!rl_outstream)
    228 		rl_outstream = stdout;
    229 
    230 	/*
    231 	 * See if we don't really want to run the editor
    232 	 */
    233 	if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
    234 		editmode = 0;
    235 
    236 	e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
    237 
    238 	if (!editmode)
    239 		el_set(e, EL_EDITMODE, 0);
    240 
    241 	h = history_init();
    242 	if (!e || !h)
    243 		return (-1);
    244 
    245 	history(h, &ev, H_SETSIZE, INT_MAX);	/* unlimited */
    246 	history_length = 0;
    247 	max_input_history = INT_MAX;
    248 	el_set(e, EL_HIST, history, h);
    249 
    250 	/* for proper prompt printing in readline() */
    251 	rl_prompt = strdup("");
    252 	if (rl_prompt == NULL) {
    253 		history_end(h);
    254 		el_end(e);
    255 		return -1;
    256 	}
    257 	el_set(e, EL_PROMPT, _get_prompt);
    258 	el_set(e, EL_SIGNAL, rl_catch_signals);
    259 
    260 	/* set default mode to "emacs"-style and read setting afterwards */
    261 	/* so this can be overriden */
    262 	el_set(e, EL_EDITOR, "emacs");
    263 	if (rl_terminal_name != NULL)
    264 		el_set(e, EL_TERMINAL, rl_terminal_name);
    265 	else
    266 		el_get(e, EL_TERMINAL, &rl_terminal_name);
    267 
    268 	/*
    269 	 * Word completion - this has to go AFTER rebinding keys
    270 	 * to emacs-style.
    271 	 */
    272 	el_set(e, EL_ADDFN, "rl_complete",
    273 	    "ReadLine compatible completion function",
    274 	    _el_rl_complete);
    275 	el_set(e, EL_BIND, "^I", "rl_complete", NULL);
    276 	/*
    277 	 * Find out where the rl_complete function was added; this is
    278 	 * used later to detect that lastcmd was also rl_complete.
    279 	 */
    280 	for(i=EL_NUM_FCNS; i < e->el_map.nfunc; i++) {
    281 		if (e->el_map.func[i] == _el_rl_complete) {
    282 			el_rl_complete_cmdnum = i;
    283 			break;
    284 		}
    285 	}
    286 
    287 	/* read settings from configuration file */
    288 	el_source(e, NULL);
    289 
    290 	/*
    291 	 * Unfortunately, some applications really do use rl_point
    292 	 * and rl_line_buffer directly.
    293 	 */
    294 	li = el_line(e);
    295 	/* a cheesy way to get rid of const cast. */
    296 	rl_line_buffer = memchr(li->buffer, *li->buffer, 1);
    297 	rl_point = rl_end = 0;
    298 
    299 	if (rl_startup_hook)
    300 		(*rl_startup_hook)(NULL, 0);
    301 
    302 	return (0);
    303 }
    304 
    305 
    306 /*
    307  * read one line from input stream and return it, chomping
    308  * trailing newline (if there is any)
    309  */
    310 char *
    311 readline(const char *prompt)
    312 {
    313 	HistEvent ev;
    314 	int count;
    315 	const char *ret;
    316 	char *buf;
    317 	static int used_event_hook;
    318 
    319 	if (e == NULL || h == NULL)
    320 		rl_initialize();
    321 
    322 	rl_done = 0;
    323 
    324 	/* update prompt accordingly to what has been passed */
    325 	if (!prompt)
    326 		prompt = "";
    327 	if (strcmp(rl_prompt, prompt) != 0) {
    328 		free(rl_prompt);
    329 		rl_prompt = strdup(prompt);
    330 		if (rl_prompt == NULL)
    331 			return NULL;
    332 	}
    333 
    334 	if (rl_pre_input_hook)
    335 		(*rl_pre_input_hook)(NULL, 0);
    336 
    337 	if (rl_event_hook && !(e->el_flags&NO_TTY)) {
    338 		el_set(e, EL_GETCFN, _rl_event_read_char);
    339 		used_event_hook = 1;
    340 	}
    341 
    342 	if (!rl_event_hook && used_event_hook) {
    343 		el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
    344 		used_event_hook = 0;
    345 	}
    346 
    347 	rl_already_prompted = 0;
    348 
    349 	/* get one line from input stream */
    350 	ret = el_gets(e, &count);
    351 
    352 	if (ret && count > 0) {
    353 		int lastidx;
    354 
    355 		buf = strdup(ret);
    356 		if (buf == NULL)
    357 			return NULL;
    358 		lastidx = count - 1;
    359 		if (buf[lastidx] == '\n')
    360 			buf[lastidx] = '\0';
    361 	} else
    362 		buf = NULL;
    363 
    364 	history(h, &ev, H_GETSIZE);
    365 	history_length = ev.num;
    366 
    367 	return buf;
    368 }
    369 
    370 /*
    371  * history functions
    372  */
    373 
    374 /*
    375  * is normally called before application starts to use
    376  * history expansion functions
    377  */
    378 void
    379 using_history(void)
    380 {
    381 	if (h == NULL || e == NULL)
    382 		rl_initialize();
    383 }
    384 
    385 
    386 /*
    387  * substitute ``what'' with ``with'', returning resulting string; if
    388  * globally == 1, substitutes all occurrences of what, otherwise only the
    389  * first one
    390  */
    391 static char *
    392 _rl_compat_sub(const char *str, const char *what, const char *with,
    393     int globally)
    394 {
    395 	const	char	*s;
    396 	char	*r, *result;
    397 	size_t	len, with_len, what_len;
    398 
    399 	len = strlen(str);
    400 	with_len = strlen(with);
    401 	what_len = strlen(what);
    402 
    403 	/* calculate length we need for result */
    404 	s = str;
    405 	while (*s) {
    406 		if (*s == *what && !strncmp(s, what, what_len)) {
    407 			len += with_len - what_len;
    408 			if (!globally)
    409 				break;
    410 			s += what_len;
    411 		} else
    412 			s++;
    413 	}
    414 	r = result = malloc(len + 1);
    415 	if (result == NULL)
    416 		return NULL;
    417 	s = str;
    418 	while (*s) {
    419 		if (*s == *what && !strncmp(s, what, what_len)) {
    420 			(void)strncpy(r, with, with_len);
    421 			r += with_len;
    422 			s += what_len;
    423 			if (!globally) {
    424 				(void)strcpy(r, s);
    425 				return(result);
    426 			}
    427 		} else
    428 			*r++ = *s++;
    429 	}
    430 	*r = 0;
    431 	return(result);
    432 }
    433 
    434 static	char	*last_search_pat;	/* last !?pat[?] search pattern */
    435 static	char	*last_search_match;	/* last !?pat[?] that matched */
    436 
    437 const char *
    438 get_history_event(const char *cmd, int *cindex, int qchar)
    439 {
    440 	int idx, sign, sub, num, begin, ret;
    441 	size_t len;
    442 	char	*pat;
    443 	const char *rptr;
    444 	HistEvent ev;
    445 
    446 	idx = *cindex;
    447 	if (cmd[idx++] != history_expansion_char)
    448 		return(NULL);
    449 
    450 	/* find out which event to take */
    451 	if (cmd[idx] == history_expansion_char || cmd[idx] == 0) {
    452 		if (history(h, &ev, H_FIRST) != 0)
    453 			return(NULL);
    454 		*cindex = cmd[idx]? (idx + 1):idx;
    455 		return(ev.str);
    456 	}
    457 	sign = 0;
    458 	if (cmd[idx] == '-') {
    459 		sign = 1;
    460 		idx++;
    461 	}
    462 
    463 	if ('0' <= cmd[idx] && cmd[idx] <= '9') {
    464 		HIST_ENTRY *rl_he;
    465 
    466 		num = 0;
    467 		while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
    468 			num = num * 10 + cmd[idx] - '0';
    469 			idx++;
    470 		}
    471 		if (sign)
    472 			num = history_length - num + 1;
    473 
    474 		if (!(rl_he = history_get(num)))
    475 			return(NULL);
    476 
    477 		*cindex = idx;
    478 		return(rl_he->line);
    479 	}
    480 	sub = 0;
    481 	if (cmd[idx] == '?') {
    482 		sub = 1;
    483 		idx++;
    484 	}
    485 	begin = idx;
    486 	while (cmd[idx]) {
    487 		if (cmd[idx] == '\n')
    488 			break;
    489 		if (sub && cmd[idx] == '?')
    490 			break;
    491 		if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
    492 				    || cmd[idx] == '\t' || cmd[idx] == qchar))
    493 			break;
    494 		idx++;
    495 	}
    496 	len = idx - begin;
    497 	if (sub && cmd[idx] == '?')
    498 		idx++;
    499 	if (sub && len == 0 && last_search_pat && *last_search_pat)
    500 		pat = last_search_pat;
    501 	else if (len == 0)
    502 		return(NULL);
    503 	else {
    504 		if ((pat = malloc(len + 1)) == NULL)
    505 			return NULL;
    506 		(void)strncpy(pat, cmd + begin, len);
    507 		pat[len] = '\0';
    508 	}
    509 
    510 	if (history(h, &ev, H_CURR) != 0) {
    511 		if (pat != last_search_pat)
    512 			free(pat);
    513 		return (NULL);
    514 	}
    515 	num = ev.num;
    516 
    517 	if (sub) {
    518 		if (pat != last_search_pat) {
    519 			if (last_search_pat)
    520 				free(last_search_pat);
    521 			last_search_pat = pat;
    522 		}
    523 		ret = history_search(pat, -1);
    524 	} else
    525 		ret = history_search_prefix(pat, -1);
    526 
    527 	if (ret == -1) {
    528 		/* restore to end of list on failed search */
    529 		history(h, &ev, H_FIRST);
    530 		(void)fprintf(rl_outstream, "%s: Event not found\n", pat);
    531 		if (pat != last_search_pat)
    532 			free(pat);
    533 		return(NULL);
    534 	}
    535 
    536 	if (sub && len) {
    537 		if (last_search_match && last_search_match != pat)
    538 			free(last_search_match);
    539 		last_search_match = pat;
    540 	}
    541 
    542 	if (pat != last_search_pat)
    543 		free(pat);
    544 
    545 	if (history(h, &ev, H_CURR) != 0)
    546 		return(NULL);
    547 	*cindex = idx;
    548 	rptr = ev.str;
    549 
    550 	/* roll back to original position */
    551 	(void)history(h, &ev, H_SET, num);
    552 
    553 	return rptr;
    554 }
    555 
    556 /*
    557  * the real function doing history expansion - takes as argument command
    558  * to do and data upon which the command should be executed
    559  * does expansion the way I've understood readline documentation
    560  *
    561  * returns 0 if data was not modified, 1 if it was and 2 if the string
    562  * should be only printed and not executed; in case of error,
    563  * returns -1 and *result points to NULL
    564  * it's callers responsibility to free() string returned in *result
    565  */
    566 static int
    567 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
    568     char **result)
    569 {
    570 	char *tmp, *search = NULL, *aptr;
    571 	const char *ptr, *cmd;
    572 	static char *from = NULL, *to = NULL;
    573 	int start, end, idx, has_mods = 0;
    574 	int p_on = 0, g_on = 0;
    575 
    576 	*result = NULL;
    577 	aptr = NULL;
    578 	ptr = NULL;
    579 
    580 	/* First get event specifier */
    581 	idx = 0;
    582 
    583 	if (strchr(":^*$", command[offs + 1])) {
    584 		char str[4];
    585 		/*
    586 		* "!:" is shorthand for "!!:".
    587 		* "!^", "!*" and "!$" are shorthand for
    588 		* "!!:^", "!!:*" and "!!:$" respectively.
    589 		*/
    590 		str[0] = str[1] = '!';
    591 		str[2] = '0';
    592 		ptr = get_history_event(str, &idx, 0);
    593 		idx = (command[offs + 1] == ':')? 1:0;
    594 		has_mods = 1;
    595 	} else {
    596 		if (command[offs + 1] == '#') {
    597 			/* use command so far */
    598 			if ((aptr = malloc(offs + 1)) == NULL)
    599 				return -1;
    600 			(void)strncpy(aptr, command, offs);
    601 			aptr[offs] = '\0';
    602 			idx = 1;
    603 		} else {
    604 			int	qchar;
    605 
    606 			qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
    607 			ptr = get_history_event(command + offs, &idx, qchar);
    608 		}
    609 		has_mods = command[offs + idx] == ':';
    610 	}
    611 
    612 	if (ptr == NULL && aptr == NULL)
    613 		return(-1);
    614 
    615 	if (!has_mods) {
    616 		*result = strdup(aptr? aptr : ptr);
    617 		if (aptr)
    618 			free(aptr);
    619 		return(1);
    620 	}
    621 
    622 	cmd = command + offs + idx + 1;
    623 
    624 	/* Now parse any word designators */
    625 
    626 	if (*cmd == '%')	/* last word matched by ?pat? */
    627 		tmp = strdup(last_search_match? last_search_match:"");
    628 	else if (strchr("^*$-0123456789", *cmd)) {
    629 		start = end = -1;
    630 		if (*cmd == '^')
    631 			start = end = 1, cmd++;
    632 		else if (*cmd == '$')
    633 			start = -1, cmd++;
    634 		else if (*cmd == '*')
    635 			start = 1, cmd++;
    636 	       else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
    637 			start = 0;
    638 			while (*cmd && '0' <= *cmd && *cmd <= '9')
    639 				start = start * 10 + *cmd++ - '0';
    640 
    641 			if (*cmd == '-') {
    642 				if (isdigit((unsigned char) cmd[1])) {
    643 					cmd++;
    644 					end = 0;
    645 					while (*cmd && '0' <= *cmd && *cmd <= '9')
    646 						end = end * 10 + *cmd++ - '0';
    647 				} else if (cmd[1] == '$') {
    648 					cmd += 2;
    649 					end = -1;
    650 				} else {
    651 					cmd++;
    652 					end = -2;
    653 				}
    654 			} else if (*cmd == '*')
    655 				end = -1, cmd++;
    656 			else
    657 				end = start;
    658 		}
    659 		tmp = history_arg_extract(start, end, aptr? aptr:ptr);
    660 		if (tmp == NULL) {
    661 			(void)fprintf(rl_outstream, "%s: Bad word specifier",
    662 			    command + offs + idx);
    663 			if (aptr)
    664 				free(aptr);
    665 			return(-1);
    666 		}
    667 	} else
    668 		tmp = strdup(aptr? aptr:ptr);
    669 
    670 	if (aptr)
    671 		free(aptr);
    672 
    673 	if (*cmd == 0 || (cmd - (command + offs) >= cmdlen)) {
    674 		*result = tmp;
    675 		return(1);
    676 	}
    677 
    678 	for (; *cmd; cmd++) {
    679 		if (*cmd == ':')
    680 			continue;
    681 		else if (*cmd == 'h') {		/* remove trailing path */
    682 			if ((aptr = strrchr(tmp, '/')) != NULL)
    683 				*aptr = 0;
    684 		} else if (*cmd == 't') {	/* remove leading path */
    685 			if ((aptr = strrchr(tmp, '/')) != NULL) {
    686 				aptr = strdup(aptr + 1);
    687 				free(tmp);
    688 				tmp = aptr;
    689 			}
    690 		} else if (*cmd == 'r') {	/* remove trailing suffix */
    691 			if ((aptr = strrchr(tmp, '.')) != NULL)
    692 				*aptr = 0;
    693 		} else if (*cmd == 'e') {	/* remove all but suffix */
    694 			if ((aptr = strrchr(tmp, '.')) != NULL) {
    695 				aptr = strdup(aptr);
    696 				free(tmp);
    697 				tmp = aptr;
    698 			}
    699 		} else if (*cmd == 'p')		/* print only */
    700 			p_on = 1;
    701 		else if (*cmd == 'g')
    702 			g_on = 2;
    703 		else if (*cmd == 's' || *cmd == '&') {
    704 			char *what, *with, delim;
    705 			size_t len, from_len;
    706 			size_t size;
    707 
    708 			if (*cmd == '&' && (from == NULL || to == NULL))
    709 				continue;
    710 			else if (*cmd == 's') {
    711 				delim = *(++cmd), cmd++;
    712 				size = 16;
    713 				what = realloc(from, size);
    714 				if (what == NULL) {
    715 					free(from);
    716 					return 0;
    717 				}
    718 				len = 0;
    719 				for (; *cmd && *cmd != delim; cmd++) {
    720 					if (*cmd == '\\' && cmd[1] == delim)
    721 						cmd++;
    722 					if (len >= size) {
    723 						char *nwhat;
    724 						nwhat = realloc(what,
    725 								(size <<= 1));
    726 						if (nwhat == NULL) {
    727 							free(what);
    728 							return 0;
    729 						}
    730 						what = nwhat;
    731 					}
    732 					what[len++] = *cmd;
    733 				}
    734 				what[len] = '\0';
    735 				from = what;
    736 				if (*what == '\0') {
    737 					free(what);
    738 					if (search) {
    739 						from = strdup(search);
    740 						if (from == NULL)
    741 							return 0;
    742 					} else {
    743 						from = NULL;
    744 						return (-1);
    745 					}
    746 				}
    747 				cmd++;	/* shift after delim */
    748 				if (!*cmd)
    749 					continue;
    750 
    751 				size = 16;
    752 				with = realloc(to, size);
    753 				if (with == NULL) {
    754 					free(to);
    755 					return -1;
    756 				}
    757 				len = 0;
    758 				from_len = strlen(from);
    759 				for (; *cmd && *cmd != delim; cmd++) {
    760 					if (len + from_len + 1 >= size) {
    761 						char *nwith;
    762 						size += from_len + 1;
    763 						nwith = realloc(with, size);
    764 						if (nwith == NULL) {
    765 							free(with);
    766 							return -1;
    767 						}
    768 						with = nwith;
    769 					}
    770 					if (*cmd == '&') {
    771 						/* safe */
    772 						(void)strcpy(&with[len], from);
    773 						len += from_len;
    774 						continue;
    775 					}
    776 					if (*cmd == '\\'
    777 					    && (*(cmd + 1) == delim
    778 						|| *(cmd + 1) == '&'))
    779 						cmd++;
    780 					with[len++] = *cmd;
    781 				}
    782 				with[len] = '\0';
    783 				to = with;
    784 			}
    785 
    786 			aptr = _rl_compat_sub(tmp, from, to, g_on);
    787 			if (aptr) {
    788 				free(tmp);
    789 				tmp = aptr;
    790 			}
    791 			g_on = 0;
    792 		}
    793 	}
    794 	*result = tmp;
    795 	return (p_on? 2:1);
    796 }
    797 
    798 
    799 /*
    800  * csh-style history expansion
    801  */
    802 int
    803 history_expand(char *str, char **output)
    804 {
    805 	int ret = 0;
    806 	size_t idx, i, size;
    807 	char *tmp, *result;
    808 
    809 	if (h == NULL || e == NULL)
    810 		rl_initialize();
    811 
    812 	if (history_expansion_char == 0) {
    813 		*output = strdup(str);
    814 		return(0);
    815 	}
    816 
    817 	*output = NULL;
    818 	if (str[0] == history_subst_char) {
    819 		/* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
    820 		*output = malloc(strlen(str) + 4 + 1);
    821 		if (*output == NULL)
    822 			return 0;
    823 		(*output)[0] = (*output)[1] = history_expansion_char;
    824 		(*output)[2] = ':';
    825 		(*output)[3] = 's';
    826 		(void)strcpy((*output) + 4, str);
    827 		str = *output;
    828 	} else {
    829 		*output = strdup(str);
    830 		if (*output == NULL)
    831 			return 0;
    832 	}
    833 
    834 #define ADD_STRING(what, len)						\
    835 	{								\
    836 		if (idx + len + 1 > size) {				\
    837 			char *nresult = realloc(result, (size += len + 1));\
    838 			if (nresult == NULL) {				\
    839 				free(*output);				\
    840 				return 0;				\
    841 			}						\
    842 			result = nresult;				\
    843 		}							\
    844 		(void)strncpy(&result[idx], what, len);			\
    845 		idx += len;						\
    846 		result[idx] = '\0';					\
    847 	}
    848 
    849 	result = NULL;
    850 	size = idx = 0;
    851 	for (i = 0; str[i];) {
    852 		int qchar, loop_again;
    853 		size_t len, start, j;
    854 
    855 		qchar = 0;
    856 		loop_again = 1;
    857 		start = j = i;
    858 loop:
    859 		for (; str[j]; j++) {
    860 			if (str[j] == '\\' &&
    861 			    str[j + 1] == history_expansion_char) {
    862 				(void)strcpy(&str[j], &str[j + 1]);
    863 				continue;
    864 			}
    865 			if (!loop_again) {
    866 				if (isspace((unsigned char) str[j])
    867 				    || str[j] == qchar)
    868 					break;
    869 			}
    870 			if (str[j] == history_expansion_char
    871 			    && !strchr(history_no_expand_chars, str[j + 1])
    872 			    && (!history_inhibit_expansion_function ||
    873 			    (*history_inhibit_expansion_function)(str,
    874 			    (int)j) == 0))
    875 				break;
    876 		}
    877 
    878 		if (str[j] && loop_again) {
    879 			i = j;
    880 			qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
    881 			j++;
    882 			if (str[j] == history_expansion_char)
    883 				j++;
    884 			loop_again = 0;
    885 			goto loop;
    886 		}
    887 		len = i - start;
    888 		tmp = &str[start];
    889 		ADD_STRING(tmp, len);
    890 
    891 		if (str[i] == '\0' || str[i] != history_expansion_char) {
    892 			len = j - i;
    893 			tmp = &str[i];
    894 			ADD_STRING(tmp, len);
    895 			if (start == 0)
    896 				ret = 0;
    897 			else
    898 				ret = 1;
    899 			break;
    900 		}
    901 		ret = _history_expand_command (str, i, (j - i), &tmp);
    902 		if (ret > 0 && tmp) {
    903 			len = strlen(tmp);
    904 			ADD_STRING(tmp, len);
    905 			free(tmp);
    906 		}
    907 		i = j;
    908 	}
    909 
    910 	/* ret is 2 for "print only" option */
    911 	if (ret == 2) {
    912 		add_history(result);
    913 #ifdef GDB_411_HACK
    914 		/* gdb 4.11 has been shipped with readline, where */
    915 		/* history_expand() returned -1 when the line	  */
    916 		/* should not be executed; in readline 2.1+	  */
    917 		/* it should return 2 in such a case		  */
    918 		ret = -1;
    919 #endif
    920 	}
    921 	free(*output);
    922 	*output = result;
    923 
    924 	return (ret);
    925 }
    926 
    927 /*
    928 * Return a string consisting of arguments of "str" from "start" to "end".
    929 */
    930 char *
    931 history_arg_extract(int start, int end, const char *str)
    932 {
    933 	size_t  i, len, max;
    934 	char	**arr, *result;
    935 
    936 	arr = history_tokenize(str);
    937 	if (!arr)
    938 		return(NULL);
    939 	if (arr && *arr == NULL) {
    940 		free(arr);
    941 		return(NULL);
    942 	}
    943 
    944 	for (max = 0; arr[max]; max++)
    945 		continue;
    946 	max--;
    947 
    948 	if (start == '$')
    949 		start = max;
    950 	if (end == '$')
    951 		end = max;
    952 	if (end < 0)
    953 		end = max + end + 1;
    954 	if (start < 0)
    955 		start = end;
    956 
    957 	if (start < 0 || end < 0 || start > max || end > max || start > end)
    958 		return(NULL);
    959 
    960 	for (i = start, len = 0; i <= end; i++)
    961 		len += strlen(arr[i]) + 1;
    962 	len++;
    963 	result = malloc(len);
    964 	if (result == NULL)
    965 		return NULL;
    966 
    967 	for (i = start, len = 0; i <= end; i++) {
    968 		(void)strcpy(result + len, arr[i]);
    969 		len += strlen(arr[i]);
    970 		if (i < end)
    971 			result[len++] = ' ';
    972 	}
    973 	result[len] = 0;
    974 
    975 	for (i = 0; arr[i]; i++)
    976 		free(arr[i]);
    977 	free(arr);
    978 
    979 	return(result);
    980 }
    981 
    982 /*
    983  * Parse the string into individual tokens,
    984  * similar to how shell would do it.
    985  */
    986 char **
    987 history_tokenize(const char *str)
    988 {
    989 	int size = 1, idx = 0, i, start;
    990 	size_t len;
    991 	char **result = NULL, *temp, delim = '\0';
    992 
    993 	for (i = 0; str[i];) {
    994 		while (isspace((unsigned char) str[i]))
    995 			i++;
    996 		start = i;
    997 		for (; str[i];) {
    998 			if (str[i] == '\\') {
    999 				if (str[i+1] != '\0')
   1000 					i++;
   1001 			} else if (str[i] == delim)
   1002 				delim = '\0';
   1003 			else if (!delim &&
   1004 				    (isspace((unsigned char) str[i]) ||
   1005 				strchr("()<>;&|$", str[i])))
   1006 				break;
   1007 			else if (!delim && strchr("'`\"", str[i]))
   1008 				delim = str[i];
   1009 			if (str[i])
   1010 				i++;
   1011 		}
   1012 
   1013 		if (idx + 2 >= size) {
   1014 			char **nresult;
   1015 			size <<= 1;
   1016 			nresult = realloc(result, size * sizeof(char *));
   1017 			if (nresult == NULL) {
   1018 				free(result);
   1019 				return NULL;
   1020 			}
   1021 			result = nresult;
   1022 		}
   1023 		len = i - start;
   1024 		temp = malloc(len + 1);
   1025 		if (temp == NULL) {
   1026 			for (i = 0; i < idx; i++)
   1027 				free(result[i]);
   1028 			free(result);
   1029 			return NULL;
   1030 		}
   1031 		(void)strncpy(temp, &str[start], len);
   1032 		temp[len] = '\0';
   1033 		result[idx++] = temp;
   1034 		result[idx] = NULL;
   1035 		if (str[i])
   1036 			i++;
   1037 	}
   1038 	return (result);
   1039 }
   1040 
   1041 
   1042 /*
   1043  * limit size of history record to ``max'' events
   1044  */
   1045 void
   1046 stifle_history(int max)
   1047 {
   1048 	HistEvent ev;
   1049 
   1050 	if (h == NULL || e == NULL)
   1051 		rl_initialize();
   1052 
   1053 	if (history(h, &ev, H_SETSIZE, max) == 0)
   1054 		max_input_history = max;
   1055 }
   1056 
   1057 
   1058 /*
   1059  * "unlimit" size of history - set the limit to maximum allowed int value
   1060  */
   1061 int
   1062 unstifle_history(void)
   1063 {
   1064 	HistEvent ev;
   1065 	int omax;
   1066 
   1067 	history(h, &ev, H_SETSIZE, INT_MAX);
   1068 	omax = max_input_history;
   1069 	max_input_history = INT_MAX;
   1070 	return (omax);		/* some value _must_ be returned */
   1071 }
   1072 
   1073 
   1074 int
   1075 history_is_stifled(void)
   1076 {
   1077 
   1078 	/* cannot return true answer */
   1079 	return (max_input_history != INT_MAX);
   1080 }
   1081 
   1082 
   1083 /*
   1084  * read history from a file given
   1085  */
   1086 int
   1087 read_history(const char *filename)
   1088 {
   1089 	HistEvent ev;
   1090 
   1091 	if (h == NULL || e == NULL)
   1092 		rl_initialize();
   1093 	return (history(h, &ev, H_LOAD, filename));
   1094 }
   1095 
   1096 
   1097 /*
   1098  * write history to a file given
   1099  */
   1100 int
   1101 write_history(const char *filename)
   1102 {
   1103 	HistEvent ev;
   1104 
   1105 	if (h == NULL || e == NULL)
   1106 		rl_initialize();
   1107 	return (history(h, &ev, H_SAVE, filename));
   1108 }
   1109 
   1110 
   1111 /*
   1112  * returns history ``num''th event
   1113  *
   1114  * returned pointer points to static variable
   1115  */
   1116 HIST_ENTRY *
   1117 history_get(int num)
   1118 {
   1119 	static HIST_ENTRY she;
   1120 	HistEvent ev;
   1121 	int curr_num;
   1122 
   1123 	if (h == NULL || e == NULL)
   1124 		rl_initialize();
   1125 
   1126 	/* save current position */
   1127 	if (history(h, &ev, H_CURR) != 0)
   1128 		return (NULL);
   1129 	curr_num = ev.num;
   1130 
   1131 	/* start from most recent */
   1132 	if (history(h, &ev, H_FIRST) != 0)
   1133 		return (NULL);	/* error */
   1134 
   1135 	/* look backwards for event matching specified offset */
   1136 	if (history(h, &ev, H_NEXT_EVENT, num))
   1137 		return (NULL);
   1138 
   1139 	she.line = ev.str;
   1140 	she.data = NULL;
   1141 
   1142 	/* restore pointer to where it was */
   1143 	(void)history(h, &ev, H_SET, curr_num);
   1144 
   1145 	return (&she);
   1146 }
   1147 
   1148 
   1149 /*
   1150  * add the line to history table
   1151  */
   1152 int
   1153 add_history(const char *line)
   1154 {
   1155 	HistEvent ev;
   1156 
   1157 	if (h == NULL || e == NULL)
   1158 		rl_initialize();
   1159 
   1160 	(void)history(h, &ev, H_ENTER, line);
   1161 	if (history(h, &ev, H_GETSIZE) == 0)
   1162 		history_length = ev.num;
   1163 
   1164 	return (!(history_length > 0)); /* return 0 if all is okay */
   1165 }
   1166 
   1167 
   1168 /*
   1169  * clear the history list - delete all entries
   1170  */
   1171 void
   1172 clear_history(void)
   1173 {
   1174 	HistEvent ev;
   1175 
   1176 	history(h, &ev, H_CLEAR);
   1177 }
   1178 
   1179 
   1180 /*
   1181  * returns offset of the current history event
   1182  */
   1183 int
   1184 where_history(void)
   1185 {
   1186 	HistEvent ev;
   1187 	int curr_num, off;
   1188 
   1189 	if (history(h, &ev, H_CURR) != 0)
   1190 		return (0);
   1191 	curr_num = ev.num;
   1192 
   1193 	history(h, &ev, H_FIRST);
   1194 	off = 1;
   1195 	while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
   1196 		off++;
   1197 
   1198 	return (off);
   1199 }
   1200 
   1201 
   1202 /*
   1203  * returns current history event or NULL if there is no such event
   1204  */
   1205 HIST_ENTRY *
   1206 current_history(void)
   1207 {
   1208 
   1209 	return (_move_history(H_CURR));
   1210 }
   1211 
   1212 
   1213 /*
   1214  * returns total number of bytes history events' data are using
   1215  */
   1216 int
   1217 history_total_bytes(void)
   1218 {
   1219 	HistEvent ev;
   1220 	int curr_num, size;
   1221 
   1222 	if (history(h, &ev, H_CURR) != 0)
   1223 		return (-1);
   1224 	curr_num = ev.num;
   1225 
   1226 	history(h, &ev, H_FIRST);
   1227 	size = 0;
   1228 	do
   1229 		size += strlen(ev.str);
   1230 	while (history(h, &ev, H_NEXT) == 0);
   1231 
   1232 	/* get to the same position as before */
   1233 	history(h, &ev, H_PREV_EVENT, curr_num);
   1234 
   1235 	return (size);
   1236 }
   1237 
   1238 
   1239 /*
   1240  * sets the position in the history list to ``pos''
   1241  */
   1242 int
   1243 history_set_pos(int pos)
   1244 {
   1245 	HistEvent ev;
   1246 	int curr_num;
   1247 
   1248 	if (pos > history_length || pos < 0)
   1249 		return (-1);
   1250 
   1251 	history(h, &ev, H_CURR);
   1252 	curr_num = ev.num;
   1253 
   1254 	if (history(h, &ev, H_SET, pos)) {
   1255 		history(h, &ev, H_SET, curr_num);
   1256 		return(-1);
   1257 	}
   1258 	return (0);
   1259 }
   1260 
   1261 
   1262 /*
   1263  * returns previous event in history and shifts pointer accordingly
   1264  */
   1265 HIST_ENTRY *
   1266 previous_history(void)
   1267 {
   1268 
   1269 	return (_move_history(H_PREV));
   1270 }
   1271 
   1272 
   1273 /*
   1274  * returns next event in history and shifts pointer accordingly
   1275  */
   1276 HIST_ENTRY *
   1277 next_history(void)
   1278 {
   1279 
   1280 	return (_move_history(H_NEXT));
   1281 }
   1282 
   1283 
   1284 /*
   1285  * searches for first history event containing the str
   1286  */
   1287 int
   1288 history_search(const char *str, int direction)
   1289 {
   1290 	HistEvent ev;
   1291 	const char *strp;
   1292 	int curr_num;
   1293 
   1294 	if (history(h, &ev, H_CURR) != 0)
   1295 		return (-1);
   1296 	curr_num = ev.num;
   1297 
   1298 	for (;;) {
   1299 		if ((strp = strstr(ev.str, str)) != NULL)
   1300 			return (int) (strp - ev.str);
   1301 		if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
   1302 			break;
   1303 	}
   1304 	history(h, &ev, H_SET, curr_num);
   1305 	return (-1);
   1306 }
   1307 
   1308 
   1309 /*
   1310  * searches for first history event beginning with str
   1311  */
   1312 int
   1313 history_search_prefix(const char *str, int direction)
   1314 {
   1315 	HistEvent ev;
   1316 
   1317 	return (history(h, &ev, direction < 0? H_PREV_STR:H_NEXT_STR, str));
   1318 }
   1319 
   1320 
   1321 /*
   1322  * search for event in history containing str, starting at offset
   1323  * abs(pos); continue backward, if pos<0, forward otherwise
   1324  */
   1325 /* ARGSUSED */
   1326 int
   1327 history_search_pos(const char *str,
   1328 		   int direction __attribute__((__unused__)), int pos)
   1329 {
   1330 	HistEvent ev;
   1331 	int curr_num, off;
   1332 
   1333 	off = (pos > 0) ? pos : -pos;
   1334 	pos = (pos > 0) ? 1 : -1;
   1335 
   1336 	if (history(h, &ev, H_CURR) != 0)
   1337 		return (-1);
   1338 	curr_num = ev.num;
   1339 
   1340 	if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
   1341 		return (-1);
   1342 
   1343 
   1344 	for (;;) {
   1345 		if (strstr(ev.str, str))
   1346 			return (off);
   1347 		if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
   1348 			break;
   1349 	}
   1350 
   1351 	/* set "current" pointer back to previous state */
   1352 	history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
   1353 
   1354 	return (-1);
   1355 }
   1356 
   1357 
   1358 /********************************/
   1359 /* completion functions */
   1360 
   1361 /*
   1362  * does tilde expansion of strings of type ``~user/foo''
   1363  * if ``user'' isn't valid user name or ``txt'' doesn't start
   1364  * w/ '~', returns pointer to strdup()ed copy of ``txt''
   1365  *
   1366  * it's callers's responsibility to free() returned string
   1367  */
   1368 char *
   1369 tilde_expand(char *txt)
   1370 {
   1371 	struct passwd *pass;
   1372 	char *temp;
   1373 	size_t len = 0;
   1374 
   1375 	if (txt[0] != '~')
   1376 		return (strdup(txt));
   1377 
   1378 	temp = strchr(txt + 1, '/');
   1379 	if (temp == NULL) {
   1380 		temp = strdup(txt + 1);
   1381 		if (temp == NULL)
   1382 			return NULL;
   1383 	} else {
   1384 		len = temp - txt + 1;	/* text until string after slash */
   1385 		temp = malloc(len);
   1386 		if (temp == NULL)
   1387 			return NULL;
   1388 		(void)strncpy(temp, txt + 1, len - 2);
   1389 		temp[len - 2] = '\0';
   1390 	}
   1391 	pass = getpwnam(temp);
   1392 	free(temp);		/* value no more needed */
   1393 	if (pass == NULL)
   1394 		return (strdup(txt));
   1395 
   1396 	/* update pointer txt to point at string immedially following */
   1397 	/* first slash */
   1398 	txt += len;
   1399 
   1400 	temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
   1401 	if (temp == NULL)
   1402 		return NULL;
   1403 	(void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
   1404 
   1405 	return (temp);
   1406 }
   1407 
   1408 
   1409 /*
   1410  * return first found file name starting by the ``text'' or NULL if no
   1411  * such file can be found
   1412  * value of ``state'' is ignored
   1413  *
   1414  * it's caller's responsibility to free returned string
   1415  */
   1416 char *
   1417 filename_completion_function(const char *text, int state)
   1418 {
   1419 	static DIR *dir = NULL;
   1420 	static char *filename = NULL, *dirname = NULL;
   1421 	static size_t filename_len = 0;
   1422 	struct dirent *entry;
   1423 	char *temp;
   1424 	size_t len;
   1425 
   1426 	if (state == 0 || dir == NULL) {
   1427 		temp = strrchr(text, '/');
   1428 		if (temp) {
   1429 			char *nptr;
   1430 			temp++;
   1431 			nptr = realloc(filename, strlen(temp) + 1);
   1432 			if (nptr == NULL) {
   1433 				free(filename);
   1434 				return NULL;
   1435 			}
   1436 			filename = nptr;
   1437 			(void)strcpy(filename, temp);
   1438 			len = temp - text;	/* including last slash */
   1439 			nptr = realloc(dirname, len + 1);
   1440 			if (nptr == NULL) {
   1441 				free(filename);
   1442 				return NULL;
   1443 			}
   1444 			dirname = nptr;
   1445 			(void)strncpy(dirname, text, len);
   1446 			dirname[len] = '\0';
   1447 		} else {
   1448 			if (*text == 0)
   1449 				filename = NULL;
   1450 			else {
   1451 				filename = strdup(text);
   1452 				if (filename == NULL)
   1453 					return NULL;
   1454 			}
   1455 			dirname = NULL;
   1456 		}
   1457 
   1458 		/* support for ``~user'' syntax */
   1459 		if (dirname && *dirname == '~') {
   1460 			char *nptr;
   1461 			temp = tilde_expand(dirname);
   1462 			if (temp == NULL)
   1463 				return NULL;
   1464 			nptr = realloc(dirname, strlen(temp) + 1);
   1465 			if (nptr == NULL) {
   1466 				free(dirname);
   1467 				return NULL;
   1468 			}
   1469 			dirname = nptr;
   1470 			(void)strcpy(dirname, temp);	/* safe */
   1471 			free(temp);	/* no longer needed */
   1472 		}
   1473 		/* will be used in cycle */
   1474 		filename_len = filename ? strlen(filename) : 0;
   1475 
   1476 		if (dir != NULL) {
   1477 			(void)closedir(dir);
   1478 			dir = NULL;
   1479 		}
   1480 		dir = opendir(dirname ? dirname : ".");
   1481 		if (!dir)
   1482 			return (NULL);	/* cannot open the directory */
   1483 	}
   1484 	/* find the match */
   1485 	while ((entry = readdir(dir)) != NULL) {
   1486 		/* skip . and .. */
   1487 		if (entry->d_name[0] == '.' && (!entry->d_name[1]
   1488 		    || (entry->d_name[1] == '.' && !entry->d_name[2])))
   1489 			continue;
   1490 		if (filename_len == 0)
   1491 			break;
   1492 		/* otherwise, get first entry where first */
   1493 		/* filename_len characters are equal	  */
   1494 		if (entry->d_name[0] == filename[0]
   1495 #if defined(__SVR4) || defined(__linux__)
   1496 		    && strlen(entry->d_name) >= filename_len
   1497 #else
   1498 		    && entry->d_namlen >= filename_len
   1499 #endif
   1500 		    && strncmp(entry->d_name, filename,
   1501 			filename_len) == 0)
   1502 			break;
   1503 	}
   1504 
   1505 	if (entry) {		/* match found */
   1506 
   1507 		struct stat stbuf;
   1508 #if defined(__SVR4) || defined(__linux__)
   1509 		len = strlen(entry->d_name) +
   1510 #else
   1511 		len = entry->d_namlen +
   1512 #endif
   1513 		    ((dirname) ? strlen(dirname) : 0) + 1 + 1;
   1514 		temp = malloc(len);
   1515 		if (temp == NULL)
   1516 			return NULL;
   1517 		(void)sprintf(temp, "%s%s",
   1518 		    dirname ? dirname : "", entry->d_name);	/* safe */
   1519 
   1520 		/* test, if it's directory */
   1521 		if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
   1522 			strcat(temp, "/");	/* safe */
   1523 	} else {
   1524 		(void)closedir(dir);
   1525 		dir = NULL;
   1526 		temp = NULL;
   1527 	}
   1528 
   1529 	return (temp);
   1530 }
   1531 
   1532 
   1533 /*
   1534  * a completion generator for usernames; returns _first_ username
   1535  * which starts with supplied text
   1536  * text contains a partial username preceded by random character
   1537  * (usually '~'); state is ignored
   1538  * it's callers responsibility to free returned value
   1539  */
   1540 char *
   1541 username_completion_function(const char *text, int state)
   1542 {
   1543 	struct passwd *pwd;
   1544 
   1545 	if (text[0] == '\0')
   1546 		return (NULL);
   1547 
   1548 	if (*text == '~')
   1549 		text++;
   1550 
   1551 	if (state == 0)
   1552 		setpwent();
   1553 
   1554 	while ((pwd = getpwent()) && text[0] == pwd->pw_name[0]
   1555 	    && strcmp(text, pwd->pw_name) == 0);
   1556 
   1557 	if (pwd == NULL) {
   1558 		endpwent();
   1559 		return (NULL);
   1560 	}
   1561 	return (strdup(pwd->pw_name));
   1562 }
   1563 
   1564 
   1565 /*
   1566  * el-compatible wrapper around rl_complete; needed for key binding
   1567  */
   1568 /* ARGSUSED */
   1569 static unsigned char
   1570 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
   1571 {
   1572 	return (unsigned char) rl_complete(0, ch);
   1573 }
   1574 
   1575 
   1576 /*
   1577  * returns list of completions for text given
   1578  */
   1579 char **
   1580 completion_matches(const char *text, CPFunction *genfunc)
   1581 {
   1582 	char **match_list = NULL, *retstr, *prevstr;
   1583 	size_t match_list_len, max_equal, which, i;
   1584 	size_t matches;
   1585 
   1586 	if (h == NULL || e == NULL)
   1587 		rl_initialize();
   1588 
   1589 	matches = 0;
   1590 	match_list_len = 1;
   1591 	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
   1592 		/* allow for list terminator here */
   1593 		if (matches + 3 >= match_list_len) {
   1594 			char **nmatch_list;
   1595 			while (matches + 3 >= match_list_len)
   1596 				match_list_len <<= 1;
   1597 			nmatch_list = realloc(match_list,
   1598 			    match_list_len * sizeof(char *));
   1599 			if (nmatch_list == NULL) {
   1600 				free(match_list);
   1601 				return NULL;
   1602 			}
   1603 			match_list = nmatch_list;
   1604 
   1605 		}
   1606 		match_list[++matches] = retstr;
   1607 	}
   1608 
   1609 	if (!match_list)
   1610 		return NULL;	/* nothing found */
   1611 
   1612 	/* find least denominator and insert it to match_list[0] */
   1613 	which = 2;
   1614 	prevstr = match_list[1];
   1615 	max_equal = strlen(prevstr);
   1616 	for (; which <= matches; which++) {
   1617 		for (i = 0; i < max_equal &&
   1618 		    prevstr[i] == match_list[which][i]; i++)
   1619 			continue;
   1620 		max_equal = i;
   1621 	}
   1622 
   1623 	retstr = malloc(max_equal + 1);
   1624 	if (retstr == NULL) {
   1625 		free(match_list);
   1626 		return NULL;
   1627 	}
   1628 	(void)strncpy(retstr, match_list[1], max_equal);
   1629 	retstr[max_equal] = '\0';
   1630 	match_list[0] = retstr;
   1631 
   1632 	/* add NULL as last pointer to the array */
   1633 	match_list[matches + 1] = (char *) NULL;
   1634 
   1635 	return (match_list);
   1636 }
   1637 
   1638 /*
   1639  * Sort function for qsort(). Just wrapper around strcasecmp().
   1640  */
   1641 static int
   1642 _rl_qsort_string_compare(i1, i2)
   1643 	const void *i1, *i2;
   1644 {
   1645 	const char *s1 = ((const char * const *)i1)[0];
   1646 	const char *s2 = ((const char * const *)i2)[0];
   1647 
   1648 	return strcasecmp(s1, s2);
   1649 }
   1650 
   1651 /*
   1652  * Display list of strings in columnar format on readline's output stream.
   1653  * 'matches' is list of strings, 'len' is number of strings in 'matches',
   1654  * 'max' is maximum length of string in 'matches'.
   1655  */
   1656 void
   1657 rl_display_match_list (matches, len, max)
   1658      char **matches;
   1659      int len, max;
   1660 {
   1661 	int i, idx, limit, count;
   1662 	int screenwidth = e->el_term.t_size.h;
   1663 
   1664 	/*
   1665 	 * Find out how many entries can be put on one line, count
   1666 	 * with two spaces between strings.
   1667 	 */
   1668 	limit = screenwidth / (max + 2);
   1669 	if (limit == 0)
   1670 		limit = 1;
   1671 
   1672 	/* how many lines of output */
   1673 	count = len / limit;
   1674 	if (count * limit < len)
   1675 		count++;
   1676 
   1677 	/* Sort the items if they are not already sorted. */
   1678 	qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
   1679 	    _rl_qsort_string_compare);
   1680 
   1681 	idx = 1;
   1682 	for(; count > 0; count--) {
   1683 		for(i = 0; i < limit && matches[idx]; i++, idx++)
   1684 			(void)fprintf(e->el_outfile, "%-*s  ", max,
   1685 			    matches[idx]);
   1686 		(void)fprintf(e->el_outfile, "\n");
   1687 	}
   1688 }
   1689 
   1690 /*
   1691  * Complete the word at or before point, called by rl_complete()
   1692  * 'what_to_do' says what to do with the completion.
   1693  * `?' means list the possible completions.
   1694  * TAB means do standard completion.
   1695  * `*' means insert all of the possible completions.
   1696  * `!' means to do standard completion, and list all possible completions if
   1697  * there is more than one.
   1698  *
   1699  * Note: '*' support is not implemented
   1700  */
   1701 static int
   1702 rl_complete_internal(int what_to_do)
   1703 {
   1704 	Function *complet_func;
   1705 	const LineInfo *li;
   1706 	char *temp, **matches;
   1707 	const char *ctemp;
   1708 	size_t len;
   1709 
   1710 	rl_completion_type = what_to_do;
   1711 
   1712 	if (h == NULL || e == NULL)
   1713 		rl_initialize();
   1714 
   1715 	complet_func = rl_completion_entry_function;
   1716 	if (!complet_func)
   1717 		complet_func = (Function *)(void *)filename_completion_function;
   1718 
   1719 	/* We now look backwards for the start of a filename/variable word */
   1720 	li = el_line(e);
   1721 	ctemp = (const char *) li->cursor;
   1722 	while (ctemp > li->buffer
   1723 	    && !strchr(rl_basic_word_break_characters, ctemp[-1])
   1724 	    && (!rl_special_prefixes
   1725 		|| !strchr(rl_special_prefixes, ctemp[-1]) ) )
   1726 		ctemp--;
   1727 
   1728 	len = li->cursor - ctemp;
   1729 	temp = alloca(len + 1);
   1730 	(void)strncpy(temp, ctemp, len);
   1731 	temp[len] = '\0';
   1732 
   1733 	/* these can be used by function called in completion_matches() */
   1734 	/* or (*rl_attempted_completion_function)() */
   1735 	rl_point = li->cursor - li->buffer;
   1736 	rl_end = li->lastchar - li->buffer;
   1737 
   1738 	if (rl_attempted_completion_function) {
   1739 		int end = li->cursor - li->buffer;
   1740 		matches = (*rl_attempted_completion_function) (temp, (int)
   1741 		    (end - len), end);
   1742 	} else
   1743 		matches = 0;
   1744 	if (!rl_attempted_completion_function || !matches)
   1745 		matches = completion_matches(temp, (CPFunction *)complet_func);
   1746 
   1747 	if (matches) {
   1748 		int i, retval = CC_REFRESH;
   1749 		int matches_num, maxlen, match_len, match_display=1;
   1750 
   1751 		/*
   1752 		 * Only replace the completed string with common part of
   1753 		 * possible matches if there is possible completion.
   1754 		 */
   1755 		if (matches[0][0] != '\0') {
   1756 			el_deletestr(e, (int) len);
   1757 			el_insertstr(e, matches[0]);
   1758 		}
   1759 
   1760 		if (what_to_do == '?')
   1761 			goto display_matches;
   1762 
   1763 		if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
   1764 			/*
   1765 			 * We found exact match. Add a space after
   1766 			 * it, unless we do filename completion and the
   1767 			 * object is a directory.
   1768 			 */
   1769 			size_t alen = strlen(matches[0]);
   1770 			if ((complet_func !=
   1771 			    (Function *)filename_completion_function
   1772 			      || (alen > 0 && (matches[0])[alen - 1] != '/'))
   1773 			    && rl_completion_append_character) {
   1774 				char buf[2];
   1775 				buf[0] = rl_completion_append_character;
   1776 				buf[1] = '\0';
   1777 				el_insertstr(e, buf);
   1778 			}
   1779 		} else if (what_to_do == '!') {
   1780     display_matches:
   1781 			/*
   1782 			 * More than one match and requested to list possible
   1783 			 * matches.
   1784 			 */
   1785 
   1786 			for(i=1, maxlen=0; matches[i]; i++) {
   1787 				match_len = strlen(matches[i]);
   1788 				if (match_len > maxlen)
   1789 					maxlen = match_len;
   1790 			}
   1791 			matches_num = i - 1;
   1792 
   1793 			/* newline to get on next line from command line */
   1794 			(void)fprintf(e->el_outfile, "\n");
   1795 
   1796 			/*
   1797 			 * If there are too many items, ask user for display
   1798 			 * confirmation.
   1799 			 */
   1800 			if (matches_num > rl_completion_query_items) {
   1801 				(void)fprintf(e->el_outfile,
   1802 				    "Display all %d possibilities? (y or n) ",
   1803 				    matches_num);
   1804 				(void)fflush(e->el_outfile);
   1805 				if (getc(stdin) != 'y')
   1806 					match_display = 0;
   1807 				(void)fprintf(e->el_outfile, "\n");
   1808 			}
   1809 
   1810 			if (match_display)
   1811 				rl_display_match_list(matches, matches_num,
   1812 					maxlen);
   1813 			retval = CC_REDISPLAY;
   1814 		} else if (matches[0][0]) {
   1815 			/*
   1816 			 * There was some common match, but the name was
   1817 			 * not complete enough. Next tab will print possible
   1818 			 * completions.
   1819 			 */
   1820 			el_beep(e);
   1821 		} else {
   1822 			/* lcd is not a valid object - further specification */
   1823 			/* is needed */
   1824 			el_beep(e);
   1825 			retval = CC_NORM;
   1826 		}
   1827 
   1828 		/* free elements of array and the array itself */
   1829 		for (i = 0; matches[i]; i++)
   1830 			free(matches[i]);
   1831 		free(matches), matches = NULL;
   1832 
   1833 		return (retval);
   1834 	}
   1835 	return (CC_NORM);
   1836 }
   1837 
   1838 
   1839 /*
   1840  * complete word at current point
   1841  */
   1842 int
   1843 rl_complete(int ignore, int invoking_key)
   1844 {
   1845 	if (h == NULL || e == NULL)
   1846 		rl_initialize();
   1847 
   1848 	if (rl_inhibit_completion) {
   1849 		rl_insert(ignore, invoking_key);
   1850 		return (CC_REFRESH);
   1851 	} else if (e->el_state.lastcmd == el_rl_complete_cmdnum)
   1852 		return rl_complete_internal('?');
   1853 	else if (_rl_complete_show_all)
   1854 		return rl_complete_internal('!');
   1855 	else
   1856 		return (rl_complete_internal(TAB));
   1857 }
   1858 
   1859 
   1860 /*
   1861  * misc other functions
   1862  */
   1863 
   1864 /*
   1865  * bind key c to readline-type function func
   1866  */
   1867 int
   1868 rl_bind_key(int c, int func(int, int))
   1869 {
   1870 	int retval = -1;
   1871 
   1872 	if (h == NULL || e == NULL)
   1873 		rl_initialize();
   1874 
   1875 	if (func == rl_insert) {
   1876 		/* XXX notice there is no range checking of ``c'' */
   1877 		e->el_map.key[c] = ED_INSERT;
   1878 		retval = 0;
   1879 	}
   1880 	return (retval);
   1881 }
   1882 
   1883 
   1884 /*
   1885  * read one key from input - handles chars pushed back
   1886  * to input stream also
   1887  */
   1888 int
   1889 rl_read_key(void)
   1890 {
   1891 	char fooarr[2 * sizeof(int)];
   1892 
   1893 	if (e == NULL || h == NULL)
   1894 		rl_initialize();
   1895 
   1896 	return (el_getc(e, fooarr));
   1897 }
   1898 
   1899 
   1900 /*
   1901  * reset the terminal
   1902  */
   1903 /* ARGSUSED */
   1904 void
   1905 rl_reset_terminal(const char *p __attribute__((__unused__)))
   1906 {
   1907 
   1908 	if (h == NULL || e == NULL)
   1909 		rl_initialize();
   1910 	el_reset(e);
   1911 }
   1912 
   1913 
   1914 /*
   1915  * insert character ``c'' back into input stream, ``count'' times
   1916  */
   1917 int
   1918 rl_insert(int count, int c)
   1919 {
   1920 	char arr[2];
   1921 
   1922 	if (h == NULL || e == NULL)
   1923 		rl_initialize();
   1924 
   1925 	/* XXX - int -> char conversion can lose on multichars */
   1926 	arr[0] = c;
   1927 	arr[1] = '\0';
   1928 
   1929 	for (; count > 0; count--)
   1930 		el_push(e, arr);
   1931 
   1932 	return (0);
   1933 }
   1934 
   1935 /*ARGSUSED*/
   1936 int
   1937 rl_newline(int count, int c)
   1938 {
   1939 	/*
   1940 	 * Readline-4.0 appears to ignore the args.
   1941 	 */
   1942 	return rl_insert(1, '\n');
   1943 }
   1944 
   1945 /*ARGSUSED*/
   1946 static unsigned char
   1947 rl_bind_wrapper(EditLine *el, unsigned char c)
   1948 {
   1949 	if (map[c] == NULL)
   1950 	    return CC_ERROR;
   1951 	(*map[c])(NULL, c);
   1952 
   1953 	/* If rl_done was set by the above call, deal with it here */
   1954 	if (rl_done)
   1955 		return CC_EOF;
   1956 
   1957 	return CC_NORM;
   1958 }
   1959 
   1960 int
   1961 rl_add_defun(const char *name, Function *fun, int c)
   1962 {
   1963 	char dest[8];
   1964 	if (c >= sizeof(map) / sizeof(map[0]) || c < 0)
   1965 		return -1;
   1966 	map[(unsigned char)c] = fun;
   1967 	el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
   1968 	vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
   1969 	el_set(e, EL_BIND, dest, name);
   1970 	return 0;
   1971 }
   1972 
   1973 void
   1974 rl_callback_read_char()
   1975 {
   1976 	int count = 0, done = 0;
   1977 	const char *buf = el_gets(e, &count);
   1978 	char *wbuf;
   1979 
   1980 	if (buf == NULL || count-- <= 0)
   1981 		return;
   1982 	if (count == 0 && buf[0] == CTRL('d'))
   1983 		done = 1;
   1984 	if (buf[count] == '\n' || buf[count] == '\r')
   1985 		done = 2;
   1986 
   1987 	if (done && rl_linefunc != NULL) {
   1988 		el_set(e, EL_UNBUFFERED, 0);
   1989 		if (done == 2) {
   1990 		    if ((wbuf = strdup(buf)) != NULL)
   1991 			wbuf[count] = '\0';
   1992 		} else
   1993 			wbuf = NULL;
   1994 		(*(void (*)(const char *))rl_linefunc)(wbuf);
   1995 	}
   1996 }
   1997 
   1998 void
   1999 rl_callback_handler_install (const char *prompt, VFunction *linefunc)
   2000 {
   2001 	if (e == NULL) {
   2002 		rl_initialize();
   2003 	}
   2004 	if (rl_prompt)
   2005 		free(rl_prompt);
   2006 	rl_prompt = prompt ? strdup(strchr(prompt, *prompt)) : NULL;
   2007 	rl_linefunc = linefunc;
   2008 	el_set(e, EL_UNBUFFERED, 1);
   2009 }
   2010 
   2011 void
   2012 rl_callback_handler_remove(void)
   2013 {
   2014 	el_set(e, EL_UNBUFFERED, 0);
   2015 }
   2016 
   2017 void
   2018 rl_redisplay(void)
   2019 {
   2020 	char a[2];
   2021 	a[0] = CTRL('r');
   2022 	a[1] = '\0';
   2023 	el_push(e, a);
   2024 }
   2025 
   2026 int
   2027 rl_get_previous_history(int count, int key)
   2028 {
   2029 	char a[2];
   2030 	a[0] = key;
   2031 	a[1] = '\0';
   2032 	while (count--)
   2033 		el_push(e, a);
   2034 	return 0;
   2035 }
   2036 
   2037 void
   2038 /*ARGSUSED*/
   2039 rl_prep_terminal(int meta_flag)
   2040 {
   2041 	el_set(e, EL_PREP_TERM, 1);
   2042 }
   2043 
   2044 void
   2045 rl_deprep_terminal()
   2046 {
   2047 	el_set(e, EL_PREP_TERM, 0);
   2048 }
   2049 
   2050 int
   2051 rl_read_init_file(const char *s)
   2052 {
   2053 	return(el_source(e, s));
   2054 }
   2055 
   2056 int
   2057 rl_parse_and_bind(const char *line)
   2058 {
   2059 	const char **argv;
   2060 	int argc;
   2061 	Tokenizer *tok;
   2062 
   2063 	tok = tok_init(NULL);
   2064 	tok_line(tok, line, &argc, &argv);
   2065 	argc = el_parse(e, argc, argv);
   2066 	tok_end(tok);
   2067 	return (argc ? 1 : 0);
   2068 }
   2069 
   2070 void
   2071 rl_stuff_char(int c)
   2072 {
   2073 	char buf[2];
   2074 
   2075 	buf[0] = c;
   2076 	buf[1] = '\0';
   2077 	el_insertstr(e, buf);
   2078 }
   2079 
   2080 static int
   2081 _rl_event_read_char(EditLine *el, char *cp)
   2082 {
   2083 	int	n, num_read = 0;
   2084 
   2085 	*cp = 0;
   2086 	while (rl_event_hook) {
   2087 
   2088 		(*rl_event_hook)();
   2089 
   2090 #if defined(FIONREAD)
   2091 		if (ioctl(el->el_infd, FIONREAD, &n) < 0)
   2092 			return(-1);
   2093 		if (n)
   2094 			num_read = read(el->el_infd, cp, 1);
   2095 		else
   2096 			num_read = 0;
   2097 #elif defined(F_SETFL) && defined(O_NDELAY)
   2098 		if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
   2099 			return(-1);
   2100 		if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
   2101 			return(-1);
   2102 		num_read = read(el->el_infd, cp, 1);
   2103 		if (fcntl(el->el_infd, F_SETFL, n))
   2104 			return(-1);
   2105 #else
   2106 		/* not non-blocking, but what you gonna do? */
   2107 		num_read = read(el->el_infd, cp, 1);
   2108 		return(-1);
   2109 #endif
   2110 
   2111 		if (num_read < 0 && errno == EAGAIN)
   2112 			continue;
   2113 		if (num_read == 0)
   2114 			continue;
   2115 		break;
   2116 	}
   2117 	if (!rl_event_hook)
   2118 		el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
   2119 	return(num_read);
   2120 }
   2121