readline.c revision 220370
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: head/lib/libedit/readline.c 220370 2011-04-05 18:41:01Z obrien $");
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 (h == NULL || e == NULL)
1367		rl_initialize();
1368
1369	wline = ct_decode_string(line, &conv);
1370
1371	(void)FUNW(history)(h, &ev, H_ENTER, wline);
1372	if (FUNW(history)(h, &ev, H_GETSIZE) == 0)
1373		history_length = ev.num;
1374
1375	return (!(history_length > 0)); /* return 0 if all is okay */
1376}
1377
1378
1379/*
1380 * remove the specified entry from the history list and return it.
1381 */
1382HIST_ENTRY *
1383remove_history(int num)
1384{
1385	HIST_ENTRY *he;
1386	TYPE(HistEvent) ev;
1387
1388	if (h == NULL || e == NULL)
1389		rl_initialize();
1390
1391	if ((he = malloc(sizeof(*he))) == NULL)
1392		return NULL;
1393
1394	if (FUNW(history)(h, &ev, H_DELDATA, num, &he->data) != 0) {
1395		free(he);
1396		return NULL;
1397	}
1398
1399	he->line = ct_encode_string(ev.str, &conv);
1400	if (FUNW(history)(h, &ev, H_GETSIZE) == 0)
1401		history_length = ev.num;
1402
1403	return he;
1404}
1405
1406
1407/*
1408 * replace the line and data of the num-th entry
1409 */
1410HIST_ENTRY *
1411replace_history_entry(int num, const char *line, histdata_t data)
1412{
1413	HIST_ENTRY *he;
1414	TYPE(HistEvent) ev;
1415	int curr_num;
1416
1417	if (h == NULL || e == NULL)
1418		rl_initialize();
1419
1420	/* save current position */
1421	if (FUNW(history)(h, &ev, H_CURR) != 0)
1422		return NULL;
1423	curr_num = ev.num;
1424
1425	/* start from the oldest */
1426	if (FUNW(history)(h, &ev, H_LAST) != 0)
1427		return NULL;	/* error */
1428
1429	if ((he = malloc(sizeof(*he))) == NULL)
1430		return NULL;
1431
1432	/* look forwards for event matching specified offset */
1433	if (FUNW(history)(h, &ev, H_NEXT_EVDATA, num, &he->data))
1434		goto out;
1435
1436	he->line = strdup(ct_encode_string(ev.str, &e->el_scratch));
1437	if (he->line == NULL)
1438		goto out;
1439
1440	if (FUNW(history)(h, &ev, H_REPLACE, line, data))
1441		goto out;
1442
1443	/* restore pointer to where it was */
1444	if (FUNW(history)(h, &ev, H_SET, curr_num))
1445		goto out;
1446
1447	return he;
1448out:
1449	free(he);
1450	return NULL;
1451}
1452
1453/*
1454 * clear the history list - delete all entries
1455 */
1456void
1457clear_history(void)
1458{
1459	TYPE(HistEvent) ev;
1460
1461	(void)FUNW(history)(h, &ev, H_CLEAR);
1462	history_length = 0;
1463}
1464
1465
1466/*
1467 * returns offset of the current history event
1468 */
1469int
1470where_history(void)
1471{
1472	TYPE(HistEvent) ev;
1473	int curr_num, off;
1474
1475	if (FUNW(history)(h, &ev, H_CURR) != 0)
1476		return (0);
1477	curr_num = ev.num;
1478
1479	(void)FUNW(history)(h, &ev, H_FIRST);
1480	off = 1;
1481	while (ev.num != curr_num && FUNW(history)(h, &ev, H_NEXT) == 0)
1482		off++;
1483
1484	return (off);
1485}
1486
1487
1488/*
1489 * returns current history event or NULL if there is no such event
1490 */
1491HIST_ENTRY *
1492current_history(void)
1493{
1494
1495	return (_move_history(H_CURR));
1496}
1497
1498
1499/*
1500 * returns total number of bytes history events' data are using
1501 */
1502int
1503history_total_bytes(void)
1504{
1505	TYPE(HistEvent) ev;
1506	int curr_num;
1507	size_t size;
1508
1509	if (FUNW(history)(h, &ev, H_CURR) != 0)
1510		return (-1);
1511	curr_num = ev.num;
1512
1513	(void)FUNW(history)(h, &ev, H_FIRST);
1514	size = 0;
1515	do
1516		size += Strlen(ev.str) * sizeof(*ev.str);
1517	while (FUNW(history)(h, &ev, H_NEXT) == 0);
1518
1519	/* get to the same position as before */
1520	FUNW(history)(h, &ev, H_PREV_EVENT, curr_num);
1521
1522	return (int)(size);
1523}
1524
1525
1526/*
1527 * sets the position in the history list to ``pos''
1528 */
1529int
1530history_set_pos(int pos)
1531{
1532	TYPE(HistEvent) ev;
1533	int curr_num;
1534
1535	if (pos >= history_length || pos < 0)
1536		return (-1);
1537
1538	(void)FUNW(history)(h, &ev, H_CURR);
1539	curr_num = ev.num;
1540
1541	/*
1542	 * use H_DELDATA to set to nth history (without delete) by passing
1543	 * (void **)-1
1544	 */
1545	if (FUNW(history)(h, &ev, H_DELDATA, pos, (void **)-1)) {
1546		(void)FUNW(history)(h, &ev, H_SET, curr_num);
1547		return(-1);
1548	}
1549	return (0);
1550}
1551
1552
1553/*
1554 * returns previous event in history and shifts pointer accordingly
1555 */
1556HIST_ENTRY *
1557previous_history(void)
1558{
1559
1560	return (_move_history(H_PREV));
1561}
1562
1563
1564/*
1565 * returns next event in history and shifts pointer accordingly
1566 */
1567HIST_ENTRY *
1568next_history(void)
1569{
1570
1571	return (_move_history(H_NEXT));
1572}
1573
1574
1575/*
1576 * searches for first history event containing the str
1577 */
1578int
1579history_search(const char *str, int direction)
1580{
1581	TYPE(HistEvent) ev;
1582	const Char *strp;
1583	const Char *wstr;
1584	int curr_num;
1585
1586	if (FUNW(history)(h, &ev, H_CURR) != 0)
1587		return (-1);
1588	curr_num = ev.num;
1589
1590	wstr = ct_decode_string(str, &conv);
1591	for (;;) {
1592		if ((strp = Strstr(ev.str, wstr)) != NULL)
1593			return (int) (strp - ev.str);
1594		if (FUNW(history)(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1595			break;
1596	}
1597	(void)FUNW(history)(h, &ev, H_SET, curr_num);
1598	return (-1);
1599}
1600
1601
1602/*
1603 * searches for first history event beginning with str
1604 */
1605int
1606history_search_prefix(const char *str, int direction)
1607{
1608	TYPE(HistEvent) ev;
1609
1610	return (FUNW(history)(h, &ev, direction < 0 ?
1611	    H_PREV_STR : H_NEXT_STR, str));
1612}
1613
1614
1615/*
1616 * search for event in history containing str, starting at offset
1617 * abs(pos); continue backward, if pos<0, forward otherwise
1618 */
1619/* ARGSUSED */
1620int
1621history_search_pos(const char *str,
1622		   int direction __attribute__((__unused__)), int pos)
1623{
1624	TYPE(HistEvent) ev;
1625	int curr_num, off;
1626	const Char *wstr;
1627
1628	off = (pos > 0) ? pos : -pos;
1629	pos = (pos > 0) ? 1 : -1;
1630
1631	if (FUNW(history)(h, &ev, H_CURR) != 0)
1632		return (-1);
1633	curr_num = ev.num;
1634
1635	if (history_set_pos(off) != 0 || FUNW(history)(h, &ev, H_CURR) != 0)
1636		return (-1);
1637
1638	wstr = ct_decode_string(str, &conv);
1639	for (;;) {
1640		if (Strstr(ev.str, wstr))
1641			return (off);
1642		if (FUNW(history)(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1643			break;
1644	}
1645
1646	/* set "current" pointer back to previous state */
1647	(void)FUNW(history)(h, &ev,
1648	    pos < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1649
1650	return (-1);
1651}
1652
1653
1654/********************************/
1655/* completion functions */
1656
1657char *
1658tilde_expand(char *name)
1659{
1660	return fn_tilde_expand(name);
1661}
1662
1663char *
1664filename_completion_function(const char *name, int state)
1665{
1666	return fn_filename_completion_function(name, state);
1667}
1668
1669/*
1670 * a completion generator for usernames; returns _first_ username
1671 * which starts with supplied text
1672 * text contains a partial username preceded by random character
1673 * (usually '~'); state is ignored
1674 * it's callers responsibility to free returned value
1675 */
1676char *
1677username_completion_function(const char *text, int state)
1678{
1679	struct passwd *pwd, pwres;
1680	char pwbuf[1024];
1681
1682	if (text[0] == '\0')
1683		return (NULL);
1684
1685	if (*text == '~')
1686		text++;
1687
1688	if (state == 0)
1689		setpwent();
1690
1691	while (getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pwd) == 0
1692	    && pwd != NULL && text[0] == pwd->pw_name[0]
1693	    && strcmp(text, pwd->pw_name) == 0);
1694
1695	if (pwd == NULL) {
1696		endpwent();
1697		return NULL;
1698	}
1699	return strdup(pwd->pw_name);
1700}
1701
1702
1703/*
1704 * el-compatible wrapper to send TSTP on ^Z
1705 */
1706/* ARGSUSED */
1707static unsigned char
1708_el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1709{
1710	(void)kill(0, SIGTSTP);
1711	return CC_NORM;
1712}
1713
1714/*
1715 * Display list of strings in columnar format on readline's output stream.
1716 * 'matches' is list of strings, 'len' is number of strings in 'matches',
1717 * 'max' is maximum length of string in 'matches'.
1718 */
1719void
1720rl_display_match_list(char **matches, int len, int max)
1721{
1722
1723	fn_display_match_list(e, matches, (size_t)len, (size_t)max);
1724}
1725
1726static const char *
1727/*ARGSUSED*/
1728_rl_completion_append_character_function(const char *dummy
1729    __attribute__((__unused__)))
1730{
1731	static char buf[2];
1732	buf[0] = rl_completion_append_character;
1733	buf[1] = '\0';
1734	return buf;
1735}
1736
1737
1738/*
1739 * complete word at current point
1740 */
1741/* ARGSUSED */
1742int
1743rl_complete(int ignore __attribute__((__unused__)), int invoking_key)
1744{
1745#ifdef WIDECHAR
1746	static ct_buffer_t wbreak_conv, sprefix_conv;
1747#endif
1748
1749	if (h == NULL || e == NULL)
1750		rl_initialize();
1751
1752	if (rl_inhibit_completion) {
1753		char arr[2];
1754		arr[0] = (char)invoking_key;
1755		arr[1] = '\0';
1756		el_insertstr(e, arr);
1757		return (CC_REFRESH);
1758	}
1759
1760	/* Just look at how many global variables modify this operation! */
1761	return fn_complete(e,
1762	    (CPFunction *)rl_completion_entry_function,
1763	    rl_attempted_completion_function,
1764	    ct_decode_string(rl_basic_word_break_characters, &wbreak_conv),
1765	    ct_decode_string(rl_special_prefixes, &sprefix_conv),
1766	    _rl_completion_append_character_function,
1767	    (size_t)rl_completion_query_items,
1768	    &rl_completion_type, &rl_attempted_completion_over,
1769	    &rl_point, &rl_end, NULL, NULL, NULL);
1770}
1771
1772
1773/* ARGSUSED */
1774static unsigned char
1775_el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1776{
1777	return (unsigned char)rl_complete(0, ch);
1778}
1779
1780/*
1781 * misc other functions
1782 */
1783
1784/*
1785 * bind key c to readline-type function func
1786 */
1787int
1788rl_bind_key(int c, rl_command_func_t *func)
1789{
1790	int retval = -1;
1791
1792	if (h == NULL || e == NULL)
1793		rl_initialize();
1794
1795	if (func == rl_insert) {
1796		/* XXX notice there is no range checking of ``c'' */
1797		e->el_map.key[c] = ED_INSERT;
1798		retval = 0;
1799	}
1800	return (retval);
1801}
1802
1803
1804/*
1805 * read one key from input - handles chars pushed back
1806 * to input stream also
1807 */
1808int
1809rl_read_key(void)
1810{
1811	char fooarr[2 * sizeof(int)];
1812
1813	if (e == NULL || h == NULL)
1814		rl_initialize();
1815
1816	return (el_getc(e, fooarr));
1817}
1818
1819
1820/*
1821 * reset the terminal
1822 */
1823/* ARGSUSED */
1824void
1825rl_reset_terminal(const char *p __attribute__((__unused__)))
1826{
1827
1828	if (h == NULL || e == NULL)
1829		rl_initialize();
1830	el_reset(e);
1831}
1832
1833
1834/*
1835 * insert character ``c'' back into input stream, ``count'' times
1836 */
1837int
1838rl_insert(int count, int c)
1839{
1840	char arr[2];
1841
1842	if (h == NULL || e == NULL)
1843		rl_initialize();
1844
1845	/* XXX - int -> char conversion can lose on multichars */
1846	arr[0] = c;
1847	arr[1] = '\0';
1848
1849	for (; count > 0; count--)
1850		el_push(e, arr);
1851
1852	return (0);
1853}
1854
1855int
1856rl_insert_text(const char *text)
1857{
1858	if (!text || *text == 0)
1859		return (0);
1860
1861	if (h == NULL || e == NULL)
1862		rl_initialize();
1863
1864	if (el_insertstr(e, text) < 0)
1865		return (0);
1866	return (int)strlen(text);
1867}
1868
1869/*ARGSUSED*/
1870int
1871rl_newline(int count, int c)
1872{
1873	/*
1874	 * Readline-4.0 appears to ignore the args.
1875	 */
1876	return rl_insert(1, '\n');
1877}
1878
1879/*ARGSUSED*/
1880static unsigned char
1881rl_bind_wrapper(EditLine *el, unsigned char c)
1882{
1883	if (map[c] == NULL)
1884	    return CC_ERROR;
1885
1886	_rl_update_pos();
1887
1888	(*map[c])(NULL, c);
1889
1890	/* If rl_done was set by the above call, deal with it here */
1891	if (rl_done)
1892		return CC_EOF;
1893
1894	return CC_NORM;
1895}
1896
1897int
1898rl_add_defun(const char *name, Function *fun, int c)
1899{
1900	char dest[8];
1901	if ((size_t)c >= sizeof(map) / sizeof(map[0]) || c < 0)
1902		return -1;
1903	map[(unsigned char)c] = fun;
1904	el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
1905	vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
1906	el_set(e, EL_BIND, dest, name);
1907	return 0;
1908}
1909
1910void
1911rl_callback_read_char()
1912{
1913	int count = 0, done = 0;
1914	const char *buf = el_gets(e, &count);
1915	char *wbuf;
1916
1917	if (buf == NULL || count-- <= 0)
1918		return;
1919	if (count == 0 && buf[0] == e->el_tty.t_c[TS_IO][C_EOF])
1920		done = 1;
1921	if (buf[count] == '\n' || buf[count] == '\r')
1922		done = 2;
1923
1924	if (done && rl_linefunc != NULL) {
1925		el_set(e, EL_UNBUFFERED, 0);
1926		if (done == 2) {
1927		    if ((wbuf = strdup(buf)) != NULL)
1928			wbuf[count] = '\0';
1929		} else
1930			wbuf = NULL;
1931		(*(void (*)(const char *))rl_linefunc)(wbuf);
1932		//el_set(e, EL_UNBUFFERED, 1);
1933	}
1934}
1935
1936void
1937rl_callback_handler_install(const char *prompt, VCPFunction *linefunc)
1938{
1939	if (e == NULL) {
1940		rl_initialize();
1941	}
1942	(void)rl_set_prompt(prompt);
1943	rl_linefunc = linefunc;
1944	el_set(e, EL_UNBUFFERED, 1);
1945}
1946
1947void
1948rl_callback_handler_remove(void)
1949{
1950	el_set(e, EL_UNBUFFERED, 0);
1951	rl_linefunc = NULL;
1952}
1953
1954void
1955rl_redisplay(void)
1956{
1957	char a[2];
1958	a[0] = e->el_tty.t_c[TS_IO][C_REPRINT];
1959	a[1] = '\0';
1960	el_push(e, a);
1961}
1962
1963int
1964rl_get_previous_history(int count, int key)
1965{
1966	char a[2];
1967	a[0] = key;
1968	a[1] = '\0';
1969	while (count--)
1970		el_push(e, a);
1971	return 0;
1972}
1973
1974void
1975/*ARGSUSED*/
1976rl_prep_terminal(int meta_flag)
1977{
1978	el_set(e, EL_PREP_TERM, 1);
1979}
1980
1981void
1982rl_deprep_terminal(void)
1983{
1984	el_set(e, EL_PREP_TERM, 0);
1985}
1986
1987int
1988rl_read_init_file(const char *s)
1989{
1990	return(el_source(e, s));
1991}
1992
1993int
1994rl_parse_and_bind(const char *line)
1995{
1996	const char **argv;
1997	int argc;
1998	Tokenizer *tok;
1999
2000	tok = tok_init(NULL);
2001	tok_str(tok, line, &argc, &argv);
2002	argc = el_parse(e, argc, argv);
2003	tok_end(tok);
2004	return (argc ? 1 : 0);
2005}
2006
2007int
2008rl_variable_bind(const char *var, const char *value)
2009{
2010	/*
2011	 * The proper return value is undocument, but this is what the
2012	 * readline source seems to do.
2013	 */
2014	return ((el_set(e, EL_BIND, "", var, value) == -1) ? 1 : 0);
2015}
2016
2017void
2018rl_stuff_char(int c)
2019{
2020	char buf[2];
2021
2022	buf[0] = c;
2023	buf[1] = '\0';
2024	el_insertstr(e, buf);
2025}
2026
2027static int
2028_rl_event_read_char(EditLine *el, char *cp)
2029{
2030	int	n;
2031	ssize_t num_read = 0;
2032
2033	*cp = '\0';
2034	while (rl_event_hook) {
2035
2036		(*rl_event_hook)();
2037
2038#if defined(FIONREAD)
2039		if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2040			return(-1);
2041		if (n)
2042			num_read = read(el->el_infd, cp, 1);
2043		else
2044			num_read = 0;
2045#elif defined(F_SETFL) && defined(O_NDELAY)
2046		if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2047			return(-1);
2048		if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2049			return(-1);
2050		num_read = read(el->el_infd, cp, 1);
2051		if (fcntl(el->el_infd, F_SETFL, n))
2052			return(-1);
2053#else
2054		/* not non-blocking, but what you gonna do? */
2055		num_read = read(el->el_infd, cp, 1);
2056		return(-1);
2057#endif
2058
2059		if (num_read < 0 && errno == EAGAIN)
2060			continue;
2061		if (num_read == 0)
2062			continue;
2063		break;
2064	}
2065	if (!rl_event_hook)
2066		el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2067	return (int)num_read;
2068}
2069
2070static void
2071_rl_update_pos(void)
2072{
2073	const LineInfo *li = el_line(e);
2074
2075	rl_point = (int)(li->cursor - li->buffer);
2076	rl_end = (int)(li->lastchar - li->buffer);
2077}
2078
2079void
2080rl_get_screen_size(int *rows, int *cols)
2081{
2082	if (rows)
2083		el_get(e, EL_GETTC, "li", rows);
2084	if (cols)
2085		el_get(e, EL_GETTC, "co", cols);
2086}
2087
2088void
2089rl_set_screen_size(int rows, int cols)
2090{
2091	char buf[64];
2092	(void)snprintf(buf, sizeof(buf), "%d", rows);
2093	el_set(e, EL_SETTC, "li", buf);
2094	(void)snprintf(buf, sizeof(buf), "%d", cols);
2095	el_set(e, EL_SETTC, "co", buf);
2096}
2097
2098char **
2099rl_completion_matches(const char *str, rl_compentry_func_t *fun)
2100{
2101	size_t len, max, i, j, min;
2102	char **list, *match, *a, *b;
2103
2104	len = 1;
2105	max = 10;
2106	if ((list = malloc(max * sizeof(*list))) == NULL)
2107		return NULL;
2108
2109	while ((match = (*fun)(str, (int)(len - 1))) != NULL) {
2110		list[len++] = match;
2111		if (len == max) {
2112			char **nl;
2113			max += 10;
2114			if ((nl = realloc(list, max * sizeof(*nl))) == NULL)
2115				goto out;
2116			list = nl;
2117		}
2118	}
2119	if (len == 1)
2120		goto out;
2121	list[len] = NULL;
2122	if (len == 2) {
2123		if ((list[0] = strdup(list[1])) == NULL)
2124			goto out;
2125		return list;
2126	}
2127	qsort(&list[1], len - 1, sizeof(*list),
2128	    (int (*)(const void *, const void *)) strcmp);
2129	min = SIZE_T_MAX;
2130	for (i = 1, a = list[i]; i < len - 1; i++, a = b) {
2131		b = list[i + 1];
2132		for (j = 0; a[j] && a[j] == b[j]; j++)
2133			continue;
2134		if (min > j)
2135			min = j;
2136	}
2137	if (min == 0 && *str) {
2138		if ((list[0] = strdup(str)) == NULL)
2139			goto out;
2140	} else {
2141		if ((list[0] = malloc(min + 1)) == NULL)
2142			goto out;
2143		(void)memcpy(list[0], list[1], min);
2144		list[0][min] = '\0';
2145	}
2146	return list;
2147
2148out:
2149	free(list);
2150	return NULL;
2151}
2152
2153char *
2154rl_filename_completion_function (const char *text, int state)
2155{
2156	return fn_filename_completion_function(text, state);
2157}
2158
2159void
2160rl_forced_update_display(void)
2161{
2162	el_set(e, EL_REFRESH);
2163}
2164
2165int
2166_rl_abort_internal(void)
2167{
2168	el_beep(e);
2169	longjmp(topbuf, 1);
2170	/*NOTREACHED*/
2171}
2172
2173int
2174_rl_qsort_string_compare(char **s1, char **s2)
2175{
2176	return strcoll(*s1, *s2);
2177}
2178
2179HISTORY_STATE *
2180history_get_history_state(void)
2181{
2182	HISTORY_STATE *hs;
2183
2184	if ((hs = malloc(sizeof(HISTORY_STATE))) == NULL)
2185		return (NULL);
2186	hs->length = history_length;
2187	return (hs);
2188}
2189
2190int
2191/*ARGSUSED*/
2192rl_kill_text(int from, int to)
2193{
2194	return 0;
2195}
2196
2197Keymap
2198rl_make_bare_keymap(void)
2199{
2200	return NULL;
2201}
2202
2203Keymap
2204rl_get_keymap(void)
2205{
2206	return NULL;
2207}
2208
2209void
2210/*ARGSUSED*/
2211rl_set_keymap(Keymap k)
2212{
2213}
2214
2215int
2216/*ARGSUSED*/
2217rl_generic_bind(int type, const char * keyseq, const char * data, Keymap k)
2218{
2219	return 0;
2220}
2221
2222int
2223/*ARGSUSED*/
2224rl_bind_key_in_map(int key, rl_command_func_t *fun, Keymap k)
2225{
2226	return 0;
2227}
2228
2229/* unsupported, but needed by python */
2230void
2231rl_cleanup_after_signal(void)
2232{
2233}
2234
2235int
2236rl_on_new_line(void)
2237{
2238	return 0;
2239}
2240