Home | History | Annotate | Line # | Download | only in libedit
readline.c revision 1.40
      1 /*	$NetBSD: readline.c,v 1.40 2003/10/27 22:26:35 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.40 2003/10/27 22:26:35 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 
    579 	/* First get event specifier */
    580 	idx = 0;
    581 
    582 	if (strchr(":^*$", command[offs + 1])) {
    583 		char str[4];
    584 		/*
    585 		* "!:" is shorthand for "!!:".
    586 		* "!^", "!*" and "!$" are shorthand for
    587 		* "!!:^", "!!:*" and "!!:$" respectively.
    588 		*/
    589 		str[0] = str[1] = '!';
    590 		str[2] = '0';
    591 		ptr = get_history_event(str, &idx, 0);
    592 		idx = (command[offs + 1] == ':')? 1:0;
    593 		has_mods = 1;
    594 	} else {
    595 		if (command[offs + 1] == '#') {
    596 			/* use command so far */
    597 			if ((aptr = malloc(offs + 1)) == NULL)
    598 				return -1;
    599 			(void)strncpy(aptr, command, offs);
    600 			aptr[offs] = '\0';
    601 			idx = 1;
    602 		} else {
    603 			int	qchar;
    604 
    605 			qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
    606 			ptr = get_history_event(command + offs, &idx, qchar);
    607 		}
    608 		has_mods = command[offs + idx] == ':';
    609 	}
    610 
    611 	if (ptr == NULL && aptr == NULL)
    612 		return(-1);
    613 
    614 	if (!has_mods) {
    615 		*result = strdup(aptr? aptr : ptr);
    616 		if (aptr)
    617 			free(aptr);
    618 		return(1);
    619 	}
    620 
    621 	cmd = command + offs + idx + 1;
    622 
    623 	/* Now parse any word designators */
    624 
    625 	if (*cmd == '%')	/* last word matched by ?pat? */
    626 		tmp = strdup(last_search_match? last_search_match:"");
    627 	else if (strchr("^*$-0123456789", *cmd)) {
    628 		start = end = -1;
    629 		if (*cmd == '^')
    630 			start = end = 1, cmd++;
    631 		else if (*cmd == '$')
    632 			start = -1, cmd++;
    633 		else if (*cmd == '*')
    634 			start = 1, cmd++;
    635 	       else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
    636 			start = 0;
    637 			while (*cmd && '0' <= *cmd && *cmd <= '9')
    638 				start = start * 10 + *cmd++ - '0';
    639 
    640 			if (*cmd == '-') {
    641 				if (isdigit((unsigned char) cmd[1])) {
    642 					cmd++;
    643 					end = 0;
    644 					while (*cmd && '0' <= *cmd && *cmd <= '9')
    645 						end = end * 10 + *cmd++ - '0';
    646 				} else if (cmd[1] == '$') {
    647 					cmd += 2;
    648 					end = -1;
    649 				} else {
    650 					cmd++;
    651 					end = -2;
    652 				}
    653 			} else if (*cmd == '*')
    654 				end = -1, cmd++;
    655 			else
    656 				end = start;
    657 		}
    658 		tmp = history_arg_extract(start, end, aptr? aptr:ptr);
    659 		if (tmp == NULL) {
    660 			(void)fprintf(rl_outstream, "%s: Bad word specifier",
    661 			    command + offs + idx);
    662 			if (aptr)
    663 				free(aptr);
    664 			return(-1);
    665 		}
    666 	} else
    667 		tmp = strdup(aptr? aptr:ptr);
    668 
    669 	if (aptr)
    670 		free(aptr);
    671 
    672 	if (*cmd == 0 || (cmd - (command + offs) >= cmdlen)) {
    673 		*result = tmp;
    674 		return(1);
    675 	}
    676 
    677 	for (; *cmd; cmd++) {
    678 		if (*cmd == ':')
    679 			continue;
    680 		else if (*cmd == 'h') {		/* remove trailing path */
    681 			if ((aptr = strrchr(tmp, '/')) != NULL)
    682 				*aptr = 0;
    683 		} else if (*cmd == 't') {	/* remove leading path */
    684 			if ((aptr = strrchr(tmp, '/')) != NULL) {
    685 				aptr = strdup(aptr + 1);
    686 				free(tmp);
    687 				tmp = aptr;
    688 			}
    689 		} else if (*cmd == 'r') {	/* remove trailing suffix */
    690 			if ((aptr = strrchr(tmp, '.')) != NULL)
    691 				*aptr = 0;
    692 		} else if (*cmd == 'e') {	/* remove all but suffix */
    693 			if ((aptr = strrchr(tmp, '.')) != NULL) {
    694 				aptr = strdup(aptr);
    695 				free(tmp);
    696 				tmp = aptr;
    697 			}
    698 		} else if (*cmd == 'p')		/* print only */
    699 			p_on = 1;
    700 		else if (*cmd == 'g')
    701 			g_on = 2;
    702 		else if (*cmd == 's' || *cmd == '&') {
    703 			char *what, *with, delim;
    704 			size_t len, from_len;
    705 			size_t size;
    706 
    707 			if (*cmd == '&' && (from == NULL || to == NULL))
    708 				continue;
    709 			else if (*cmd == 's') {
    710 				delim = *(++cmd), cmd++;
    711 				size = 16;
    712 				what = realloc(from, size);
    713 				if (what == NULL) {
    714 					free(from);
    715 					return 0;
    716 				}
    717 				len = 0;
    718 				for (; *cmd && *cmd != delim; cmd++) {
    719 					if (*cmd == '\\' && cmd[1] == delim)
    720 						cmd++;
    721 					if (len >= size) {
    722 						char *nwhat;
    723 						nwhat = realloc(what,
    724 								(size <<= 1));
    725 						if (nwhat == NULL) {
    726 							free(what);
    727 							return 0;
    728 						}
    729 						what = nwhat;
    730 					}
    731 					what[len++] = *cmd;
    732 				}
    733 				what[len] = '\0';
    734 				from = what;
    735 				if (*what == '\0') {
    736 					free(what);
    737 					if (search) {
    738 						from = strdup(search);
    739 						if (from == NULL)
    740 							return 0;
    741 					} else {
    742 						from = NULL;
    743 						return (-1);
    744 					}
    745 				}
    746 				cmd++;	/* shift after delim */
    747 				if (!*cmd)
    748 					continue;
    749 
    750 				size = 16;
    751 				with = realloc(to, size);
    752 				if (with == NULL) {
    753 					free(to);
    754 					return -1;
    755 				}
    756 				len = 0;
    757 				from_len = strlen(from);
    758 				for (; *cmd && *cmd != delim; cmd++) {
    759 					if (len + from_len + 1 >= size) {
    760 						char *nwith;
    761 						size += from_len + 1;
    762 						nwith = realloc(with, size);
    763 						if (nwith == NULL) {
    764 							free(with);
    765 							return -1;
    766 						}
    767 						with = nwith;
    768 					}
    769 					if (*cmd == '&') {
    770 						/* safe */
    771 						(void)strcpy(&with[len], from);
    772 						len += from_len;
    773 						continue;
    774 					}
    775 					if (*cmd == '\\'
    776 					    && (*(cmd + 1) == delim
    777 						|| *(cmd + 1) == '&'))
    778 						cmd++;
    779 					with[len++] = *cmd;
    780 				}
    781 				with[len] = '\0';
    782 				to = with;
    783 			}
    784 
    785 			aptr = _rl_compat_sub(tmp, from, to, g_on);
    786 			if (aptr) {
    787 				free(tmp);
    788 				tmp = aptr;
    789 			}
    790 			g_on = 0;
    791 		}
    792 	}
    793 	*result = tmp;
    794 	return (p_on? 2:1);
    795 }
    796 
    797 
    798 /*
    799  * csh-style history expansion
    800  */
    801 int
    802 history_expand(char *str, char **output)
    803 {
    804 	int ret = 0;
    805 	size_t idx, i, size;
    806 	char *tmp, *result;
    807 
    808 	if (h == NULL || e == NULL)
    809 		rl_initialize();
    810 
    811 	if (history_expansion_char == 0) {
    812 		*output = strdup(str);
    813 		return(0);
    814 	}
    815 
    816 	*output = NULL;
    817 	if (str[0] == history_subst_char) {
    818 		/* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
    819 		*output = malloc(strlen(str) + 4 + 1);
    820 		if (*output == NULL)
    821 			return 0;
    822 		(*output)[0] = (*output)[1] = history_expansion_char;
    823 		(*output)[2] = ':';
    824 		(*output)[3] = 's';
    825 		(void)strcpy((*output) + 4, str);
    826 		str = *output;
    827 	} else {
    828 		*output = strdup(str);
    829 		if (*output == NULL)
    830 			return 0;
    831 	}
    832 
    833 #define ADD_STRING(what, len)						\
    834 	{								\
    835 		if (idx + len + 1 > size) {				\
    836 			char *nresult = realloc(result, (size += len + 1));\
    837 			if (nresult == NULL) {				\
    838 				free(*output);				\
    839 				return 0;				\
    840 			}						\
    841 			result = nresult;				\
    842 		}							\
    843 		(void)strncpy(&result[idx], what, len);			\
    844 		idx += len;						\
    845 		result[idx] = '\0';					\
    846 	}
    847 
    848 	result = NULL;
    849 	size = idx = 0;
    850 	for (i = 0; str[i];) {
    851 		int qchar, loop_again;
    852 		size_t len, start, j;
    853 
    854 		qchar = 0;
    855 		loop_again = 1;
    856 		start = j = i;
    857 loop:
    858 		for (; str[j]; j++) {
    859 			if (str[j] == '\\' &&
    860 			    str[j + 1] == history_expansion_char) {
    861 				(void)strcpy(&str[j], &str[j + 1]);
    862 				continue;
    863 			}
    864 			if (!loop_again) {
    865 				if (isspace((unsigned char) str[j])
    866 				    || str[j] == qchar)
    867 					break;
    868 			}
    869 			if (str[j] == history_expansion_char
    870 			    && !strchr(history_no_expand_chars, str[j + 1])
    871 			    && (!history_inhibit_expansion_function ||
    872 			    (*history_inhibit_expansion_function)(str,
    873 			    (int)j) == 0))
    874 				break;
    875 		}
    876 
    877 		if (str[j] && loop_again) {
    878 			i = j;
    879 			qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
    880 			j++;
    881 			if (str[j] == history_expansion_char)
    882 				j++;
    883 			loop_again = 0;
    884 			goto loop;
    885 		}
    886 		len = i - start;
    887 		tmp = &str[start];
    888 		ADD_STRING(tmp, len);
    889 
    890 		if (str[i] == '\0' || str[i] != history_expansion_char) {
    891 			len = j - i;
    892 			tmp = &str[i];
    893 			ADD_STRING(tmp, len);
    894 			if (start == 0)
    895 				ret = 0;
    896 			else
    897 				ret = 1;
    898 			break;
    899 		}
    900 		ret = _history_expand_command (str, i, (j - i), &tmp);
    901 		if (ret > 0 && tmp) {
    902 			len = strlen(tmp);
    903 			ADD_STRING(tmp, len);
    904 			free(tmp);
    905 		}
    906 		i = j;
    907 	}
    908 
    909 	/* ret is 2 for "print only" option */
    910 	if (ret == 2) {
    911 		add_history(result);
    912 #ifdef GDB_411_HACK
    913 		/* gdb 4.11 has been shipped with readline, where */
    914 		/* history_expand() returned -1 when the line	  */
    915 		/* should not be executed; in readline 2.1+	  */
    916 		/* it should return 2 in such a case		  */
    917 		ret = -1;
    918 #endif
    919 	}
    920 	free(*output);
    921 	*output = result;
    922 
    923 	return (ret);
    924 }
    925 
    926 /*
    927 * Return a string consisting of arguments of "str" from "start" to "end".
    928 */
    929 char *
    930 history_arg_extract(int start, int end, const char *str)
    931 {
    932 	size_t  i, len, max;
    933 	char	**arr, *result;
    934 
    935 	arr = history_tokenize(str);
    936 	if (!arr)
    937 		return(NULL);
    938 	if (arr && *arr == NULL) {
    939 		free(arr);
    940 		return(NULL);
    941 	}
    942 
    943 	for (max = 0; arr[max]; max++)
    944 		continue;
    945 	max--;
    946 
    947 	if (start == '$')
    948 		start = max;
    949 	if (end == '$')
    950 		end = max;
    951 	if (end < 0)
    952 		end = max + end + 1;
    953 	if (start < 0)
    954 		start = end;
    955 
    956 	if (start < 0 || end < 0 || start > max || end > max || start > end)
    957 		return(NULL);
    958 
    959 	for (i = start, len = 0; i <= end; i++)
    960 		len += strlen(arr[i]) + 1;
    961 	len++;
    962 	result = malloc(len);
    963 	if (result == NULL)
    964 		return NULL;
    965 
    966 	for (i = start, len = 0; i <= end; i++) {
    967 		(void)strcpy(result + len, arr[i]);
    968 		len += strlen(arr[i]);
    969 		if (i < end)
    970 			result[len++] = ' ';
    971 	}
    972 	result[len] = 0;
    973 
    974 	for (i = 0; arr[i]; i++)
    975 		free(arr[i]);
    976 	free(arr);
    977 
    978 	return(result);
    979 }
    980 
    981 /*
    982  * Parse the string into individual tokens,
    983  * similar to how shell would do it.
    984  */
    985 char **
    986 history_tokenize(const char *str)
    987 {
    988 	int size = 1, idx = 0, i, start;
    989 	size_t len;
    990 	char **result = NULL, *temp, delim = '\0';
    991 
    992 	for (i = 0; str[i];) {
    993 		while (isspace((unsigned char) str[i]))
    994 			i++;
    995 		start = i;
    996 		for (; str[i];) {
    997 			if (str[i] == '\\') {
    998 				if (str[i+1] != '\0')
    999 					i++;
   1000 			} else if (str[i] == delim)
   1001 				delim = '\0';
   1002 			else if (!delim &&
   1003 				    (isspace((unsigned char) str[i]) ||
   1004 				strchr("()<>;&|$", str[i])))
   1005 				break;
   1006 			else if (!delim && strchr("'`\"", str[i]))
   1007 				delim = str[i];
   1008 			if (str[i])
   1009 				i++;
   1010 		}
   1011 
   1012 		if (idx + 2 >= size) {
   1013 			char **nresult;
   1014 			size <<= 1;
   1015 			nresult = realloc(result, size * sizeof(char *));
   1016 			if (nresult == NULL) {
   1017 				free(result);
   1018 				return NULL;
   1019 			}
   1020 			result = nresult;
   1021 		}
   1022 		len = i - start;
   1023 		temp = malloc(len + 1);
   1024 		if (temp == NULL) {
   1025 			for (i = 0; i < idx; i++)
   1026 				free(result[i]);
   1027 			free(result);
   1028 			return NULL;
   1029 		}
   1030 		(void)strncpy(temp, &str[start], len);
   1031 		temp[len] = '\0';
   1032 		result[idx++] = temp;
   1033 		result[idx] = NULL;
   1034 		if (str[i])
   1035 			i++;
   1036 	}
   1037 	return (result);
   1038 }
   1039 
   1040 
   1041 /*
   1042  * limit size of history record to ``max'' events
   1043  */
   1044 void
   1045 stifle_history(int max)
   1046 {
   1047 	HistEvent ev;
   1048 
   1049 	if (h == NULL || e == NULL)
   1050 		rl_initialize();
   1051 
   1052 	if (history(h, &ev, H_SETSIZE, max) == 0)
   1053 		max_input_history = max;
   1054 }
   1055 
   1056 
   1057 /*
   1058  * "unlimit" size of history - set the limit to maximum allowed int value
   1059  */
   1060 int
   1061 unstifle_history(void)
   1062 {
   1063 	HistEvent ev;
   1064 	int omax;
   1065 
   1066 	history(h, &ev, H_SETSIZE, INT_MAX);
   1067 	omax = max_input_history;
   1068 	max_input_history = INT_MAX;
   1069 	return (omax);		/* some value _must_ be returned */
   1070 }
   1071 
   1072 
   1073 int
   1074 history_is_stifled(void)
   1075 {
   1076 
   1077 	/* cannot return true answer */
   1078 	return (max_input_history != INT_MAX);
   1079 }
   1080 
   1081 
   1082 /*
   1083  * read history from a file given
   1084  */
   1085 int
   1086 read_history(const char *filename)
   1087 {
   1088 	HistEvent ev;
   1089 
   1090 	if (h == NULL || e == NULL)
   1091 		rl_initialize();
   1092 	return (history(h, &ev, H_LOAD, filename));
   1093 }
   1094 
   1095 
   1096 /*
   1097  * write history to a file given
   1098  */
   1099 int
   1100 write_history(const char *filename)
   1101 {
   1102 	HistEvent ev;
   1103 
   1104 	if (h == NULL || e == NULL)
   1105 		rl_initialize();
   1106 	return (history(h, &ev, H_SAVE, filename));
   1107 }
   1108 
   1109 
   1110 /*
   1111  * returns history ``num''th event
   1112  *
   1113  * returned pointer points to static variable
   1114  */
   1115 HIST_ENTRY *
   1116 history_get(int num)
   1117 {
   1118 	static HIST_ENTRY she;
   1119 	HistEvent ev;
   1120 	int curr_num;
   1121 
   1122 	if (h == NULL || e == NULL)
   1123 		rl_initialize();
   1124 
   1125 	/* save current position */
   1126 	if (history(h, &ev, H_CURR) != 0)
   1127 		return (NULL);
   1128 	curr_num = ev.num;
   1129 
   1130 	/* start from most recent */
   1131 	if (history(h, &ev, H_FIRST) != 0)
   1132 		return (NULL);	/* error */
   1133 
   1134 	/* look backwards for event matching specified offset */
   1135 	if (history(h, &ev, H_NEXT_EVENT, num))
   1136 		return (NULL);
   1137 
   1138 	she.line = ev.str;
   1139 	she.data = NULL;
   1140 
   1141 	/* restore pointer to where it was */
   1142 	(void)history(h, &ev, H_SET, curr_num);
   1143 
   1144 	return (&she);
   1145 }
   1146 
   1147 
   1148 /*
   1149  * add the line to history table
   1150  */
   1151 int
   1152 add_history(const char *line)
   1153 {
   1154 	HistEvent ev;
   1155 
   1156 	if (h == NULL || e == NULL)
   1157 		rl_initialize();
   1158 
   1159 	(void)history(h, &ev, H_ENTER, line);
   1160 	if (history(h, &ev, H_GETSIZE) == 0)
   1161 		history_length = ev.num;
   1162 
   1163 	return (!(history_length > 0)); /* return 0 if all is okay */
   1164 }
   1165 
   1166 
   1167 /*
   1168  * clear the history list - delete all entries
   1169  */
   1170 void
   1171 clear_history(void)
   1172 {
   1173 	HistEvent ev;
   1174 
   1175 	history(h, &ev, H_CLEAR);
   1176 }
   1177 
   1178 
   1179 /*
   1180  * returns offset of the current history event
   1181  */
   1182 int
   1183 where_history(void)
   1184 {
   1185 	HistEvent ev;
   1186 	int curr_num, off;
   1187 
   1188 	if (history(h, &ev, H_CURR) != 0)
   1189 		return (0);
   1190 	curr_num = ev.num;
   1191 
   1192 	history(h, &ev, H_FIRST);
   1193 	off = 1;
   1194 	while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
   1195 		off++;
   1196 
   1197 	return (off);
   1198 }
   1199 
   1200 
   1201 /*
   1202  * returns current history event or NULL if there is no such event
   1203  */
   1204 HIST_ENTRY *
   1205 current_history(void)
   1206 {
   1207 
   1208 	return (_move_history(H_CURR));
   1209 }
   1210 
   1211 
   1212 /*
   1213  * returns total number of bytes history events' data are using
   1214  */
   1215 int
   1216 history_total_bytes(void)
   1217 {
   1218 	HistEvent ev;
   1219 	int curr_num, size;
   1220 
   1221 	if (history(h, &ev, H_CURR) != 0)
   1222 		return (-1);
   1223 	curr_num = ev.num;
   1224 
   1225 	history(h, &ev, H_FIRST);
   1226 	size = 0;
   1227 	do
   1228 		size += strlen(ev.str);
   1229 	while (history(h, &ev, H_NEXT) == 0);
   1230 
   1231 	/* get to the same position as before */
   1232 	history(h, &ev, H_PREV_EVENT, curr_num);
   1233 
   1234 	return (size);
   1235 }
   1236 
   1237 
   1238 /*
   1239  * sets the position in the history list to ``pos''
   1240  */
   1241 int
   1242 history_set_pos(int pos)
   1243 {
   1244 	HistEvent ev;
   1245 	int curr_num;
   1246 
   1247 	if (pos > history_length || pos < 0)
   1248 		return (-1);
   1249 
   1250 	history(h, &ev, H_CURR);
   1251 	curr_num = ev.num;
   1252 
   1253 	if (history(h, &ev, H_SET, pos)) {
   1254 		history(h, &ev, H_SET, curr_num);
   1255 		return(-1);
   1256 	}
   1257 	return (0);
   1258 }
   1259 
   1260 
   1261 /*
   1262  * returns previous event in history and shifts pointer accordingly
   1263  */
   1264 HIST_ENTRY *
   1265 previous_history(void)
   1266 {
   1267 
   1268 	return (_move_history(H_PREV));
   1269 }
   1270 
   1271 
   1272 /*
   1273  * returns next event in history and shifts pointer accordingly
   1274  */
   1275 HIST_ENTRY *
   1276 next_history(void)
   1277 {
   1278 
   1279 	return (_move_history(H_NEXT));
   1280 }
   1281 
   1282 
   1283 /*
   1284  * searches for first history event containing the str
   1285  */
   1286 int
   1287 history_search(const char *str, int direction)
   1288 {
   1289 	HistEvent ev;
   1290 	const char *strp;
   1291 	int curr_num;
   1292 
   1293 	if (history(h, &ev, H_CURR) != 0)
   1294 		return (-1);
   1295 	curr_num = ev.num;
   1296 
   1297 	for (;;) {
   1298 		if ((strp = strstr(ev.str, str)) != NULL)
   1299 			return (int) (strp - ev.str);
   1300 		if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
   1301 			break;
   1302 	}
   1303 	history(h, &ev, H_SET, curr_num);
   1304 	return (-1);
   1305 }
   1306 
   1307 
   1308 /*
   1309  * searches for first history event beginning with str
   1310  */
   1311 int
   1312 history_search_prefix(const char *str, int direction)
   1313 {
   1314 	HistEvent ev;
   1315 
   1316 	return (history(h, &ev, direction < 0? H_PREV_STR:H_NEXT_STR, str));
   1317 }
   1318 
   1319 
   1320 /*
   1321  * search for event in history containing str, starting at offset
   1322  * abs(pos); continue backward, if pos<0, forward otherwise
   1323  */
   1324 /* ARGSUSED */
   1325 int
   1326 history_search_pos(const char *str,
   1327 		   int direction __attribute__((__unused__)), int pos)
   1328 {
   1329 	HistEvent ev;
   1330 	int curr_num, off;
   1331 
   1332 	off = (pos > 0) ? pos : -pos;
   1333 	pos = (pos > 0) ? 1 : -1;
   1334 
   1335 	if (history(h, &ev, H_CURR) != 0)
   1336 		return (-1);
   1337 	curr_num = ev.num;
   1338 
   1339 	if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
   1340 		return (-1);
   1341 
   1342 
   1343 	for (;;) {
   1344 		if (strstr(ev.str, str))
   1345 			return (off);
   1346 		if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
   1347 			break;
   1348 	}
   1349 
   1350 	/* set "current" pointer back to previous state */
   1351 	history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
   1352 
   1353 	return (-1);
   1354 }
   1355 
   1356 
   1357 /********************************/
   1358 /* completion functions */
   1359 
   1360 /*
   1361  * does tilde expansion of strings of type ``~user/foo''
   1362  * if ``user'' isn't valid user name or ``txt'' doesn't start
   1363  * w/ '~', returns pointer to strdup()ed copy of ``txt''
   1364  *
   1365  * it's callers's responsibility to free() returned string
   1366  */
   1367 char *
   1368 tilde_expand(char *txt)
   1369 {
   1370 	struct passwd *pass;
   1371 	char *temp;
   1372 	size_t len = 0;
   1373 
   1374 	if (txt[0] != '~')
   1375 		return (strdup(txt));
   1376 
   1377 	temp = strchr(txt + 1, '/');
   1378 	if (temp == NULL) {
   1379 		temp = strdup(txt + 1);
   1380 		if (temp == NULL)
   1381 			return NULL;
   1382 	} else {
   1383 		len = temp - txt + 1;	/* text until string after slash */
   1384 		temp = malloc(len);
   1385 		if (temp == NULL)
   1386 			return NULL;
   1387 		(void)strncpy(temp, txt + 1, len - 2);
   1388 		temp[len - 2] = '\0';
   1389 	}
   1390 	pass = getpwnam(temp);
   1391 	free(temp);		/* value no more needed */
   1392 	if (pass == NULL)
   1393 		return (strdup(txt));
   1394 
   1395 	/* update pointer txt to point at string immedially following */
   1396 	/* first slash */
   1397 	txt += len;
   1398 
   1399 	temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
   1400 	if (temp == NULL)
   1401 		return NULL;
   1402 	(void)sprintf(temp, "%s/%s", pass->pw_dir, txt);
   1403 
   1404 	return (temp);
   1405 }
   1406 
   1407 
   1408 /*
   1409  * return first found file name starting by the ``text'' or NULL if no
   1410  * such file can be found
   1411  * value of ``state'' is ignored
   1412  *
   1413  * it's caller's responsibility to free returned string
   1414  */
   1415 char *
   1416 filename_completion_function(const char *text, int state)
   1417 {
   1418 	static DIR *dir = NULL;
   1419 	static char *filename = NULL, *dirname = NULL;
   1420 	static size_t filename_len = 0;
   1421 	struct dirent *entry;
   1422 	char *temp;
   1423 	size_t len;
   1424 
   1425 	if (state == 0 || dir == NULL) {
   1426 		temp = strrchr(text, '/');
   1427 		if (temp) {
   1428 			char *nptr;
   1429 			temp++;
   1430 			nptr = realloc(filename, strlen(temp) + 1);
   1431 			if (nptr == NULL) {
   1432 				free(filename);
   1433 				return NULL;
   1434 			}
   1435 			filename = nptr;
   1436 			(void)strcpy(filename, temp);
   1437 			len = temp - text;	/* including last slash */
   1438 			nptr = realloc(dirname, len + 1);
   1439 			if (nptr == NULL) {
   1440 				free(filename);
   1441 				return NULL;
   1442 			}
   1443 			dirname = nptr;
   1444 			(void)strncpy(dirname, text, len);
   1445 			dirname[len] = '\0';
   1446 		} else {
   1447 			filename = strdup(text);
   1448 			if (filename == NULL)
   1449 				return NULL;
   1450 			dirname = NULL;
   1451 		}
   1452 
   1453 		/* support for ``~user'' syntax */
   1454 		if (dirname && *dirname == '~') {
   1455 			char *nptr;
   1456 			temp = tilde_expand(dirname);
   1457 			if (temp == NULL)
   1458 				return NULL;
   1459 			nptr = realloc(dirname, strlen(temp) + 1);
   1460 			if (nptr == NULL) {
   1461 				free(dirname);
   1462 				return NULL;
   1463 			}
   1464 			dirname = nptr;
   1465 			(void)strcpy(dirname, temp);	/* safe */
   1466 			free(temp);	/* no longer needed */
   1467 		}
   1468 		/* will be used in cycle */
   1469 		filename_len = strlen(filename);
   1470 		if (filename_len == 0)
   1471 			return (NULL);	/* no expansion possible */
   1472 
   1473 		if (dir != NULL) {
   1474 			(void)closedir(dir);
   1475 			dir = NULL;
   1476 		}
   1477 		dir = opendir(dirname ? dirname : ".");
   1478 		if (!dir)
   1479 			return (NULL);	/* cannot open the directory */
   1480 	}
   1481 	/* find the match */
   1482 	while ((entry = readdir(dir)) != NULL) {
   1483 		/* otherwise, get first entry where first */
   1484 		/* filename_len characters are equal	  */
   1485 		if (entry->d_name[0] == filename[0]
   1486 #if defined(__SVR4) || defined(__linux__)
   1487 		    && strlen(entry->d_name) >= filename_len
   1488 #else
   1489 		    && entry->d_namlen >= filename_len
   1490 #endif
   1491 		    && strncmp(entry->d_name, filename,
   1492 			filename_len) == 0)
   1493 			break;
   1494 	}
   1495 
   1496 	if (entry) {		/* match found */
   1497 
   1498 		struct stat stbuf;
   1499 #if defined(__SVR4) || defined(__linux__)
   1500 		len = strlen(entry->d_name) +
   1501 #else
   1502 		len = entry->d_namlen +
   1503 #endif
   1504 		    ((dirname) ? strlen(dirname) : 0) + 1 + 1;
   1505 		temp = malloc(len);
   1506 		if (temp == NULL)
   1507 			return NULL;
   1508 		(void)sprintf(temp, "%s%s",
   1509 		    dirname ? dirname : "", entry->d_name);	/* safe */
   1510 
   1511 		/* test, if it's directory */
   1512 		if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
   1513 			strcat(temp, "/");	/* safe */
   1514 	} else {
   1515 		(void)closedir(dir);
   1516 		dir = NULL;
   1517 		temp = NULL;
   1518 	}
   1519 
   1520 	return (temp);
   1521 }
   1522 
   1523 
   1524 /*
   1525  * a completion generator for usernames; returns _first_ username
   1526  * which starts with supplied text
   1527  * text contains a partial username preceded by random character
   1528  * (usually '~'); state is ignored
   1529  * it's callers responsibility to free returned value
   1530  */
   1531 char *
   1532 username_completion_function(const char *text, int state)
   1533 {
   1534 	struct passwd *pwd;
   1535 
   1536 	if (text[0] == '\0')
   1537 		return (NULL);
   1538 
   1539 	if (*text == '~')
   1540 		text++;
   1541 
   1542 	if (state == 0)
   1543 		setpwent();
   1544 
   1545 	while ((pwd = getpwent()) && text[0] == pwd->pw_name[0]
   1546 	    && strcmp(text, pwd->pw_name) == 0);
   1547 
   1548 	if (pwd == NULL) {
   1549 		endpwent();
   1550 		return (NULL);
   1551 	}
   1552 	return (strdup(pwd->pw_name));
   1553 }
   1554 
   1555 
   1556 /*
   1557  * el-compatible wrapper around rl_complete; needed for key binding
   1558  */
   1559 /* ARGSUSED */
   1560 static unsigned char
   1561 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
   1562 {
   1563 	return (unsigned char) rl_complete(0, ch);
   1564 }
   1565 
   1566 
   1567 /*
   1568  * returns list of completions for text given
   1569  */
   1570 char **
   1571 completion_matches(const char *text, CPFunction *genfunc)
   1572 {
   1573 	char **match_list = NULL, *retstr, *prevstr;
   1574 	size_t match_list_len, max_equal, which, i;
   1575 	size_t matches;
   1576 
   1577 	if (h == NULL || e == NULL)
   1578 		rl_initialize();
   1579 
   1580 	matches = 0;
   1581 	match_list_len = 1;
   1582 	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
   1583 		/* allow for list terminator here */
   1584 		if (matches + 3 >= match_list_len) {
   1585 			char **nmatch_list;
   1586 			while (matches + 3 >= match_list_len)
   1587 				match_list_len <<= 1;
   1588 			nmatch_list = realloc(match_list,
   1589 			    match_list_len * sizeof(char *));
   1590 			if (nmatch_list == NULL) {
   1591 				free(match_list);
   1592 				return NULL;
   1593 			}
   1594 			match_list = nmatch_list;
   1595 
   1596 		}
   1597 		match_list[++matches] = retstr;
   1598 	}
   1599 
   1600 	if (!match_list)
   1601 		return NULL;	/* nothing found */
   1602 
   1603 	/* find least denominator and insert it to match_list[0] */
   1604 	which = 2;
   1605 	prevstr = match_list[1];
   1606 	max_equal = strlen(prevstr);
   1607 	for (; which <= matches; which++) {
   1608 		for (i = 0; i < max_equal &&
   1609 		    prevstr[i] == match_list[which][i]; i++)
   1610 			continue;
   1611 		max_equal = i;
   1612 	}
   1613 
   1614 	retstr = malloc(max_equal + 1);
   1615 	if (retstr == NULL) {
   1616 		free(match_list);
   1617 		return NULL;
   1618 	}
   1619 	(void)strncpy(retstr, match_list[1], max_equal);
   1620 	retstr[max_equal] = '\0';
   1621 	match_list[0] = retstr;
   1622 
   1623 	/* add NULL as last pointer to the array */
   1624 	match_list[matches + 1] = (char *) NULL;
   1625 
   1626 	return (match_list);
   1627 }
   1628 
   1629 /*
   1630  * Sort function for qsort(). Just wrapper around strcasecmp().
   1631  */
   1632 static int
   1633 _rl_qsort_string_compare(i1, i2)
   1634 	const void *i1, *i2;
   1635 {
   1636 	const char *s1 = ((const char * const *)i1)[0];
   1637 	const char *s2 = ((const char * const *)i2)[0];
   1638 
   1639 	return strcasecmp(s1, s2);
   1640 }
   1641 
   1642 /*
   1643  * Display list of strings in columnar format on readline's output stream.
   1644  * 'matches' is list of strings, 'len' is number of strings in 'matches',
   1645  * 'max' is maximum length of string in 'matches'.
   1646  */
   1647 void
   1648 rl_display_match_list (matches, len, max)
   1649      char **matches;
   1650      int len, max;
   1651 {
   1652 	int i, idx, limit, count;
   1653 	int screenwidth = e->el_term.t_size.h;
   1654 
   1655 	/*
   1656 	 * Find out how many entries can be put on one line, count
   1657 	 * with two spaces between strings.
   1658 	 */
   1659 	limit = screenwidth / (max + 2);
   1660 	if (limit == 0)
   1661 		limit = 1;
   1662 
   1663 	/* how many lines of output */
   1664 	count = len / limit;
   1665 	if (count * limit < len)
   1666 		count++;
   1667 
   1668 	/* Sort the items if they are not already sorted. */
   1669 	qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
   1670 	    _rl_qsort_string_compare);
   1671 
   1672 	idx = 1;
   1673 	for(; count > 0; count--) {
   1674 		for(i = 0; i < limit && matches[idx]; i++, idx++)
   1675 			(void)fprintf(e->el_outfile, "%-*s  ", max,
   1676 			    matches[idx]);
   1677 		(void)fprintf(e->el_outfile, "\n");
   1678 	}
   1679 }
   1680 
   1681 /*
   1682  * Complete the word at or before point, called by rl_complete()
   1683  * 'what_to_do' says what to do with the completion.
   1684  * `?' means list the possible completions.
   1685  * TAB means do standard completion.
   1686  * `*' means insert all of the possible completions.
   1687  * `!' means to do standard completion, and list all possible completions if
   1688  * there is more than one.
   1689  *
   1690  * Note: '*' support is not implemented
   1691  */
   1692 static int
   1693 rl_complete_internal(int what_to_do)
   1694 {
   1695 	Function *complet_func;
   1696 	const LineInfo *li;
   1697 	char *temp, **matches;
   1698 	const char *ctemp;
   1699 	size_t len;
   1700 
   1701 	rl_completion_type = what_to_do;
   1702 
   1703 	if (h == NULL || e == NULL)
   1704 		rl_initialize();
   1705 
   1706 	complet_func = rl_completion_entry_function;
   1707 	if (!complet_func)
   1708 		complet_func = (Function *)(void *)filename_completion_function;
   1709 
   1710 	/* We now look backwards for the start of a filename/variable word */
   1711 	li = el_line(e);
   1712 	ctemp = (const char *) li->cursor;
   1713 	while (ctemp > li->buffer
   1714 	    && !strchr(rl_basic_word_break_characters, ctemp[-1])
   1715 	    && (!rl_special_prefixes
   1716 		|| !strchr(rl_special_prefixes, ctemp[-1]) ) )
   1717 		ctemp--;
   1718 
   1719 	len = li->cursor - ctemp;
   1720 	temp = alloca(len + 1);
   1721 	(void)strncpy(temp, ctemp, len);
   1722 	temp[len] = '\0';
   1723 
   1724 	/* these can be used by function called in completion_matches() */
   1725 	/* or (*rl_attempted_completion_function)() */
   1726 	rl_point = li->cursor - li->buffer;
   1727 	rl_end = li->lastchar - li->buffer;
   1728 
   1729 	if (!rl_attempted_completion_function)
   1730 		matches = completion_matches(temp, (CPFunction *)complet_func);
   1731 	else {
   1732 		int end = li->cursor - li->buffer;
   1733 		matches = (*rl_attempted_completion_function) (temp, (int)
   1734 		    (end - len), end);
   1735 	}
   1736 
   1737 	if (matches) {
   1738 		int i, retval = CC_REFRESH;
   1739 		int matches_num, maxlen, match_len, match_display=1;
   1740 
   1741 		/*
   1742 		 * Only replace the completed string with common part of
   1743 		 * possible matches if there is possible completion.
   1744 		 */
   1745 		if (matches[0][0] != '\0') {
   1746 			el_deletestr(e, (int) len);
   1747 			el_insertstr(e, matches[0]);
   1748 		}
   1749 
   1750 		if (what_to_do == '?')
   1751 			goto display_matches;
   1752 
   1753 		if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
   1754 			/*
   1755 			 * We found exact match. Add a space after
   1756 			 * it, unless we do filename completion and the
   1757 			 * object is a directory.
   1758 			 */
   1759 			size_t alen = strlen(matches[0]);
   1760 			if ((complet_func !=
   1761 			    (Function *)filename_completion_function
   1762 			      || (alen > 0 && (matches[0])[alen - 1] != '/'))
   1763 			    && rl_completion_append_character) {
   1764 				char buf[2];
   1765 				buf[0] = rl_completion_append_character;
   1766 				buf[1] = '\0';
   1767 				el_insertstr(e, buf);
   1768 			}
   1769 		} else if (what_to_do == '!') {
   1770     display_matches:
   1771 			/*
   1772 			 * More than one match and requested to list possible
   1773 			 * matches.
   1774 			 */
   1775 
   1776 			for(i=1, maxlen=0; matches[i]; i++) {
   1777 				match_len = strlen(matches[i]);
   1778 				if (match_len > maxlen)
   1779 					maxlen = match_len;
   1780 			}
   1781 			matches_num = i - 1;
   1782 
   1783 			/* newline to get on next line from command line */
   1784 			(void)fprintf(e->el_outfile, "\n");
   1785 
   1786 			/*
   1787 			 * If there are too many items, ask user for display
   1788 			 * confirmation.
   1789 			 */
   1790 			if (matches_num > rl_completion_query_items) {
   1791 				(void)fprintf(e->el_outfile,
   1792 				    "Display all %d possibilities? (y or n) ",
   1793 				    matches_num);
   1794 				(void)fflush(e->el_outfile);
   1795 				if (getc(stdin) != 'y')
   1796 					match_display = 0;
   1797 				(void)fprintf(e->el_outfile, "\n");
   1798 			}
   1799 
   1800 			if (match_display)
   1801 				rl_display_match_list(matches, matches_num,
   1802 					maxlen);
   1803 			retval = CC_REDISPLAY;
   1804 		} else if (matches[0][0]) {
   1805 			/*
   1806 			 * There was some common match, but the name was
   1807 			 * not complete enough. Next tab will print possible
   1808 			 * completions.
   1809 			 */
   1810 			el_beep(e);
   1811 		} else {
   1812 			/* lcd is not a valid object - further specification */
   1813 			/* is needed */
   1814 			el_beep(e);
   1815 			retval = CC_NORM;
   1816 		}
   1817 
   1818 		/* free elements of array and the array itself */
   1819 		for (i = 0; matches[i]; i++)
   1820 			free(matches[i]);
   1821 		free(matches), matches = NULL;
   1822 
   1823 		return (retval);
   1824 	}
   1825 	return (CC_NORM);
   1826 }
   1827 
   1828 
   1829 /*
   1830  * complete word at current point
   1831  */
   1832 int
   1833 rl_complete(int ignore, int invoking_key)
   1834 {
   1835 	if (h == NULL || e == NULL)
   1836 		rl_initialize();
   1837 
   1838 	if (rl_inhibit_completion) {
   1839 		rl_insert(ignore, invoking_key);
   1840 		return (CC_REFRESH);
   1841 	} else if (e->el_state.lastcmd == el_rl_complete_cmdnum)
   1842 		return rl_complete_internal('?');
   1843 	else if (_rl_complete_show_all)
   1844 		return rl_complete_internal('!');
   1845 	else
   1846 		return (rl_complete_internal(TAB));
   1847 }
   1848 
   1849 
   1850 /*
   1851  * misc other functions
   1852  */
   1853 
   1854 /*
   1855  * bind key c to readline-type function func
   1856  */
   1857 int
   1858 rl_bind_key(int c, int func(int, int))
   1859 {
   1860 	int retval = -1;
   1861 
   1862 	if (h == NULL || e == NULL)
   1863 		rl_initialize();
   1864 
   1865 	if (func == rl_insert) {
   1866 		/* XXX notice there is no range checking of ``c'' */
   1867 		e->el_map.key[c] = ED_INSERT;
   1868 		retval = 0;
   1869 	}
   1870 	return (retval);
   1871 }
   1872 
   1873 
   1874 /*
   1875  * read one key from input - handles chars pushed back
   1876  * to input stream also
   1877  */
   1878 int
   1879 rl_read_key(void)
   1880 {
   1881 	char fooarr[2 * sizeof(int)];
   1882 
   1883 	if (e == NULL || h == NULL)
   1884 		rl_initialize();
   1885 
   1886 	return (el_getc(e, fooarr));
   1887 }
   1888 
   1889 
   1890 /*
   1891  * reset the terminal
   1892  */
   1893 /* ARGSUSED */
   1894 void
   1895 rl_reset_terminal(const char *p __attribute__((__unused__)))
   1896 {
   1897 
   1898 	if (h == NULL || e == NULL)
   1899 		rl_initialize();
   1900 	el_reset(e);
   1901 }
   1902 
   1903 
   1904 /*
   1905  * insert character ``c'' back into input stream, ``count'' times
   1906  */
   1907 int
   1908 rl_insert(int count, int c)
   1909 {
   1910 	char arr[2];
   1911 
   1912 	if (h == NULL || e == NULL)
   1913 		rl_initialize();
   1914 
   1915 	/* XXX - int -> char conversion can lose on multichars */
   1916 	arr[0] = c;
   1917 	arr[1] = '\0';
   1918 
   1919 	for (; count > 0; count--)
   1920 		el_push(e, arr);
   1921 
   1922 	return (0);
   1923 }
   1924 
   1925 /*ARGSUSED*/
   1926 int
   1927 rl_newline(int count, int c)
   1928 {
   1929 	/*
   1930 	 * Readline-4.0 appears to ignore the args.
   1931 	 */
   1932 	return rl_insert(1, '\n');
   1933 }
   1934 
   1935 /*ARGSUSED*/
   1936 static unsigned char
   1937 rl_bind_wrapper(EditLine *el, unsigned char c)
   1938 {
   1939 	if (map[c] == NULL)
   1940 	    return CC_ERROR;
   1941 	(*map[c])(NULL, c);
   1942 
   1943 	/* If rl_done was set by the above call, deal with it here */
   1944 	if (rl_done)
   1945 		return CC_EOF;
   1946 
   1947 	return CC_NORM;
   1948 }
   1949 
   1950 int
   1951 rl_add_defun(const char *name, Function *fun, int c)
   1952 {
   1953 	char dest[8];
   1954 	if (c >= sizeof(map) / sizeof(map[0]) || c < 0)
   1955 		return -1;
   1956 	map[(unsigned char)c] = fun;
   1957 	el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
   1958 	vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
   1959 	el_set(e, EL_BIND, dest, name);
   1960 	return 0;
   1961 }
   1962 
   1963 void
   1964 rl_callback_read_char()
   1965 {
   1966 	int count = 0, done = 0;
   1967 	const char *buf = el_gets(e, &count);
   1968 	char *wbuf;
   1969 
   1970 	if (buf == NULL || count-- <= 0)
   1971 		return;
   1972 	if (count == 0 && buf[0] == CTRL('d'))
   1973 		done = 1;
   1974 	if (buf[count] == '\n' || buf[count] == '\r')
   1975 		done = 2;
   1976 
   1977 	if (done && rl_linefunc != NULL) {
   1978 		el_set(e, EL_UNBUFFERED, 0);
   1979 		if (done == 2) {
   1980 		    if ((wbuf = strdup(buf)) != NULL)
   1981 			wbuf[count] = '\0';
   1982 		} else
   1983 			wbuf = NULL;
   1984 		(*(void (*)(const char *))rl_linefunc)(wbuf);
   1985 	}
   1986 }
   1987 
   1988 void
   1989 rl_callback_handler_install (const char *prompt, VFunction *linefunc)
   1990 {
   1991 	if (e == NULL) {
   1992 		rl_initialize();
   1993 	}
   1994 	if (rl_prompt)
   1995 		free(rl_prompt);
   1996 	rl_prompt = prompt ? strdup(strchr(prompt, *prompt)) : NULL;
   1997 	rl_linefunc = linefunc;
   1998 	el_set(e, EL_UNBUFFERED, 1);
   1999 }
   2000 
   2001 void
   2002 rl_callback_handler_remove(void)
   2003 {
   2004 	el_set(e, EL_UNBUFFERED, 0);
   2005 }
   2006 
   2007 void
   2008 rl_redisplay(void)
   2009 {
   2010 	char a[2];
   2011 	a[0] = CTRL('r');
   2012 	a[1] = '\0';
   2013 	el_push(e, a);
   2014 }
   2015 
   2016 int
   2017 rl_get_previous_history(int count, int key)
   2018 {
   2019 	char a[2];
   2020 	a[0] = key;
   2021 	a[1] = '\0';
   2022 	while (count--)
   2023 		el_push(e, a);
   2024 	return 0;
   2025 }
   2026 
   2027 void
   2028 /*ARGSUSED*/
   2029 rl_prep_terminal(int meta_flag)
   2030 {
   2031 	el_set(e, EL_PREP_TERM, 1);
   2032 }
   2033 
   2034 void
   2035 rl_deprep_terminal()
   2036 {
   2037 	el_set(e, EL_PREP_TERM, 0);
   2038 }
   2039 
   2040 int
   2041 rl_read_init_file(const char *s)
   2042 {
   2043 	return(el_source(e, s));
   2044 }
   2045 
   2046 int
   2047 rl_parse_and_bind(const char *line)
   2048 {
   2049 	const char **argv;
   2050 	int argc;
   2051 	Tokenizer *tok;
   2052 
   2053 	tok = tok_init(NULL);
   2054 	tok_line(tok, line, &argc, &argv);
   2055 	argc = el_parse(e, argc, argv);
   2056 	tok_end(tok);
   2057 	return (argc ? 1 : 0);
   2058 }
   2059 
   2060 void
   2061 rl_stuff_char(int c)
   2062 {
   2063 	char buf[2];
   2064 
   2065 	buf[0] = c;
   2066 	buf[1] = '\0';
   2067 	el_insertstr(e, buf);
   2068 }
   2069 
   2070 static int
   2071 _rl_event_read_char(EditLine *el, char *cp)
   2072 {
   2073 	int	n, num_read;
   2074 
   2075 	*cp = 0;
   2076 	while (rl_event_hook) {
   2077 
   2078 		(*rl_event_hook)();
   2079 
   2080 #if defined(FIONREAD)
   2081 		if (ioctl(el->el_infd, FIONREAD, &n) < 0)
   2082 			return(-1);
   2083 		if (n)
   2084 			num_read = read(el->el_infd, cp, 1);
   2085 		else
   2086 			num_read = 0;
   2087 #elif defined(F_SETFL) && defined(O_NDELAY)
   2088 		if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
   2089 			return(-1);
   2090 		if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
   2091 			return(-1);
   2092 		num_read = read(el->el_infd, cp, 1);
   2093 		if (fcntl(el->el_infd, F_SETFL, n))
   2094 			return(-1);
   2095 #else
   2096 		/* not non-blocking, but what you gonna do? */
   2097 		num_read = read(el->el_infd, cp, 1);
   2098 		return(-1);
   2099 #endif
   2100 
   2101 		if (num_read < 0 && errno == EAGAIN)
   2102 			continue;
   2103 		if (num_read == 0)
   2104 			continue;
   2105 		break;
   2106 	}
   2107 	if (!rl_event_hook)
   2108 		el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
   2109 	return(num_read);
   2110 }
   2111