Home | History | Annotate | Line # | Download | only in sh
      1 /*	$NetBSD: histedit.c,v 1.75 2026/08/15 10:35:46 christos 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.75 2026/08/15 10:35:46 christos Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <sys/param.h>
     45 #include <sys/stat.h>
     46 #include <dirent.h>
     47 #include <errno.h>
     48 #include <fcntl.h>
     49 #include <paths.h>
     50 #include <stdio.h>
     51 #include <stdlib.h>
     52 #include <unistd.h>
     53 /*
     54  * Editline and history functions (and glue).
     55  */
     56 #include "shell.h"
     57 #include "parser.h"
     58 #include "var.h"
     59 #include "options.h"
     60 #include "builtins.h"
     61 #include "main.h"
     62 #include "output.h"
     63 #include "mystring.h"
     64 #include "myhistedit.h"
     65 #include "error.h"
     66 #include "alias.h"
     67 #include "redir.h"
     68 
     69 #ifndef SMALL		/* almost all the rest of this file */
     70 
     71 #include "eval.h"
     72 #include "memalloc.h"
     73 #include "show.h"
     74 
     75 #define MAXHISTLOOPS	4	/* max recursions through fc */
     76 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
     77 
     78 History *hist;	/* history cookie */
     79 EditLine *el;	/* editline cookie */
     80 int displayhist;
     81 static FILE *el_in, *el_out;
     82 static int curpos;
     83 
     84 static char *HistFile = NULL;
     85 static const char *HistFileOpen = NULL;
     86 FILE *HistFP = NULL;
     87 static int History_fd;
     88 
     89 #ifdef DEBUG
     90 extern FILE *tracefile;
     91 #endif
     92 
     93 static const char *fc_replace(const char *, char *, char *);
     94 static int not_fcnumber(const char *);
     95 static int str_to_event(const char *, int);
     96 static int comparator(const void *, const void *);
     97 static char **sh_matches(const char *, int, int);
     98 static unsigned char sh_complete(EditLine *, int);
     99 static FILE *Hist_File_Open(const char *);
    100 
    101 /*
    102  * a getenv(3) lookalike function for libedit to
    103  * use so it can access current values of sh variables
    104  * so there is no need to keep doing setenv() of anything
    105  * it might want to lookup.
    106  */
    107 static char *
    108 el_getenv(const char *name)
    109 {
    110 	return bltinlookup(name, 1);
    111 }
    112 
    113 /*
    114  * Set history and editing status.  Called whenever the status may
    115  * have changed (figures out what to do).
    116  */
    117 void
    118 histedit(void)
    119 {
    120 	FILE *el_err;
    121 
    122 #define editing (Eflag || Vflag)
    123 
    124 	CTRACE(DBG_HISTORY, ("histedit: %cE%cV %sinteractive\n",
    125 	    Eflag ? '-' : '+',  Vflag ? '-' : '+', iflag ? "" : "not "));
    126 
    127 	if (iflag == 1) {
    128 		if (!hist) {
    129 			/*
    130 			 * turn history on
    131 			 */
    132 			INTOFF;
    133 			hist = history_init();
    134 			INTON;
    135 
    136 			if (hist != NULL) {
    137 				sethistsize(histsizeval(),
    138 				    histsizeflags(), NULL);
    139 				sethistfile(histfileval(),
    140 				    histfileflags(), NULL);
    141 			} else
    142 				out2str("sh: can't initialize history\n");
    143 		}
    144 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
    145 			/*
    146 			 * turn editing on
    147 			 */
    148 			INTOFF;
    149 			if (el_in == NULL)
    150 				el_in = fdopen(0, "r");
    151 			if (el_out == NULL)
    152 				el_out = fdopen(2, "w");
    153 			if (el_in == NULL || el_out == NULL)
    154 				goto bad;
    155 			el_err = el_out;
    156 #if DEBUG
    157 			if (tracefile)
    158 				el_err = tracefile;
    159 #endif
    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, NULL);
    168 
    169 				el_set(el, EL_GETENV, el_getenv);
    170 				el_set(el, EL_SIGNAL, 1);
    171 				el_set(el, EL_SAFEREAD, 1);
    172 				el_set(el, EL_ALIAS_TEXT, alias_text, NULL);
    173 				el_set(el, EL_ADDFN, "rl-complete",
    174 				    "ReadLine compatible completion function",
    175 				    sh_complete);
    176 			} else {
    177  bad:;
    178 				out2str("sh: can't initialize editing\n");
    179 			}
    180 			INTON;
    181 		} else if (!editing && el) {
    182 			INTOFF;
    183 			el_end(el);
    184 			el = NULL;
    185 			VTRACE(DBG_HISTORY, ("line editing disabled\n"));
    186 			INTON;
    187 		}
    188 		if (el) {
    189 			INTOFF;
    190 			if (Vflag)
    191 				el_set(el, EL_EDITOR, "vi");
    192 			else if (Eflag)
    193 				el_set(el, EL_EDITOR, "emacs");
    194 			VTRACE(DBG_HISTORY, ("reading $EDITRC\n"));
    195 			el_source(el, lookupvar("EDITRC"));
    196 			el_set(el, EL_BIND, "^I",
    197 			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
    198 			el_set(el, EL_MATCH_HIDDEN_FILES, dotglob);
    199 			INTON;
    200 		}
    201 	} else {
    202 		INTOFF;
    203 		if (el) {	/* no editing if not interactive */
    204 			el_end(el);
    205 			el = NULL;
    206 		}
    207 		if (hist) {
    208 			history_end(hist);
    209 			hist = NULL;
    210 		}
    211 		INTON;
    212 		VTRACE(DBG_HISTORY, ("line editing & history disabled\n"));
    213 	}
    214 }
    215 
    216 void
    217 set_prompt_lit(const char *lit_ch, int flags, struct var *vp __unused)
    218 {
    219 	wchar_t wc;
    220 
    221 	if (!(iflag && editing && el))
    222 		return;
    223 
    224 	if (lit_ch == NULL) {
    225 		el_set(el, EL_PROMPT, getprompt);
    226 		return;
    227 	}
    228 
    229 	mbtowc(&wc, NULL, 1);		/* state init */
    230 
    231 	INTOFF;
    232 	if ((flags & VUNSET) || mbtowc(&wc, lit_ch, strlen(lit_ch)) <= 0)
    233 		el_set(el, EL_PROMPT, getprompt);
    234 	else
    235 		el_set(el, EL_PROMPT_ESC, getprompt, (int)wc);
    236 	INTON;
    237 }
    238 
    239 void
    240 set_editrc(const char *fname, int flags, struct var *vp __unused)
    241 {
    242 	INTOFF;
    243 	if (iflag && editing && el && !(flags & VUNSET))
    244 		el_source(el, fname);
    245 	INTON;
    246 }
    247 
    248 void
    249 sethistsize(const char *hs, int flags, struct var *vp __unused)
    250 {
    251 	int histsize;
    252 	HistEvent he;
    253 
    254 	CTRACE(DBG_HISTORY, ("Set HISTSIZE=%s [%x] %s\n",
    255 	    (hs == NULL ? "''" : hs), flags, "!hist" + (hist != NULL)));
    256 
    257 	if (hs != NULL && *hs != '\0' && (flags & VUNSAFE) && !is_number(hs))
    258 		hs = NULL;
    259 
    260 	if (hs == NULL || *hs == '\0' || (flags & VUNSET) ||
    261 	    (histsize = number(hs)) < 0)
    262 		histsize = 100;
    263 
    264 	if (hist != NULL) {
    265 		INTOFF;
    266 		/* H_SETSIZE actually sets n-1 as the limit */
    267 		history(hist, &he, H_SETSIZE, histsize + 1);
    268 		history(hist, &he, H_SETUNIQUE, 1);
    269 		INTON;
    270 	}
    271 }
    272 
    273 void
    274 sethistfile(const char *hs, int flags, struct var *vp __unused)
    275 {
    276 	const char *file;
    277 	HistEvent he;
    278 
    279 	CTRACE(DBG_HISTORY, ("Set HISTFILE=%s [%x] %s\n",
    280 	    (hs == NULL ? "''" : hs), flags, "!hist" + (hist != NULL)));
    281 
    282 	if (hs == NULL || *hs == '\0' || (flags & VUNSET)) {
    283 		if (HistFP != NULL) {
    284 			fclose(HistFP);
    285 			HistFP = NULL;
    286 		}
    287 		if (HistFile != NULL) {
    288 			free(HistFile);
    289 			HistFile = NULL;
    290 			HistFileOpen = NULL;
    291 		}
    292 		return;
    293 	}
    294 
    295 	if (hist != NULL) {
    296 		file = expandvar(hs, flags);
    297 		if (file == NULL || *file == '\0')
    298 			return;
    299 
    300 		INTOFF;
    301 
    302 		history(hist, &he, H_LOAD, file);
    303 
    304 		/*
    305 		 * This is needed so sethistappend() can work
    306 		 * on the current (new) filename, not the previous one.
    307 		 */
    308 		if (HistFile != NULL)
    309 			free(HistFile);
    310 
    311 		HistFile = strdup(hs);
    312 		/*
    313 		 * We need to ensure that HistFile & HistFileOpen
    314 		 * are not equal .. we know HistFile has just altered.
    315 		 * If they happen to be equal (both NULL perhaps, or
    316 		 * the strdup() just above happned to return the same
    317 		 * buffer as was freed the line before) then simply
    318 		 * set HistFileOpen to something which cannot be the
    319 		 * same as anything allocated, or NULL.   Its only
    320 		 * use is to compare against HistFile.
    321 		 */
    322 		if (HistFile == HistFileOpen)
    323 			HistFileOpen = "";
    324 
    325 		sethistappend((histappflags() & VUNSET) ? NULL : histappval(),
    326 			~VUNSET & 0xFFFF, NULL);
    327 
    328 		INTON;
    329 	}
    330 }
    331 
    332 void
    333 sethistappend(const char *s, int flags, struct var *vp __unused)
    334 {
    335 	CTRACE(DBG_HISTORY, ("Set HISTAPPEND=%s [%x] %s ",
    336 	    (s == NULL ? "''" : s), flags, "!hist" + (hist != NULL)));
    337 
    338 	INTOFF;
    339 	if (flags & VUNSET || !boolstr(s)) {
    340 		CTRACE(DBG_HISTORY, ("off"));
    341 
    342 		if (HistFP != NULL) {
    343 			CTRACE(DBG_HISTORY, (" closing"));
    344 
    345 			fclose(HistFP);
    346 			HistFP = NULL;
    347 			HistFileOpen = NULL;
    348 		}
    349 	} else {
    350 		CTRACE(DBG_HISTORY, ("on"));
    351 
    352 		if (HistFileOpen != HistFile || HistFP == NULL) {
    353 			if (HistFP != NULL) {
    354 				CTRACE(DBG_HISTORY, (" closing prev"));
    355 				fclose(HistFP);
    356 				HistFP = NULL;
    357 			}
    358 			if (hist != NULL &&
    359 			    HistFile != NULL &&
    360 			    HistFP == NULL) {
    361 				CTRACE(DBG_HISTORY, ("\n"));
    362 
    363 				save_sh_history();
    364 
    365 				CTRACE(DBG_HISTORY, ("opening: "));
    366 
    367 				HistFP = Hist_File_Open(HistFile);
    368 				if (HistFP != NULL)
    369 					HistFileOpen = HistFile;
    370 				else {
    371 					CTRACE(DBG_HISTORY, ("open failed"));
    372 				}
    373 			}
    374 		}
    375 	}
    376 	INTON;
    377 
    378 	CTRACE(DBG_HISTORY, ("\n"));
    379 }
    380 
    381 static void
    382 History_FD_Renumbered(int from, int to)
    383 {
    384 	if (History_fd == from)
    385 		History_fd = to;
    386 
    387 	VTRACE(DBG_HISTORY, ("History_FD_Renumbered(%d,%d)-> %d\n",
    388 	    from, to, History_fd));
    389 }
    390 
    391 /*
    392  * The callback functions for the FILE* returned by funopen2()
    393  */
    394 static ssize_t
    395 Hist_Write(void *cookie, const void *buf, size_t len)
    396 {
    397 	if (cookie != (void *)&History_fd) {
    398 		errno = EINVAL;
    399 		return -1;
    400 	}
    401 
    402 	return write(History_fd, buf, len);
    403 }
    404 
    405 static int
    406 Hist_Close(void *cookie)
    407 {
    408 	if (cookie == (void *)&History_fd) {
    409 		sh_close(History_fd);
    410 		History_fd = -1;
    411 		return 0;
    412 	}
    413 
    414 	VTRACE(DBG_HISTORY, ("HistClose(%p) != %p\n", cookie, &History_fd));
    415 
    416 	errno = EINVAL;
    417 	return -1;
    418 }
    419 
    420 static off_t
    421 Hist_Seek(void *cookie, off_t pos, int whence)
    422 {
    423 	if (cookie != (void *)&History_fd) {
    424 		errno = EINVAL;
    425 		return -1;
    426 	}
    427 
    428 	return lseek(History_fd, pos, whence);
    429 }
    430 
    431 /*
    432  * a variant of open() for history files.
    433  */
    434 static int
    435 open_history_file(const char *name, int mode)
    436 {
    437 	int fd;
    438 	struct stat statb;
    439 
    440 	fd = open(name, mode, S_IWUSR|S_IRUSR);
    441 
    442 	VTRACE(DBG_HISTORY, ("open_history_file(\"%s\", %#x) -> %d\n",
    443 	    name, mode, fd));
    444 
    445 	if (fd == -1)
    446 		return -1;
    447 
    448 	if (fstat(fd, &statb) == -1) {
    449 		VTRACE(DBG_HISTORY, ("history file fstat(%d) failed [%d]\n",
    450 		    fd, errno));
    451 		close(fd);
    452 		return -1;
    453 	}
    454 
    455 	if (statb.st_uid != getuid()) {
    456 		VTRACE(DBG_HISTORY,
    457 		    ("history file wrong user (uid=%d file=%d)\n",
    458 			getuid(), statb.st_uid));
    459 		close(fd);
    460 		return -1;
    461 	}
    462 
    463 	return fd;
    464 }
    465 
    466 static FILE *
    467 Hist_File_Open(const char *name)
    468 {
    469 	FILE *fd;
    470 	int n;
    471 
    472 	INTOFF;
    473 
    474 	n = open_history_file(name, O_WRONLY|O_CREAT|O_APPEND|O_CLOEXEC);
    475 
    476 	VTRACE(DBG_HISTORY, ("History_File_Open(\"%s\") -> %d", name, n));
    477 	if (n == -1) {
    478 		VTRACE(DBG_HISTORY, (" [%d]\n", errno));
    479 		INTON;
    480 		return NULL;
    481 	}
    482 
    483 	n = to_upper_fd(n);
    484 	(void) lseek(n, 0, SEEK_END);
    485 	VTRACE(DBG_HISTORY, (" -> %d", n));
    486 
    487 	History_fd = n;
    488 	register_sh_fd(n, History_FD_Renumbered);
    489 
    490 	if ((fd =
    491 	    funopen2(&History_fd, NULL, Hist_Write, Hist_Seek, NULL,
    492 		     Hist_Close)) == NULL) {
    493 
    494 		VTRACE(DBG_HISTORY, ("; funopen2 failed[%d]\n", errno));
    495 
    496 		sh_close(n);
    497 		History_fd = -1;
    498 		INTON;
    499 		return NULL;
    500 	}
    501 	setlinebuf(fd);
    502 
    503 	VTRACE(DBG_HISTORY, (" fd:%p\n", fd));
    504 
    505 	INTON;
    506 
    507 	return fd;
    508 }
    509 
    510 void
    511 save_sh_history(void)
    512 {
    513 	char *var;
    514 	const char *file;
    515 	int fd;
    516 	FILE *fp;
    517 	HistEvent he;
    518 
    519 	if (HistFP != NULL) {
    520 		/* don't close, just make sure nothing in buffer */
    521 		(void) fflush(HistFP);
    522 		return;
    523 	}
    524 
    525 	if (hist == NULL)
    526 		return;
    527 
    528 	var = histfileval();
    529 	if ((histfileflags() & VUNSET) || *var == '\0')
    530 		return;
    531 
    532 	file = expandvar(var, histfileflags());
    533 
    534 	VTRACE(DBG_HISTORY,
    535 	    ("save_sh_history('%s')\n", file == NULL ? "" : file));
    536 
    537 	if (file == NULL || *file == '\0')
    538 		return;
    539 
    540 	INTOFF;
    541 	fd = open_history_file(file, O_WRONLY|O_CREAT|O_TRUNC);
    542 	if (fd != -1) {
    543 		fp = fdopen(fd, "w");
    544 		if (fp != NULL) {
    545 			(void) history(hist, &he, H_SAVE_FP, fp);
    546 			fclose(fp);
    547 		} else
    548 			close(fd);
    549 	}
    550 	INTON;
    551 }
    552 
    553 void
    554 setterm(const char *term, int flags __unused, struct var *vp __unused)
    555 {
    556 	INTOFF;
    557 	if (el != NULL && term != NULL && *term != '\0')
    558 		if (el_set(el, EL_TERMINAL, term) != 0) {
    559 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
    560 			outfmt(out2, "sh: Using dumb terminal settings.\n");
    561 		}
    562 	INTON;
    563 }
    564 
    565 /*
    566  * The built-in sh commands supported by this file
    567  */
    568 int
    569 inputrc(int argc, char **argv)
    570 {
    571 	CTRACE(DBG_HISTORY, ("inputrc (%d arg%s)", argc-1, argc==2?"":"s"));
    572 	if (argc != 2) {
    573 		CTRACE(DBG_HISTORY, (" -- bad\n"));
    574 		out2str("usage: inputrc file\n");
    575 		return 1;
    576 	}
    577 	CTRACE(DBG_HISTORY, (" file: \"%s\"\n", argv[1]));
    578 	if (el != NULL) {
    579 		INTOFF;
    580 		if (el_source(el, argv[1])) {
    581 			INTON;
    582 			out2str("inputrc: failed\n");
    583 			return 1;
    584 		}
    585 		INTON;
    586 		return 0;
    587 	} else {
    588 		out2str("sh: inputrc ignored, not editing\n");
    589 		return 1;
    590 	}
    591 }
    592 
    593 /*
    594  *  This command is provided since POSIX decided to standardize
    595  *  the Korn shell fc command.  Oh well...
    596  */
    597 int
    598 histcmd(volatile int argc, char ** volatile argv)
    599 {
    600 	int ch;
    601 	const char * volatile editor = NULL;
    602 	HistEvent he;
    603 	volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0, zflg = 0;
    604 	int i, retval;
    605 	const char *firststr, *laststr;
    606 	int first, last, direction;
    607 
    608 	char * volatile pat = NULL;	/* ksh "fc old=new" crap */
    609 	char * volatile repl;
    610 
    611 	static int active = 0;
    612 	struct jmploc jmploc;
    613 	struct jmploc *volatile savehandler;
    614 	char editfile[MAXPATHLEN + 1];
    615 	FILE * volatile efp;
    616 
    617 #ifdef __GNUC__
    618 	repl = NULL;	/* XXX gcc4 */
    619 	efp = NULL;	/* XXX gcc4 */
    620 #endif
    621 
    622 	if (hist == NULL)
    623 		error("history not active");
    624 
    625 	CTRACE(DBG_HISTORY, ("histcmd (fc) %d arg%s\n", argc, argc==1?"":"s"));
    626 	if (argc == 1)
    627 		error("missing history argument");
    628 
    629 	optreset = 1; optind = 1; /* initialize getopt */
    630 	while (not_fcnumber(argv[optind]) &&
    631 	      (ch = getopt(argc, argv, ":e:lnrsz")) != -1)
    632 		switch ((char)ch) {
    633 		case 'e':
    634 			editor = optarg;
    635 			VTRACE(DBG_HISTORY, ("histcmd -e %s\n", editor));
    636 			break;
    637 		case 'l':
    638 			lflg = 1;
    639 			VTRACE(DBG_HISTORY, ("histcmd -l\n"));
    640 			break;
    641 		case 'n':
    642 			nflg = 1;
    643 			VTRACE(DBG_HISTORY, ("histcmd -n\n"));
    644 			break;
    645 		case 'r':
    646 			rflg = 1;
    647 			VTRACE(DBG_HISTORY, ("histcmd -r\n"));
    648 			break;
    649 		case 's':
    650 			sflg = 1;
    651 			VTRACE(DBG_HISTORY, ("histcmd -s\n"));
    652 			break;
    653 		case 'z':
    654 			zflg = 1;
    655 			VTRACE(DBG_HISTORY, ("histcmd -z\n"));
    656 			break;
    657 		case ':':
    658 			error("option -%c expects argument", optopt);
    659 			/* NOTREACHED */
    660 		case '?':
    661 		default:
    662 			error("unknown option: -%c", optopt);
    663 			/* NOTREACHED */
    664 		}
    665 	argc -= optind, argv += optind;
    666 
    667 	if (zflg) {
    668 		if (argc != 0 || (lflg|nflg|rflg|sflg) != 0)
    669 			error("Usage: fc -z");
    670 
    671 		history(hist, &he, H_CLEAR);
    672 		return 0;
    673 	}
    674 
    675 
    676 	/*
    677 	 * If executing...
    678 	 */
    679 	if (lflg == 0 || editor || sflg) {
    680 		lflg = 0;	/* ignore */
    681 		editfile[0] = '\0';
    682 		/*
    683 		 * Catch interrupts to reset active counter and
    684 		 * cleanup temp files.
    685 		 */
    686 		savehandler = handler;
    687 		if (setjmp(jmploc.loc)) {
    688 			active = 0;
    689 			if (*editfile) {
    690 				VTRACE(DBG_HISTORY,
    691 				    ("histcmd err jump unlink temp \"%s\"\n",
    692 				    editfile));
    693 				unlink(editfile);
    694 			}
    695 			handler = savehandler;
    696 			longjmp(handler->loc, 1);
    697 		}
    698 		handler = &jmploc;
    699 		VTRACE(DBG_HISTORY, ("histcmd is active %d(++)\n", active));
    700 		if (++active > MAXHISTLOOPS) {
    701 			active = 0;
    702 			displayhist = 0;
    703 			error("called recursively too many times");
    704 		}
    705 		/*
    706 		 * Set editor.
    707 		 */
    708 		if (sflg == 0) {
    709 			if (editor == NULL &&
    710 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
    711 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
    712 				editor = DEFEDITOR;
    713 			if (editor[0] == '-' && editor[1] == '\0') {
    714 				sflg = 1;	/* no edit */
    715 				editor = NULL;
    716 			}
    717 			VTRACE(DBG_HISTORY, ("histcmd using %s as editor\n",
    718 			    editor == NULL ? "-nothing-" : editor));
    719 		}
    720 	}
    721 
    722 	/*
    723 	 * If executing, parse [old=new] now
    724 	 */
    725 	if (lflg == 0 && argc > 0 &&
    726 	     ((repl = strchr(argv[0], '=')) != NULL)) {
    727 		pat = argv[0];
    728 		*repl++ = '\0';
    729 		argc--, argv++;
    730 		VTRACE(DBG_HISTORY, ("histcmd replace old=\"%s\" new=\"%s\""
    731 		    " (%d args)\n", pat, repl, argc));
    732 	}
    733 
    734 	/*
    735 	 * If -s is specified, accept only one operand
    736 	 */
    737 	if (sflg && argc >= 2)
    738 		error("too many args");
    739 
    740 	/*
    741 	 * determine [first] and [last]
    742 	 */
    743 	switch (argc) {
    744 	case 0:
    745 		if (lflg) {
    746 			firststr = "-16";
    747 			laststr = "-1";
    748 		} else
    749 			firststr = laststr = "-1";	/* the exact same str */
    750 		break;
    751 	case 1:
    752 		firststr = argv[0];
    753 		laststr = lflg ? "-1" : argv[0];
    754 		break;
    755 	case 2:
    756 		firststr = argv[0];
    757 		laststr = argv[1];
    758 		break;
    759 	default:
    760 		error("too many args");
    761 		/* NOTREACHED */
    762 	}
    763 	/*
    764 	 * Turn into event numbers.
    765 	 */
    766 	first = str_to_event(firststr, 0);
    767 	last = str_to_event(laststr, 1);
    768 
    769 	if (first == -1 || last == -1) {
    770 		if (lflg)   /* no history exists, that's OK */
    771 			return 0;
    772 		if (first == -1 && last == -1) {
    773 			if (firststr != laststr)
    774 				error("history events %s to %s do not exist",
    775 				    firststr, laststr);
    776 			else
    777 				error("history event %s does not exist",
    778 				    firststr);
    779 		} else {
    780 			error("history event %s does not exist",
    781 			    first == -1 ? firststr : laststr);
    782 		}
    783 	}
    784 
    785 	if (rflg) {
    786 		i = last;
    787 		last = first;
    788 		first = i;
    789 	}
    790 	VTRACE(DBG_HISTORY, ("histcmd%s first=\"%s\" (#%d) last=\"%s\" (#%d)\n",
    791 	    rflg ? " reversed" : "", rflg ? laststr : firststr, first,
    792 	    rflg ? firststr : laststr, last));
    793 
    794 	/*
    795 	 * XXX - this should not depend on the event numbers
    796 	 * always increasing.  Add sequence numbers or offset
    797 	 * to the history element in next (diskbased) release.
    798 	 */
    799 	direction = first < last ? H_PREV : H_NEXT;
    800 
    801 	/*
    802 	 * If editing, grab a temp file.
    803 	 */
    804 	if (editor) {
    805 		int fd;
    806 
    807 		INTOFF;		/* easier */
    808 		snprintf(editfile, sizeof(editfile),
    809 		    "%s_shXXXXXX", _PATH_TMP);
    810 		if ((fd = mkstemp(editfile)) < 0)
    811 			error("can't create temporary file %s", editfile);
    812 		if ((efp = fdopen(fd, "w")) == NULL) {
    813 			close(fd);
    814 			error("can't allocate stdio buffer for temp");
    815 		}
    816 		VTRACE(DBG_HISTORY, ("histcmd created \"%s\" for edit buffer"
    817 		    " fd=%d\n", editfile, fd));
    818 	}
    819 
    820 	/*
    821 	 * Loop through selected history events.  If listing or executing,
    822 	 * do it now.  Otherwise, put into temp file and call the editor
    823 	 * after.
    824 	 *
    825 	 * The history interface needs rethinking, as the following
    826 	 * convolutions will demonstrate.
    827 	 */
    828 	history(hist, &he, H_FIRST);
    829 	retval = history(hist, &he, H_NEXT_EVENT, first);
    830 	for ( ; retval != -1; retval = history(hist, &he, direction)) {
    831 		if (lflg) {
    832 			if (!nflg)
    833 				out1fmt("%5d ", he.num);
    834 			out1str(he.str);
    835 		} else {
    836 			const char *s = pat ?
    837 			   fc_replace(he.str, pat, repl) : he.str;
    838 
    839 			if (sflg) {
    840 				VTRACE(DBG_HISTORY, ("histcmd -s \"%s\"\n", s));
    841 				if (displayhist) {
    842 					out2str(s);
    843 				}
    844 
    845 				evalstring(s, 0);
    846 
    847 				if (displayhist && hist) {
    848 					/*
    849 					 *  XXX what about recursive and
    850 					 *  relative histnums.
    851 					 */
    852 					history(hist, &he, H_ENTER, s);
    853 				}
    854 
    855 				break;
    856 			} else
    857 				fputs(s, efp);
    858 		}
    859 		/*
    860 		 * At end?  (if we were to lose last, we'd sure be
    861 		 * messed up).
    862 		 */
    863 		if (he.num == last)
    864 			break;
    865 	}
    866 	if (editor) {
    867 		char *editcmd;
    868 		size_t cmdlen;
    869 
    870 		fclose(efp);
    871 		cmdlen = strlen(editor) + strlen(editfile) + 2;
    872 		editcmd = stalloc(cmdlen);
    873 		snprintf(editcmd, cmdlen, "%s %s", editor, editfile);
    874 		VTRACE(DBG_HISTORY, ("histcmd editing: \"%s\"\n", editcmd));
    875 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
    876 		stunalloc(editcmd);
    877 		VTRACE(DBG_HISTORY, ("histcmd read cmds from %s\n", editfile));
    878 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
    879 		VTRACE(DBG_HISTORY, ("histcmd unlink %s\n", editfile));
    880 		unlink(editfile);
    881 		editfile[0] = '\0';
    882 		INTON;
    883 	}
    884 
    885 	if (lflg == 0 && active > 0)
    886 		--active;
    887 	if (displayhist)
    888 		displayhist = 0;
    889 	return 0;
    890 }
    891 
    892 /*
    893  * and finally worker functions for those built-ins
    894  */
    895 
    896 static const char *
    897 fc_replace(const char *s, char *p, char *r)
    898 {
    899 	char *dest;
    900 	int plen = strlen(p);
    901 
    902 	VTRACE(DBG_HISTORY, ("histcmd s/%s/%s/ in \"%s\" -> ", p, r, s));
    903 	STARTSTACKSTR(dest);
    904 	while (*s) {
    905 		if (*s == *p && strncmp(s, p, plen) == 0) {
    906 			while (*r)
    907 				STPUTC(*r++, dest);
    908 			s += plen;
    909 			*p = '\0';	/* so no more matches */
    910 		} else
    911 			STPUTC(*s++, dest);
    912 	}
    913 	STPUTC('\0', dest);
    914 	dest = grabstackstr(dest);
    915 	VTRACE(DBG_HISTORY, ("\"%s\"\n", dest));
    916 
    917 	return dest;
    918 }
    919 
    920 
    921 /*
    922  * Comparator function for qsort(). The use of curpos here is to skip
    923  * characters that we already know to compare equal (common prefix).
    924  */
    925 static int
    926 comparator(const void *a, const void *b)
    927 {
    928 	return strcmp(*(char *const *)a + curpos,
    929 		*(char *const *)b + curpos);
    930 }
    931 
    932 /*
    933  * This function is passed to libedit's fn_complete(). The library will
    934  * use it instead of its standard function to find matches, which
    935  * searches for files in current directory. If we're at the start of the
    936  * line, we want to look for available commands from all paths in $PATH.
    937  */
    938 static char **
    939 sh_matches(const char *text, int start, int end)
    940 {
    941 	char *free_path = NULL, *dirname, *path;
    942 	char **matches = NULL;
    943 	size_t i = 0, size = 16;
    944 
    945 	if (start > 0)
    946 		return NULL;
    947 	curpos = end - start;
    948 	if ((free_path = path = strdup(pathval())) == NULL)
    949 		goto out;
    950 	if ((matches = malloc(size * sizeof(matches[0]))) == NULL)
    951 		goto out;
    952 	while ((dirname = strsep(&path, ":")) != NULL) {
    953 		struct dirent *entry;
    954 		DIR *dir;
    955 		int dfd;
    956 
    957 		if ((dir = opendir(dirname)) == NULL)
    958 			continue;
    959 		if ((dfd = dirfd(dir)) == -1)
    960 			continue;
    961 		while ((entry = readdir(dir)) != NULL) {
    962 			struct stat statb;
    963 
    964 			if (strncmp(entry->d_name, text, curpos) != 0)
    965 				continue;
    966 			if (entry->d_type == DT_UNKNOWN ||
    967 			    entry->d_type == DT_LNK) {
    968 				if (fstatat(dfd, entry->d_name, &statb, 0)
    969 				    == -1)
    970 					continue;
    971 				if (!S_ISREG(statb.st_mode))
    972 					continue;
    973 			} else if (entry->d_type != DT_REG)
    974 				continue;
    975 			if (++i >= size - 1) {
    976 				size *= 2;
    977 				if (reallocarr(&matches, size,
    978 				    sizeof(*matches)))
    979 				{
    980 					closedir(dir);
    981 					goto out;
    982 				}
    983 			}
    984 			matches[i] = strdup(entry->d_name);
    985 		}
    986 		closedir(dir);
    987 	}
    988  out:;
    989 	free(free_path);
    990 	if (i == 0) {
    991 		free(matches);
    992 		return NULL;
    993 	}
    994 	if (i == 1) {
    995 		matches[0] = strdup(matches[1]);
    996 		matches[i + 1] = NULL;
    997 	} else {
    998 		size_t j, k;
    999 
   1000 		qsort(matches + 1, i, sizeof(matches[0]), comparator);
   1001 		for (j = 1, k = 2; k <= i; k++)
   1002 			if (strcmp(matches[j] + curpos, matches[k] + curpos)
   1003 			    == 0)
   1004 				free(matches[k]);
   1005 			else
   1006 				matches[++j] = matches[k];
   1007 		matches[0] = strdup(text);
   1008 		matches[j + 1] = NULL;
   1009 	}
   1010 	return matches;
   1011 }
   1012 
   1013 /*
   1014  * This is passed to el_set(el, EL_ADDFN, ...) so that it's possible to
   1015  * bind a key (tab by default) to execute the function.
   1016  */
   1017 unsigned char
   1018 sh_complete(EditLine *sel, int ch __unused)
   1019 {
   1020 	return (unsigned char)fn_complete2(sel, NULL, sh_matches,
   1021 		L" \t\n\"\\'`@$><=;|&{(", NULL, NULL, (size_t)100,
   1022 		NULL, &((int) {0}), NULL, NULL, FN_QUOTE_MATCH
   1023 		| (dotglob ? FN_MATCH_HIDDEN_FILES : 0));
   1024 }
   1025 
   1026 static int
   1027 not_fcnumber(const char *s)
   1028 {
   1029 	if (s == NULL)
   1030 		return 0;
   1031 	if (*s == '-')
   1032 		s++;
   1033 	return !is_number(s);
   1034 }
   1035 
   1036 static int
   1037 str_to_event(const char *str, int last)
   1038 {
   1039 	HistEvent he;
   1040 	const char *s = str;
   1041 	int relative = 0;
   1042 	int i, retval;
   1043 
   1044 	retval = history(hist, &he, H_FIRST);
   1045 	switch (*s) {
   1046 	case '-':
   1047 		relative = 1;
   1048 		/*FALLTHROUGH*/
   1049 	case '+':
   1050 		s++;
   1051 	}
   1052 	if (is_number(s)) {
   1053 		i = number(s);
   1054 		if (relative) {
   1055 			while (retval != -1 && i--) {
   1056 				retval = history(hist, &he, H_NEXT);
   1057 			}
   1058 			if (retval == -1)
   1059 				retval = history(hist, &he, H_LAST);
   1060 		} else {
   1061 			retval = history(hist, &he, H_NEXT_EVENT, i);
   1062 			if (retval == -1) {
   1063 				/*
   1064 				 * the notion of first and last is
   1065 				 * backwards to that of the history package
   1066 				 */
   1067 				retval = history(hist, &he,
   1068 						last ? H_FIRST : H_LAST);
   1069 			}
   1070 		}
   1071 		if (retval == -1)
   1072 			return -1;
   1073 	} else {
   1074 		/*
   1075 		 * pattern
   1076 		 */
   1077 		retval = history(hist, &he, H_PREV_STR, str);
   1078 		if (retval == -1)
   1079 			error("history pattern not found: %s", str);
   1080 	}
   1081 	return he.num;
   1082 }
   1083 
   1084 #else	/* defined(SMALL) */
   1085 
   1086 int
   1087 histcmd(int argc, char **argv)
   1088 {
   1089 	error("not compiled with history support");
   1090 	/* NOTREACHED */
   1091 }
   1092 
   1093 int
   1094 inputrc(int argc, char **argv)
   1095 {
   1096 	error("not compiled with history support");
   1097 	/* NOTREACHED */
   1098 }
   1099 
   1100 #endif	/* SMALL */
   1101