Home | History | Annotate | Line # | Download | only in sh
histedit.c revision 1.70
      1 /*	$NetBSD: histedit.c,v 1.70 2024/07/12 07:30:30 kre Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Kenneth Almquist.
      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  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
     39 #else
     40 __RCSID("$NetBSD: histedit.c,v 1.70 2024/07/12 07:30:30 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <sys/param.h>
     45 #include <sys/stat.h>
     46 #include <dirent.h>
     47 #include <paths.h>
     48 #include <stdio.h>
     49 #include <stdlib.h>
     50 #include <unistd.h>
     51 /*
     52  * Editline and history functions (and glue).
     53  */
     54 #include "shell.h"
     55 #include "parser.h"
     56 #include "var.h"
     57 #include "options.h"
     58 #include "builtins.h"
     59 #include "main.h"
     60 #include "output.h"
     61 #include "mystring.h"
     62 #include "myhistedit.h"
     63 #include "error.h"
     64 #include "alias.h"
     65 
     66 #ifndef SMALL		/* almost all the rest of this file */
     67 
     68 #include "eval.h"
     69 #include "memalloc.h"
     70 #include "show.h"
     71 
     72 #define MAXHISTLOOPS	4	/* max recursions through fc */
     73 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
     74 
     75 History *hist;	/* history cookie */
     76 EditLine *el;	/* editline cookie */
     77 int displayhist;
     78 static FILE *el_in, *el_out;
     79 static int curpos;
     80 
     81 #ifdef DEBUG
     82 extern FILE *tracefile;
     83 #endif
     84 
     85 static const char *fc_replace(const char *, char *, char *);
     86 static int not_fcnumber(const char *);
     87 static int str_to_event(const char *, int);
     88 static int comparator(const void *, const void *);
     89 static char **sh_matches(const char *, int, int);
     90 static unsigned char sh_complete(EditLine *, int);
     91 
     92 /*
     93  * Set history and editing status.  Called whenever the status may
     94  * have changed (figures out what to do).
     95  */
     96 void
     97 histedit(void)
     98 {
     99 	FILE *el_err;
    100 
    101 #define editing (Eflag || Vflag)
    102 
    103 	CTRACE(DBG_HISTORY, ("histedit: %cE%cV %sinteractive\n",
    104 	    Eflag ? '-' : '+',  Vflag ? '-' : '+', iflag ? "" : "not "));
    105 
    106 	if (iflag == 1) {
    107 		if (!hist) {
    108 			/*
    109 			 * turn history on
    110 			 */
    111 			INTOFF;
    112 			hist = history_init();
    113 			INTON;
    114 
    115 			if (hist != NULL)
    116 				sethistsize(histsizeval(), histsizeflags());
    117 			else
    118 				out2str("sh: can't initialize history\n");
    119 		}
    120 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
    121 			/*
    122 			 * turn editing on
    123 			 */
    124 			char *term;
    125 
    126 			INTOFF;
    127 			if (el_in == NULL)
    128 				el_in = fdopen(0, "r");
    129 			if (el_out == NULL)
    130 				el_out = fdopen(2, "w");
    131 			if (el_in == NULL || el_out == NULL)
    132 				goto bad;
    133 			el_err = el_out;
    134 #if DEBUG
    135 			if (tracefile)
    136 				el_err = tracefile;
    137 #endif
    138 			/*
    139 			 * This odd piece of code doesn't affect the shell
    140 			 * at all, the environment modified here is the
    141 			 * stuff accessed via "environ" (the incoming
    142 			 * environment to the shell) which is only ever
    143 			 * touched at sh startup time (long before we get
    144 			 * here) and ignored thereafter.
    145 			 *
    146 			 * But libedit calls getenv() to discover TERM
    147 			 * and that searches the "environ" environment,
    148 			 * not the shell's internal variable data struct,
    149 			 * so we need to make sure that TERM in there is
    150 			 * correct.
    151 			 *
    152 			 * This sequence copies TERM from the shell into
    153 			 * the old "environ" environment.
    154 			 */
    155 			term = lookupvar("TERM");
    156 			if (term)
    157 				setenv("TERM", term, 1);
    158 			else
    159 				unsetenv("TERM");
    160 			el = el_init("sh", el_in, el_out, el_err);
    161 			VTRACE(DBG_HISTORY, ("el_init() %sed\n",
    162 			    el != NULL ? "succeed" : "fail"));
    163 			if (el != NULL) {
    164 				if (hist)
    165 					el_set(el, EL_HIST, history, hist);
    166 
    167 				set_prompt_lit(lookupvar("PSlit"), 0);
    168 				el_set(el, EL_SIGNAL, 1);
    169 				el_set(el, EL_SAFEREAD, 1);
    170 				el_set(el, EL_ALIAS_TEXT, alias_text, NULL);
    171 				el_set(el, EL_ADDFN, "rl-complete",
    172 				    "ReadLine compatible completion function",
    173 				    sh_complete);
    174 			} else {
    175  bad:;
    176 				out2str("sh: can't initialize editing\n");
    177 			}
    178 			INTON;
    179 		} else if (!editing && el) {
    180 			INTOFF;
    181 			el_end(el);
    182 			el = NULL;
    183 			VTRACE(DBG_HISTORY, ("line editing disabled\n"));
    184 			INTON;
    185 		}
    186 		if (el) {
    187 			INTOFF;
    188 			if (Vflag)
    189 				el_set(el, EL_EDITOR, "vi");
    190 			else if (Eflag)
    191 				el_set(el, EL_EDITOR, "emacs");
    192 			VTRACE(DBG_HISTORY, ("reading $EDITRC\n"));
    193 			el_source(el, lookupvar("EDITRC"));
    194 			el_set(el, EL_BIND, "^I",
    195 			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
    196 			INTON;
    197 		}
    198 	} else {
    199 		INTOFF;
    200 		if (el) {	/* no editing if not interactive */
    201 			el_end(el);
    202 			el = NULL;
    203 		}
    204 		if (hist) {
    205 			history_end(hist);
    206 			hist = NULL;
    207 		}
    208 		INTON;
    209 		VTRACE(DBG_HISTORY, ("line editing & history disabled\n"));
    210 	}
    211 }
    212 
    213 void
    214 set_prompt_lit(char *lit_ch, int flags __unused)
    215 {
    216 	wchar_t wc;
    217 
    218 	if (!(iflag && editing && el))
    219 		return;
    220 
    221 	if (lit_ch == NULL) {
    222 		el_set(el, EL_PROMPT, getprompt);
    223 		return;
    224 	}
    225 
    226 	mbtowc(&wc, NULL, 1);		/* state init */
    227 
    228 	INTOFF;
    229 	if (mbtowc(&wc, lit_ch, strlen(lit_ch)) <= 0)
    230 		el_set(el, EL_PROMPT, getprompt);
    231 	else
    232 		el_set(el, EL_PROMPT_ESC, getprompt, (int)wc);
    233 	INTON;
    234 }
    235 
    236 void
    237 set_editrc(char *fname, int flags)
    238 {
    239 	INTOFF;
    240 	if (iflag && editing && el && !(flags & VUNSET))
    241 		el_source(el, fname);
    242 	INTON;
    243 }
    244 
    245 void
    246 sethistsize(char *hs, int flags)
    247 {
    248 	int histsize;
    249 	HistEvent he;
    250 
    251 	CTRACE(DBG_HISTORY, ("Set HISTSIZE=%s [%x] %s\n",
    252 	    (hs == NULL ? "''" : hs), flags, "!hist" + (hist != NULL)));
    253 
    254 	if (hs != NULL && *hs != '\0' && (flags & VUNSAFE) && !is_number(hs))
    255 		hs = NULL;
    256 
    257 	if (hs == NULL || *hs == '\0' || (flags & VUNSET) ||
    258 	    (histsize = number(hs)) < 0)
    259 		histsize = 100;
    260 
    261 	if (hist != NULL) {
    262 		INTOFF;
    263 		history(hist, &he, H_SETSIZE, histsize);
    264 		history(hist, &he, H_SETUNIQUE, 1);
    265 		INTON;
    266 	}
    267 }
    268 
    269 void
    270 setterm(char *term, int flags __unused)
    271 {
    272 	INTOFF;
    273 	if (el != NULL && term != NULL && *term != '\0')
    274 		if (el_set(el, EL_TERMINAL, term) != 0) {
    275 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
    276 			outfmt(out2, "sh: Using dumb terminal settings.\n");
    277 		}
    278 	INTON;
    279 }
    280 
    281 int
    282 inputrc(int argc, char **argv)
    283 {
    284 	CTRACE(DBG_HISTORY, ("inputrc (%d arg%s)", argc-1, argc==2?"":"s"));
    285 	if (argc != 2) {
    286 		CTRACE(DBG_HISTORY, (" -- bad\n"));
    287 		out2str("usage: inputrc file\n");
    288 		return 1;
    289 	}
    290 	CTRACE(DBG_HISTORY, (" file: \"%s\"\n", argv[1]));
    291 	if (el != NULL) {
    292 		INTOFF;
    293 		if (el_source(el, argv[1])) {
    294 			INTON;
    295 			out2str("inputrc: failed\n");
    296 			return 1;
    297 		}
    298 		INTON;
    299 		return 0;
    300 	} else {
    301 		out2str("sh: inputrc ignored, not editing\n");
    302 		return 1;
    303 	}
    304 }
    305 
    306 /*
    307  *  This command is provided since POSIX decided to standardize
    308  *  the Korn shell fc command.  Oh well...
    309  */
    310 int
    311 histcmd(volatile int argc, char ** volatile argv)
    312 {
    313 	int ch;
    314 	const char * volatile editor = NULL;
    315 	HistEvent he;
    316 	volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
    317 	int i, retval;
    318 	const char *firststr, *laststr;
    319 	int first, last, direction;
    320 
    321 	char * volatile pat = NULL;	/* ksh "fc old=new" crap */
    322 	char * volatile repl;
    323 
    324 	static int active = 0;
    325 	struct jmploc jmploc;
    326 	struct jmploc *volatile savehandler;
    327 	char editfile[MAXPATHLEN + 1];
    328 	FILE * volatile efp;
    329 
    330 #ifdef __GNUC__
    331 	repl = NULL;	/* XXX gcc4 */
    332 	efp = NULL;	/* XXX gcc4 */
    333 #endif
    334 
    335 	if (hist == NULL)
    336 		error("history not active");
    337 
    338 	CTRACE(DBG_HISTORY, ("histcmd (fc) %d arg%s\n", argc, argc==1?"":"s"));
    339 	if (argc == 1)
    340 		error("missing history argument");
    341 
    342 	optreset = 1; optind = 1; /* initialize getopt */
    343 	while (not_fcnumber(argv[optind]) &&
    344 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
    345 		switch ((char)ch) {
    346 		case 'e':
    347 			editor = optarg;
    348 			VTRACE(DBG_HISTORY, ("histcmd -e %s\n", editor));
    349 			break;
    350 		case 'l':
    351 			lflg = 1;
    352 			VTRACE(DBG_HISTORY, ("histcmd -l\n"));
    353 			break;
    354 		case 'n':
    355 			nflg = 1;
    356 			VTRACE(DBG_HISTORY, ("histcmd -n\n"));
    357 			break;
    358 		case 'r':
    359 			rflg = 1;
    360 			VTRACE(DBG_HISTORY, ("histcmd -r\n"));
    361 			break;
    362 		case 's':
    363 			sflg = 1;
    364 			VTRACE(DBG_HISTORY, ("histcmd -s\n"));
    365 			break;
    366 		case ':':
    367 			error("option -%c expects argument", optopt);
    368 			/* NOTREACHED */
    369 		case '?':
    370 		default:
    371 			error("unknown option: -%c", optopt);
    372 			/* NOTREACHED */
    373 		}
    374 	argc -= optind, argv += optind;
    375 
    376 	/*
    377 	 * If executing...
    378 	 */
    379 	if (lflg == 0 || editor || sflg) {
    380 		lflg = 0;	/* ignore */
    381 		editfile[0] = '\0';
    382 		/*
    383 		 * Catch interrupts to reset active counter and
    384 		 * cleanup temp files.
    385 		 */
    386 		savehandler = handler;
    387 		if (setjmp(jmploc.loc)) {
    388 			active = 0;
    389 			if (*editfile) {
    390 				VTRACE(DBG_HISTORY,
    391 				    ("histcmd err jump unlink temp \"%s\"\n",
    392 				    editfile));
    393 				unlink(editfile);
    394 			}
    395 			handler = savehandler;
    396 			longjmp(handler->loc, 1);
    397 		}
    398 		handler = &jmploc;
    399 		VTRACE(DBG_HISTORY, ("histcmd is active %d(++)\n", active));
    400 		if (++active > MAXHISTLOOPS) {
    401 			active = 0;
    402 			displayhist = 0;
    403 			error("called recursively too many times");
    404 		}
    405 		/*
    406 		 * Set editor.
    407 		 */
    408 		if (sflg == 0) {
    409 			if (editor == NULL &&
    410 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
    411 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
    412 				editor = DEFEDITOR;
    413 			if (editor[0] == '-' && editor[1] == '\0') {
    414 				sflg = 1;	/* no edit */
    415 				editor = NULL;
    416 			}
    417 			VTRACE(DBG_HISTORY, ("histcmd using %s as editor\n",
    418 			    editor == NULL ? "-nothing-" : editor));
    419 		}
    420 	}
    421 
    422 	/*
    423 	 * If executing, parse [old=new] now
    424 	 */
    425 	if (lflg == 0 && argc > 0 &&
    426 	     ((repl = strchr(argv[0], '=')) != NULL)) {
    427 		pat = argv[0];
    428 		*repl++ = '\0';
    429 		argc--, argv++;
    430 		VTRACE(DBG_HISTORY, ("histcmd replace old=\"%s\" new=\"%s\""
    431 		    " (%d args)\n", pat, repl, argc));
    432 	}
    433 
    434 	/*
    435 	 * If -s is specified, accept only one operand
    436 	 */
    437 	if (sflg && argc >= 2)
    438 		error("too many args");
    439 
    440 	/*
    441 	 * determine [first] and [last]
    442 	 */
    443 	switch (argc) {
    444 	case 0:
    445 		if (lflg) {
    446 			firststr = "-16";
    447 			laststr = "-1";
    448 		} else
    449 			firststr = laststr = "-1";
    450 		break;
    451 	case 1:
    452 		firststr = argv[0];
    453 		laststr = lflg ? "-1" : argv[0];
    454 		break;
    455 	case 2:
    456 		firststr = argv[0];
    457 		laststr = argv[1];
    458 		break;
    459 	default:
    460 		error("too many args");
    461 		/* NOTREACHED */
    462 	}
    463 	/*
    464 	 * Turn into event numbers.
    465 	 */
    466 	first = str_to_event(firststr, 0);
    467 	last = str_to_event(laststr, 1);
    468 
    469 	if (first == -1 || last == -1) {
    470 		if (lflg)   /* no history exists, that's OK */
    471 			return 0;
    472 		if (first == -1 && last == -1) {
    473 			if (firststr != laststr)
    474 				error("history events %s to %s do not exist",
    475 				    firststr, laststr);
    476 			else
    477 				error("history event %s does not exist",
    478 				    firststr);
    479 		} else {
    480 			error("history event %s does not exist",
    481 			    first == -1 ? firststr : laststr);
    482 		}
    483 	}
    484 
    485 	if (rflg) {
    486 		i = last;
    487 		last = first;
    488 		first = i;
    489 	}
    490 	VTRACE(DBG_HISTORY, ("histcmd%s first=\"%s\" (#%d) last=\"%s\" (#%d)\n",
    491 	    rflg ? " reversed" : "", rflg ? laststr : firststr, first,
    492 	    rflg ? firststr : laststr, last));
    493 
    494 	/*
    495 	 * XXX - this should not depend on the event numbers
    496 	 * always increasing.  Add sequence numbers or offset
    497 	 * to the history element in next (diskbased) release.
    498 	 */
    499 	direction = first < last ? H_PREV : H_NEXT;
    500 
    501 	/*
    502 	 * If editing, grab a temp file.
    503 	 */
    504 	if (editor) {
    505 		int fd;
    506 
    507 		INTOFF;		/* easier */
    508 		snprintf(editfile, sizeof(editfile),
    509 		    "%s_shXXXXXX", _PATH_TMP);
    510 		if ((fd = mkstemp(editfile)) < 0)
    511 			error("can't create temporary file %s", editfile);
    512 		if ((efp = fdopen(fd, "w")) == NULL) {
    513 			close(fd);
    514 			error("can't allocate stdio buffer for temp");
    515 		}
    516 		VTRACE(DBG_HISTORY, ("histcmd created \"%s\" for edit buffer"
    517 		    " fd=%d\n", editfile, fd));
    518 	}
    519 
    520 	/*
    521 	 * Loop through selected history events.  If listing or executing,
    522 	 * do it now.  Otherwise, put into temp file and call the editor
    523 	 * after.
    524 	 *
    525 	 * The history interface needs rethinking, as the following
    526 	 * convolutions will demonstrate.
    527 	 */
    528 	history(hist, &he, H_FIRST);
    529 	retval = history(hist, &he, H_NEXT_EVENT, first);
    530 	for ( ; retval != -1; retval = history(hist, &he, direction)) {
    531 		if (lflg) {
    532 			if (!nflg)
    533 				out1fmt("%5d ", he.num);
    534 			out1str(he.str);
    535 		} else {
    536 			const char *s = pat ?
    537 			   fc_replace(he.str, pat, repl) : he.str;
    538 
    539 			if (sflg) {
    540 				VTRACE(DBG_HISTORY, ("histcmd -s \"%s\"\n", s));
    541 				if (displayhist) {
    542 					out2str(s);
    543 				}
    544 
    545 				evalstring(strcpy(stalloc(strlen(s)+1), s), 0);
    546 				if (displayhist && hist) {
    547 					/*
    548 					 *  XXX what about recursive and
    549 					 *  relative histnums.
    550 					 */
    551 					history(hist, &he, H_ENTER, s);
    552 				}
    553 
    554 				break;
    555 			} else
    556 				fputs(s, efp);
    557 		}
    558 		/*
    559 		 * At end?  (if we were to lose last, we'd sure be
    560 		 * messed up).
    561 		 */
    562 		if (he.num == last)
    563 			break;
    564 	}
    565 	if (editor) {
    566 		char *editcmd;
    567 		size_t cmdlen;
    568 
    569 		fclose(efp);
    570 		cmdlen = strlen(editor) + strlen(editfile) + 2;
    571 		editcmd = stalloc(cmdlen);
    572 		snprintf(editcmd, cmdlen, "%s %s", editor, editfile);
    573 		VTRACE(DBG_HISTORY, ("histcmd editing: \"%s\"\n", editcmd));
    574 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
    575 		stunalloc(editcmd);
    576 		VTRACE(DBG_HISTORY, ("histcmd read cmds from %s\n", editfile));
    577 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
    578 		VTRACE(DBG_HISTORY, ("histcmd unlink %s\n", editfile));
    579 		unlink(editfile);
    580 		editfile[0] = '\0';
    581 		INTON;
    582 	}
    583 
    584 	if (lflg == 0 && active > 0)
    585 		--active;
    586 	if (displayhist)
    587 		displayhist = 0;
    588 	return 0;
    589 }
    590 
    591 static const char *
    592 fc_replace(const char *s, char *p, char *r)
    593 {
    594 	char *dest;
    595 	int plen = strlen(p);
    596 
    597 	VTRACE(DBG_HISTORY, ("histcmd s/%s/%s/ in \"%s\" -> ", p, r, s));
    598 	STARTSTACKSTR(dest);
    599 	while (*s) {
    600 		if (*s == *p && strncmp(s, p, plen) == 0) {
    601 			while (*r)
    602 				STPUTC(*r++, dest);
    603 			s += plen;
    604 			*p = '\0';	/* so no more matches */
    605 		} else
    606 			STPUTC(*s++, dest);
    607 	}
    608 	STACKSTRNUL(dest);
    609 	dest = grabstackstr(dest);
    610 	VTRACE(DBG_HISTORY, ("\"%s\"\n", dest));
    611 
    612 	return dest;
    613 }
    614 
    615 
    616 /*
    617  * Comparator function for qsort(). The use of curpos here is to skip
    618  * characters that we already know to compare equal (common prefix).
    619  */
    620 static int
    621 comparator(const void *a, const void *b)
    622 {
    623 	return strcmp(*(char *const *)a + curpos,
    624 		*(char *const *)b + curpos);
    625 }
    626 
    627 /*
    628  * This function is passed to libedit's fn_complete(). The library will
    629  * use it instead of its standard function to find matches, which
    630  * searches for files in current directory. If we're at the start of the
    631  * line, we want to look for available commands from all paths in $PATH.
    632  */
    633 static char **
    634 sh_matches(const char *text, int start, int end)
    635 {
    636 	char *free_path = NULL, *dirname, *path;
    637 	char **matches = NULL;
    638 	size_t i = 0, size = 16;
    639 
    640 	if (start > 0)
    641 		return NULL;
    642 	curpos = end - start;
    643 	if ((free_path = path = strdup(pathval())) == NULL)
    644 		goto out;
    645 	if ((matches = malloc(size * sizeof(matches[0]))) == NULL)
    646 		goto out;
    647 	while ((dirname = strsep(&path, ":")) != NULL) {
    648 		struct dirent *entry;
    649 		DIR *dir;
    650 		int dfd;
    651 
    652 		if ((dir = opendir(dirname)) == NULL)
    653 			continue;
    654 		if ((dfd = dirfd(dir)) == -1)
    655 			continue;
    656 		while ((entry = readdir(dir)) != NULL) {
    657 			struct stat statb;
    658 
    659 			if (strncmp(entry->d_name, text, curpos) != 0)
    660 				continue;
    661 			if (entry->d_type == DT_UNKNOWN ||
    662 			    entry->d_type == DT_LNK) {
    663 				if (fstatat(dfd, entry->d_name, &statb, 0)
    664 				    == -1)
    665 					continue;
    666 				if (!S_ISREG(statb.st_mode))
    667 					continue;
    668 			} else if (entry->d_type != DT_REG)
    669 				continue;
    670 			if (++i >= size - 1) {
    671 				size *= 2;
    672 				if (reallocarr(&matches, size,
    673 				    sizeof(*matches)))
    674 				{
    675 					closedir(dir);
    676 					goto out;
    677 				}
    678 			}
    679 			matches[i] = strdup(entry->d_name);
    680 		}
    681 		closedir(dir);
    682 	}
    683  out:;
    684 	free(free_path);
    685 	if (i == 0) {
    686 		free(matches);
    687 		return NULL;
    688 	}
    689 	if (i == 1) {
    690 		matches[0] = strdup(matches[1]);
    691 		matches[i + 1] = NULL;
    692 	} else {
    693 		size_t j, k;
    694 
    695 		qsort(matches + 1, i, sizeof(matches[0]), comparator);
    696 		for (j = 1, k = 2; k <= i; k++)
    697 			if (strcmp(matches[j] + curpos, matches[k] + curpos)
    698 			    == 0)
    699 				free(matches[k]);
    700 			else
    701 				matches[++j] = matches[k];
    702 		matches[0] = strdup(text);
    703 		matches[j + 1] = NULL;
    704 	}
    705 	return matches;
    706 }
    707 
    708 /*
    709  * This is passed to el_set(el, EL_ADDFN, ...) so that it's possible to
    710  * bind a key (tab by default) to execute the function.
    711  */
    712 unsigned char
    713 sh_complete(EditLine *sel, int ch __unused)
    714 {
    715 	return (unsigned char)fn_complete2(sel, NULL, sh_matches,
    716 		L" \t\n\"\\'`@$><=;|&{(", NULL, NULL, (size_t)100,
    717 		NULL, &((int) {0}), NULL, NULL, FN_QUOTE_MATCH);
    718 }
    719 
    720 static int
    721 not_fcnumber(const char *s)
    722 {
    723 	if (s == NULL)
    724 		return 0;
    725 	if (*s == '-')
    726 		s++;
    727 	return !is_number(s);
    728 }
    729 
    730 static int
    731 str_to_event(const char *str, int last)
    732 {
    733 	HistEvent he;
    734 	const char *s = str;
    735 	int relative = 0;
    736 	int i, retval;
    737 
    738 	retval = history(hist, &he, H_FIRST);
    739 	switch (*s) {
    740 	case '-':
    741 		relative = 1;
    742 		/*FALLTHROUGH*/
    743 	case '+':
    744 		s++;
    745 	}
    746 	if (is_number(s)) {
    747 		i = number(s);
    748 		if (relative) {
    749 			while (retval != -1 && i--) {
    750 				retval = history(hist, &he, H_NEXT);
    751 			}
    752 			if (retval == -1)
    753 				retval = history(hist, &he, H_LAST);
    754 		} else {
    755 			retval = history(hist, &he, H_NEXT_EVENT, i);
    756 			if (retval == -1) {
    757 				/*
    758 				 * the notion of first and last is
    759 				 * backwards to that of the history package
    760 				 */
    761 				retval = history(hist, &he,
    762 						last ? H_FIRST : H_LAST);
    763 			}
    764 		}
    765 		if (retval == -1)
    766 			return -1;
    767 	} else {
    768 		/*
    769 		 * pattern
    770 		 */
    771 		retval = history(hist, &he, H_PREV_STR, str);
    772 		if (retval == -1)
    773 			error("history pattern not found: %s", str);
    774 	}
    775 	return he.num;
    776 }
    777 
    778 #else	/* defined(SMALL) */
    779 
    780 int
    781 histcmd(int argc, char **argv)
    782 {
    783 	error("not compiled with history support");
    784 	/* NOTREACHED */
    785 }
    786 
    787 int
    788 inputrc(int argc, char **argv)
    789 {
    790 	error("not compiled with history support");
    791 	/* NOTREACHED */
    792 }
    793 
    794 #endif	/* SMALL */
    795