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