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