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