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