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