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