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