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