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