xref: /netbsd-src/lib/libedit/readline.c (revision d20841bb642898112fe68f0ad3f7b26dddf56f07)
1 /*	$NetBSD: readline.c,v 1.45 2004/01/17 17:57:40 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.45 2004/01/17 17:57:40 christos Exp $");
42 #endif /* not lint && not SCCSID */
43 
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <stdio.h>
47 #include <dirent.h>
48 #include <string.h>
49 #include <pwd.h>
50 #include <ctype.h>
51 #include <stdlib.h>
52 #include <unistd.h>
53 #include <limits.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #ifdef HAVE_VIS_H
57 #include <vis.h>
58 #else
59 #include "np/vis.h"
60 #endif
61 #ifdef HAVE_ALLOCA_H
62 #include <alloca.h>
63 #endif
64 #include "el.h"
65 #include "fcns.h"		/* for EL_NUM_FCNS */
66 #include "histedit.h"
67 #include "readline/readline.h"
68 
69 /* for rl_complete() */
70 #define TAB		'\r'
71 
72 /* see comment at the #ifdef for sense of this */
73 /* #define GDB_411_HACK */
74 
75 /* readline compatibility stuff - look at readline sources/documentation */
76 /* to see what these variables mean */
77 const char *rl_library_version = "EditLine wrapper";
78 static char empty[] = { '\0' };
79 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
80 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
81     '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
82 char *rl_readline_name = empty;
83 FILE *rl_instream = NULL;
84 FILE *rl_outstream = NULL;
85 int rl_point = 0;
86 int rl_end = 0;
87 char *rl_line_buffer = NULL;
88 VFunction *rl_linefunc = NULL;
89 int rl_done = 0;
90 VFunction *rl_event_hook = NULL;
91 
92 int history_base = 1;		/* probably never subject to change */
93 int history_length = 0;
94 int max_input_history = 0;
95 char history_expansion_char = '!';
96 char history_subst_char = '^';
97 char *history_no_expand_chars = expand_chars;
98 Function *history_inhibit_expansion_function = NULL;
99 char *history_arg_extract(int start, int end, const char *str);
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_expand_command(const char *, size_t, size_t,
167     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 = NULL;
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 	const	char	*s;
395 	char	*r, *result;
396 	size_t	len, with_len, what_len;
397 
398 	len = strlen(str);
399 	with_len = strlen(with);
400 	what_len = strlen(what);
401 
402 	/* calculate length we need for result */
403 	s = str;
404 	while (*s) {
405 		if (*s == *what && !strncmp(s, what, what_len)) {
406 			len += with_len - what_len;
407 			if (!globally)
408 				break;
409 			s += what_len;
410 		} else
411 			s++;
412 	}
413 	r = result = malloc(len + 1);
414 	if (result == NULL)
415 		return NULL;
416 	s = str;
417 	while (*s) {
418 		if (*s == *what && !strncmp(s, what, what_len)) {
419 			(void)strncpy(r, with, with_len);
420 			r += with_len;
421 			s += what_len;
422 			if (!globally) {
423 				(void)strcpy(r, s);
424 				return(result);
425 			}
426 		} else
427 			*r++ = *s++;
428 	}
429 	*r = 0;
430 	return(result);
431 }
432 
433 static	char	*last_search_pat;	/* last !?pat[?] search pattern */
434 static	char	*last_search_match;	/* last !?pat[?] that matched */
435 
436 const char *
437 get_history_event(const char *cmd, int *cindex, int qchar)
438 {
439 	int idx, sign, sub, num, begin, ret;
440 	size_t len;
441 	char	*pat;
442 	const char *rptr;
443 	HistEvent ev;
444 
445 	idx = *cindex;
446 	if (cmd[idx++] != history_expansion_char)
447 		return(NULL);
448 
449 	/* find out which event to take */
450 	if (cmd[idx] == history_expansion_char || cmd[idx] == 0) {
451 		if (history(h, &ev, H_FIRST) != 0)
452 			return(NULL);
453 		*cindex = cmd[idx]? (idx + 1):idx;
454 		return(ev.str);
455 	}
456 	sign = 0;
457 	if (cmd[idx] == '-') {
458 		sign = 1;
459 		idx++;
460 	}
461 
462 	if ('0' <= cmd[idx] && cmd[idx] <= '9') {
463 		HIST_ENTRY *rl_he;
464 
465 		num = 0;
466 		while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
467 			num = num * 10 + cmd[idx] - '0';
468 			idx++;
469 		}
470 		if (sign)
471 			num = history_length - num + 1;
472 
473 		if (!(rl_he = history_get(num)))
474 			return(NULL);
475 
476 		*cindex = idx;
477 		return(rl_he->line);
478 	}
479 	sub = 0;
480 	if (cmd[idx] == '?') {
481 		sub = 1;
482 		idx++;
483 	}
484 	begin = idx;
485 	while (cmd[idx]) {
486 		if (cmd[idx] == '\n')
487 			break;
488 		if (sub && cmd[idx] == '?')
489 			break;
490 		if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
491 				    || cmd[idx] == '\t' || cmd[idx] == qchar))
492 			break;
493 		idx++;
494 	}
495 	len = idx - begin;
496 	if (sub && cmd[idx] == '?')
497 		idx++;
498 	if (sub && len == 0 && last_search_pat && *last_search_pat)
499 		pat = last_search_pat;
500 	else if (len == 0)
501 		return(NULL);
502 	else {
503 		if ((pat = malloc(len + 1)) == NULL)
504 			return NULL;
505 		(void)strncpy(pat, cmd + begin, len);
506 		pat[len] = '\0';
507 	}
508 
509 	if (history(h, &ev, H_CURR) != 0) {
510 		if (pat != last_search_pat)
511 			free(pat);
512 		return (NULL);
513 	}
514 	num = ev.num;
515 
516 	if (sub) {
517 		if (pat != last_search_pat) {
518 			if (last_search_pat)
519 				free(last_search_pat);
520 			last_search_pat = pat;
521 		}
522 		ret = history_search(pat, -1);
523 	} else
524 		ret = history_search_prefix(pat, -1);
525 
526 	if (ret == -1) {
527 		/* restore to end of list on failed search */
528 		history(h, &ev, H_FIRST);
529 		(void)fprintf(rl_outstream, "%s: Event not found\n", pat);
530 		if (pat != last_search_pat)
531 			free(pat);
532 		return(NULL);
533 	}
534 
535 	if (sub && len) {
536 		if (last_search_match && last_search_match != pat)
537 			free(last_search_match);
538 		last_search_match = pat;
539 	}
540 
541 	if (pat != last_search_pat)
542 		free(pat);
543 
544 	if (history(h, &ev, H_CURR) != 0)
545 		return(NULL);
546 	*cindex = idx;
547 	rptr = ev.str;
548 
549 	/* roll back to original position */
550 	(void)history(h, &ev, H_SET, num);
551 
552 	return rptr;
553 }
554 
555 /*
556  * the real function doing history expansion - takes as argument command
557  * to do and data upon which the command should be executed
558  * does expansion the way I've understood readline documentation
559  *
560  * returns 0 if data was not modified, 1 if it was and 2 if the string
561  * should be only printed and not executed; in case of error,
562  * returns -1 and *result points to NULL
563  * it's callers responsibility to free() string returned in *result
564  */
565 static int
566 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
567     char **result)
568 {
569 	char *tmp, *search = NULL, *aptr;
570 	const char *ptr, *cmd;
571 	static char *from = NULL, *to = NULL;
572 	int start, end, idx, has_mods = 0;
573 	int p_on = 0, g_on = 0;
574 
575 	*result = NULL;
576 	aptr = NULL;
577 	ptr = 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 			if (*text == 0)
1448 				filename = NULL;
1449 			else {
1450 				filename = strdup(text);
1451 				if (filename == NULL)
1452 					return NULL;
1453 			}
1454 			dirname = NULL;
1455 		}
1456 
1457 		/* support for ``~user'' syntax */
1458 		if (dirname && *dirname == '~') {
1459 			char *nptr;
1460 			temp = tilde_expand(dirname);
1461 			if (temp == NULL)
1462 				return NULL;
1463 			nptr = realloc(dirname, strlen(temp) + 1);
1464 			if (nptr == NULL) {
1465 				free(dirname);
1466 				return NULL;
1467 			}
1468 			dirname = nptr;
1469 			(void)strcpy(dirname, temp);	/* safe */
1470 			free(temp);	/* no longer needed */
1471 		}
1472 		/* will be used in cycle */
1473 		filename_len = filename ? strlen(filename) : 0;
1474 
1475 		if (dir != NULL) {
1476 			(void)closedir(dir);
1477 			dir = NULL;
1478 		}
1479 		dir = opendir(dirname ? dirname : ".");
1480 		if (!dir)
1481 			return (NULL);	/* cannot open the directory */
1482 	}
1483 	/* find the match */
1484 	while ((entry = readdir(dir)) != NULL) {
1485 		/* skip . and .. */
1486 		if (entry->d_name[0] == '.' && (!entry->d_name[1]
1487 		    || (entry->d_name[1] == '.' && !entry->d_name[2])))
1488 			continue;
1489 		if (filename_len == 0)
1490 			break;
1491 		/* otherwise, get first entry where first */
1492 		/* filename_len characters are equal	  */
1493 		if (entry->d_name[0] == filename[0]
1494 #if defined(__SVR4) || defined(__linux__)
1495 		    && strlen(entry->d_name) >= filename_len
1496 #else
1497 		    && entry->d_namlen >= filename_len
1498 #endif
1499 		    && strncmp(entry->d_name, filename,
1500 			filename_len) == 0)
1501 			break;
1502 	}
1503 
1504 	if (entry) {		/* match found */
1505 
1506 		struct stat stbuf;
1507 #if defined(__SVR4) || defined(__linux__)
1508 		len = strlen(entry->d_name) +
1509 #else
1510 		len = entry->d_namlen +
1511 #endif
1512 		    ((dirname) ? strlen(dirname) : 0) + 1 + 1;
1513 		temp = malloc(len);
1514 		if (temp == NULL)
1515 			return NULL;
1516 		(void)sprintf(temp, "%s%s",
1517 		    dirname ? dirname : "", entry->d_name);	/* safe */
1518 
1519 		/* test, if it's directory */
1520 		if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
1521 			strcat(temp, "/");	/* safe */
1522 	} else {
1523 		(void)closedir(dir);
1524 		dir = NULL;
1525 		temp = NULL;
1526 	}
1527 
1528 	return (temp);
1529 }
1530 
1531 
1532 /*
1533  * a completion generator for usernames; returns _first_ username
1534  * which starts with supplied text
1535  * text contains a partial username preceded by random character
1536  * (usually '~'); state is ignored
1537  * it's callers responsibility to free returned value
1538  */
1539 char *
1540 username_completion_function(const char *text, int state)
1541 {
1542 	struct passwd *pwd;
1543 
1544 	if (text[0] == '\0')
1545 		return (NULL);
1546 
1547 	if (*text == '~')
1548 		text++;
1549 
1550 	if (state == 0)
1551 		setpwent();
1552 
1553 	while ((pwd = getpwent()) && text[0] == pwd->pw_name[0]
1554 	    && strcmp(text, pwd->pw_name) == 0);
1555 
1556 	if (pwd == NULL) {
1557 		endpwent();
1558 		return (NULL);
1559 	}
1560 	return (strdup(pwd->pw_name));
1561 }
1562 
1563 
1564 /*
1565  * el-compatible wrapper around rl_complete; needed for key binding
1566  */
1567 /* ARGSUSED */
1568 static unsigned char
1569 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1570 {
1571 	return (unsigned char) rl_complete(0, ch);
1572 }
1573 
1574 
1575 /*
1576  * returns list of completions for text given
1577  */
1578 char **
1579 completion_matches(const char *text, CPFunction *genfunc)
1580 {
1581 	char **match_list = NULL, *retstr, *prevstr;
1582 	size_t match_list_len, max_equal, which, i;
1583 	size_t matches;
1584 
1585 	if (h == NULL || e == NULL)
1586 		rl_initialize();
1587 
1588 	matches = 0;
1589 	match_list_len = 1;
1590 	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
1591 		/* allow for list terminator here */
1592 		if (matches + 3 >= match_list_len) {
1593 			char **nmatch_list;
1594 			while (matches + 3 >= match_list_len)
1595 				match_list_len <<= 1;
1596 			nmatch_list = realloc(match_list,
1597 			    match_list_len * sizeof(char *));
1598 			if (nmatch_list == NULL) {
1599 				free(match_list);
1600 				return NULL;
1601 			}
1602 			match_list = nmatch_list;
1603 
1604 		}
1605 		match_list[++matches] = retstr;
1606 	}
1607 
1608 	if (!match_list)
1609 		return NULL;	/* nothing found */
1610 
1611 	/* find least denominator and insert it to match_list[0] */
1612 	which = 2;
1613 	prevstr = match_list[1];
1614 	max_equal = strlen(prevstr);
1615 	for (; which <= matches; which++) {
1616 		for (i = 0; i < max_equal &&
1617 		    prevstr[i] == match_list[which][i]; i++)
1618 			continue;
1619 		max_equal = i;
1620 	}
1621 
1622 	retstr = malloc(max_equal + 1);
1623 	if (retstr == NULL) {
1624 		free(match_list);
1625 		return NULL;
1626 	}
1627 	(void)strncpy(retstr, match_list[1], max_equal);
1628 	retstr[max_equal] = '\0';
1629 	match_list[0] = retstr;
1630 
1631 	/* add NULL as last pointer to the array */
1632 	match_list[matches + 1] = (char *) NULL;
1633 
1634 	return (match_list);
1635 }
1636 
1637 /*
1638  * Sort function for qsort(). Just wrapper around strcasecmp().
1639  */
1640 static int
1641 _rl_qsort_string_compare(i1, i2)
1642 	const void *i1, *i2;
1643 {
1644 	const char *s1 = ((const char * const *)i1)[0];
1645 	const char *s2 = ((const char * const *)i2)[0];
1646 
1647 	return strcasecmp(s1, s2);
1648 }
1649 
1650 /*
1651  * Display list of strings in columnar format on readline's output stream.
1652  * 'matches' is list of strings, 'len' is number of strings in 'matches',
1653  * 'max' is maximum length of string in 'matches'.
1654  */
1655 void
1656 rl_display_match_list (matches, len, max)
1657      char **matches;
1658      int len, max;
1659 {
1660 	int i, idx, limit, count;
1661 	int screenwidth = e->el_term.t_size.h;
1662 
1663 	/*
1664 	 * Find out how many entries can be put on one line, count
1665 	 * with two spaces between strings.
1666 	 */
1667 	limit = screenwidth / (max + 2);
1668 	if (limit == 0)
1669 		limit = 1;
1670 
1671 	/* how many lines of output */
1672 	count = len / limit;
1673 	if (count * limit < len)
1674 		count++;
1675 
1676 	/* Sort the items if they are not already sorted. */
1677 	qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
1678 	    _rl_qsort_string_compare);
1679 
1680 	idx = 1;
1681 	for(; count > 0; count--) {
1682 		for(i = 0; i < limit && matches[idx]; i++, idx++)
1683 			(void)fprintf(e->el_outfile, "%-*s  ", max,
1684 			    matches[idx]);
1685 		(void)fprintf(e->el_outfile, "\n");
1686 	}
1687 }
1688 
1689 /*
1690  * Complete the word at or before point, called by rl_complete()
1691  * 'what_to_do' says what to do with the completion.
1692  * `?' means list the possible completions.
1693  * TAB means do standard completion.
1694  * `*' means insert all of the possible completions.
1695  * `!' means to do standard completion, and list all possible completions if
1696  * there is more than one.
1697  *
1698  * Note: '*' support is not implemented
1699  */
1700 static int
1701 rl_complete_internal(int what_to_do)
1702 {
1703 	Function *complet_func;
1704 	const LineInfo *li;
1705 	char *temp, **matches;
1706 	const char *ctemp;
1707 	size_t len;
1708 
1709 	rl_completion_type = what_to_do;
1710 
1711 	if (h == NULL || e == NULL)
1712 		rl_initialize();
1713 
1714 	complet_func = rl_completion_entry_function;
1715 	if (!complet_func)
1716 		complet_func = (Function *)(void *)filename_completion_function;
1717 
1718 	/* We now look backwards for the start of a filename/variable word */
1719 	li = el_line(e);
1720 	ctemp = (const char *) li->cursor;
1721 	while (ctemp > li->buffer
1722 	    && !strchr(rl_basic_word_break_characters, ctemp[-1])
1723 	    && (!rl_special_prefixes
1724 		|| !strchr(rl_special_prefixes, ctemp[-1]) ) )
1725 		ctemp--;
1726 
1727 	len = li->cursor - ctemp;
1728 	temp = alloca(len + 1);
1729 	(void)strncpy(temp, ctemp, len);
1730 	temp[len] = '\0';
1731 
1732 	/* these can be used by function called in completion_matches() */
1733 	/* or (*rl_attempted_completion_function)() */
1734 	rl_point = li->cursor - li->buffer;
1735 	rl_end = li->lastchar - li->buffer;
1736 
1737 	if (rl_attempted_completion_function) {
1738 		int end = li->cursor - li->buffer;
1739 		matches = (*rl_attempted_completion_function) (temp, (int)
1740 		    (end - len), end);
1741 	} else
1742 		matches = 0;
1743 	if (!rl_attempted_completion_function || !matches)
1744 		matches = completion_matches(temp, (CPFunction *)complet_func);
1745 
1746 	if (matches) {
1747 		int i, retval = CC_REFRESH;
1748 		int matches_num, maxlen, match_len, match_display=1;
1749 
1750 		/*
1751 		 * Only replace the completed string with common part of
1752 		 * possible matches if there is possible completion.
1753 		 */
1754 		if (matches[0][0] != '\0') {
1755 			el_deletestr(e, (int) len);
1756 			el_insertstr(e, matches[0]);
1757 		}
1758 
1759 		if (what_to_do == '?')
1760 			goto display_matches;
1761 
1762 		if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
1763 			/*
1764 			 * We found exact match. Add a space after
1765 			 * it, unless we do filename completion and the
1766 			 * object is a directory.
1767 			 */
1768 			size_t alen = strlen(matches[0]);
1769 			if ((complet_func !=
1770 			    (Function *)filename_completion_function
1771 			      || (alen > 0 && (matches[0])[alen - 1] != '/'))
1772 			    && rl_completion_append_character) {
1773 				char buf[2];
1774 				buf[0] = rl_completion_append_character;
1775 				buf[1] = '\0';
1776 				el_insertstr(e, buf);
1777 			}
1778 		} else if (what_to_do == '!') {
1779     display_matches:
1780 			/*
1781 			 * More than one match and requested to list possible
1782 			 * matches.
1783 			 */
1784 
1785 			for(i=1, maxlen=0; matches[i]; i++) {
1786 				match_len = strlen(matches[i]);
1787 				if (match_len > maxlen)
1788 					maxlen = match_len;
1789 			}
1790 			matches_num = i - 1;
1791 
1792 			/* newline to get on next line from command line */
1793 			(void)fprintf(e->el_outfile, "\n");
1794 
1795 			/*
1796 			 * If there are too many items, ask user for display
1797 			 * confirmation.
1798 			 */
1799 			if (matches_num > rl_completion_query_items) {
1800 				(void)fprintf(e->el_outfile,
1801 				    "Display all %d possibilities? (y or n) ",
1802 				    matches_num);
1803 				(void)fflush(e->el_outfile);
1804 				if (getc(stdin) != 'y')
1805 					match_display = 0;
1806 				(void)fprintf(e->el_outfile, "\n");
1807 			}
1808 
1809 			if (match_display)
1810 				rl_display_match_list(matches, matches_num,
1811 					maxlen);
1812 			retval = CC_REDISPLAY;
1813 		} else if (matches[0][0]) {
1814 			/*
1815 			 * There was some common match, but the name was
1816 			 * not complete enough. Next tab will print possible
1817 			 * completions.
1818 			 */
1819 			el_beep(e);
1820 		} else {
1821 			/* lcd is not a valid object - further specification */
1822 			/* is needed */
1823 			el_beep(e);
1824 			retval = CC_NORM;
1825 		}
1826 
1827 		/* free elements of array and the array itself */
1828 		for (i = 0; matches[i]; i++)
1829 			free(matches[i]);
1830 		free(matches), matches = NULL;
1831 
1832 		return (retval);
1833 	}
1834 	return (CC_NORM);
1835 }
1836 
1837 
1838 /*
1839  * complete word at current point
1840  */
1841 int
1842 rl_complete(int ignore, int invoking_key)
1843 {
1844 	if (h == NULL || e == NULL)
1845 		rl_initialize();
1846 
1847 	if (rl_inhibit_completion) {
1848 		rl_insert(ignore, invoking_key);
1849 		return (CC_REFRESH);
1850 	} else if (e->el_state.lastcmd == el_rl_complete_cmdnum)
1851 		return rl_complete_internal('?');
1852 	else if (_rl_complete_show_all)
1853 		return rl_complete_internal('!');
1854 	else
1855 		return (rl_complete_internal(TAB));
1856 }
1857 
1858 
1859 /*
1860  * misc other functions
1861  */
1862 
1863 /*
1864  * bind key c to readline-type function func
1865  */
1866 int
1867 rl_bind_key(int c, int func(int, int))
1868 {
1869 	int retval = -1;
1870 
1871 	if (h == NULL || e == NULL)
1872 		rl_initialize();
1873 
1874 	if (func == rl_insert) {
1875 		/* XXX notice there is no range checking of ``c'' */
1876 		e->el_map.key[c] = ED_INSERT;
1877 		retval = 0;
1878 	}
1879 	return (retval);
1880 }
1881 
1882 
1883 /*
1884  * read one key from input - handles chars pushed back
1885  * to input stream also
1886  */
1887 int
1888 rl_read_key(void)
1889 {
1890 	char fooarr[2 * sizeof(int)];
1891 
1892 	if (e == NULL || h == NULL)
1893 		rl_initialize();
1894 
1895 	return (el_getc(e, fooarr));
1896 }
1897 
1898 
1899 /*
1900  * reset the terminal
1901  */
1902 /* ARGSUSED */
1903 void
1904 rl_reset_terminal(const char *p __attribute__((__unused__)))
1905 {
1906 
1907 	if (h == NULL || e == NULL)
1908 		rl_initialize();
1909 	el_reset(e);
1910 }
1911 
1912 
1913 /*
1914  * insert character ``c'' back into input stream, ``count'' times
1915  */
1916 int
1917 rl_insert(int count, int c)
1918 {
1919 	char arr[2];
1920 
1921 	if (h == NULL || e == NULL)
1922 		rl_initialize();
1923 
1924 	/* XXX - int -> char conversion can lose on multichars */
1925 	arr[0] = c;
1926 	arr[1] = '\0';
1927 
1928 	for (; count > 0; count--)
1929 		el_push(e, arr);
1930 
1931 	return (0);
1932 }
1933 
1934 /*ARGSUSED*/
1935 int
1936 rl_newline(int count, int c)
1937 {
1938 	/*
1939 	 * Readline-4.0 appears to ignore the args.
1940 	 */
1941 	return rl_insert(1, '\n');
1942 }
1943 
1944 /*ARGSUSED*/
1945 static unsigned char
1946 rl_bind_wrapper(EditLine *el, unsigned char c)
1947 {
1948 	if (map[c] == NULL)
1949 	    return CC_ERROR;
1950 	(*map[c])(NULL, c);
1951 
1952 	/* If rl_done was set by the above call, deal with it here */
1953 	if (rl_done)
1954 		return CC_EOF;
1955 
1956 	return CC_NORM;
1957 }
1958 
1959 int
1960 rl_add_defun(const char *name, Function *fun, int c)
1961 {
1962 	char dest[8];
1963 	if (c >= sizeof(map) / sizeof(map[0]) || c < 0)
1964 		return -1;
1965 	map[(unsigned char)c] = fun;
1966 	el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1967 	vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1968 	el_set(e, EL_BIND, dest, name);
1969 	return 0;
1970 }
1971 
1972 void
1973 rl_callback_read_char()
1974 {
1975 	int count = 0, done = 0;
1976 	const char *buf = el_gets(e, &count);
1977 	char *wbuf;
1978 
1979 	if (buf == NULL || count-- <= 0)
1980 		return;
1981 	if (count == 0 && buf[0] == CTRL('d'))
1982 		done = 1;
1983 	if (buf[count] == '\n' || buf[count] == '\r')
1984 		done = 2;
1985 
1986 	if (done && rl_linefunc != NULL) {
1987 		el_set(e, EL_UNBUFFERED, 0);
1988 		if (done == 2) {
1989 		    if ((wbuf = strdup(buf)) != NULL)
1990 			wbuf[count] = '\0';
1991 		} else
1992 			wbuf = NULL;
1993 		(*(void (*)(const char *))rl_linefunc)(wbuf);
1994 	}
1995 }
1996 
1997 void
1998 rl_callback_handler_install (const char *prompt, VFunction *linefunc)
1999 {
2000 	if (e == NULL) {
2001 		rl_initialize();
2002 	}
2003 	if (rl_prompt)
2004 		free(rl_prompt);
2005 	rl_prompt = prompt ? strdup(strchr(prompt, *prompt)) : NULL;
2006 	rl_linefunc = linefunc;
2007 	el_set(e, EL_UNBUFFERED, 1);
2008 }
2009 
2010 void
2011 rl_callback_handler_remove(void)
2012 {
2013 	el_set(e, EL_UNBUFFERED, 0);
2014 }
2015 
2016 void
2017 rl_redisplay(void)
2018 {
2019 	char a[2];
2020 	a[0] = CTRL('r');
2021 	a[1] = '\0';
2022 	el_push(e, a);
2023 }
2024 
2025 int
2026 rl_get_previous_history(int count, int key)
2027 {
2028 	char a[2];
2029 	a[0] = key;
2030 	a[1] = '\0';
2031 	while (count--)
2032 		el_push(e, a);
2033 	return 0;
2034 }
2035 
2036 void
2037 /*ARGSUSED*/
2038 rl_prep_terminal(int meta_flag)
2039 {
2040 	el_set(e, EL_PREP_TERM, 1);
2041 }
2042 
2043 void
2044 rl_deprep_terminal()
2045 {
2046 	el_set(e, EL_PREP_TERM, 0);
2047 }
2048 
2049 int
2050 rl_read_init_file(const char *s)
2051 {
2052 	return(el_source(e, s));
2053 }
2054 
2055 int
2056 rl_parse_and_bind(const char *line)
2057 {
2058 	const char **argv;
2059 	int argc;
2060 	Tokenizer *tok;
2061 
2062 	tok = tok_init(NULL);
2063 	tok_str(tok, line, &argc, &argv);
2064 	argc = el_parse(e, argc, argv);
2065 	tok_end(tok);
2066 	return (argc ? 1 : 0);
2067 }
2068 
2069 void
2070 rl_stuff_char(int c)
2071 {
2072 	char buf[2];
2073 
2074 	buf[0] = c;
2075 	buf[1] = '\0';
2076 	el_insertstr(e, buf);
2077 }
2078 
2079 static int
2080 _rl_event_read_char(EditLine *el, char *cp)
2081 {
2082 	int	n, num_read = 0;
2083 
2084 	*cp = 0;
2085 	while (rl_event_hook) {
2086 
2087 		(*rl_event_hook)();
2088 
2089 #if defined(FIONREAD)
2090 		if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2091 			return(-1);
2092 		if (n)
2093 			num_read = read(el->el_infd, cp, 1);
2094 		else
2095 			num_read = 0;
2096 #elif defined(F_SETFL) && defined(O_NDELAY)
2097 		if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2098 			return(-1);
2099 		if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2100 			return(-1);
2101 		num_read = read(el->el_infd, cp, 1);
2102 		if (fcntl(el->el_infd, F_SETFL, n))
2103 			return(-1);
2104 #else
2105 		/* not non-blocking, but what you gonna do? */
2106 		num_read = read(el->el_infd, cp, 1);
2107 		return(-1);
2108 #endif
2109 
2110 		if (num_read < 0 && errno == EAGAIN)
2111 			continue;
2112 		if (num_read == 0)
2113 			continue;
2114 		break;
2115 	}
2116 	if (!rl_event_hook)
2117 		el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2118 	return(num_read);
2119 }
2120