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