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