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