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