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