Home | History | Annotate | Line # | Download | only in sh
histedit.c revision 1.54
      1 /*	$NetBSD: histedit.c,v 1.54 2019/02/09 03:35:55 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.54 2019/02/09 03:35:55 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <sys/param.h>
     45 #include <paths.h>
     46 #include <stdio.h>
     47 #include <stdlib.h>
     48 #include <unistd.h>
     49 /*
     50  * Editline and history functions (and glue).
     51  */
     52 #include "shell.h"
     53 #include "parser.h"
     54 #include "var.h"
     55 #include "options.h"
     56 #include "builtins.h"
     57 #include "main.h"
     58 #include "output.h"
     59 #include "mystring.h"
     60 #include "myhistedit.h"
     61 #include "error.h"
     62 #include "alias.h"
     63 #ifndef SMALL
     64 #include "eval.h"
     65 #include "memalloc.h"
     66 
     67 #define MAXHISTLOOPS	4	/* max recursions through fc */
     68 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
     69 
     70 History *hist;	/* history cookie */
     71 EditLine *el;	/* editline cookie */
     72 int displayhist;
     73 static FILE *el_in, *el_out;
     74 unsigned char _el_fn_complete(EditLine *, int);
     75 
     76 STATIC const char *fc_replace(const char *, char *, char *);
     77 
     78 #ifdef DEBUG
     79 extern FILE *tracefile;
     80 #endif
     81 
     82 /*
     83  * Set history and editing status.  Called whenever the status may
     84  * have changed (figures out what to do).
     85  */
     86 void
     87 histedit(void)
     88 {
     89 	FILE *el_err;
     90 
     91 #define editing (Eflag || Vflag)
     92 
     93 	if (iflag == 1) {
     94 		if (!hist) {
     95 			/*
     96 			 * turn history on
     97 			 */
     98 			INTOFF;
     99 			hist = history_init();
    100 			INTON;
    101 
    102 			if (hist != NULL)
    103 				sethistsize(histsizeval());
    104 			else
    105 				out2str("sh: can't initialize history\n");
    106 		}
    107 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
    108 			/*
    109 			 * turn editing on
    110 			 */
    111 			char *term, *shname;
    112 
    113 			INTOFF;
    114 			if (el_in == NULL)
    115 				el_in = fdopen(0, "r");
    116 			if (el_out == NULL)
    117 				el_out = fdopen(2, "w");
    118 			if (el_in == NULL || el_out == NULL)
    119 				goto bad;
    120 			el_err = el_out;
    121 #if DEBUG
    122 			if (tracefile)
    123 				el_err = tracefile;
    124 #endif
    125 			term = lookupvar("TERM");
    126 			if (term)
    127 				setenv("TERM", term, 1);
    128 			else
    129 				unsetenv("TERM");
    130 			shname = arg0;
    131 			if (shname[0] == '-')
    132 				shname++;
    133 			el = el_init(shname, el_in, el_out, el_err);
    134 			if (el != NULL) {
    135 				if (hist)
    136 					el_set(el, EL_HIST, history, hist);
    137 
    138 				set_prompt_lit(lookupvar("PSlit"));
    139 				el_set(el, EL_SIGNAL, 1);
    140 				el_set(el, EL_ALIAS_TEXT, alias_text, NULL);
    141 				el_set(el, EL_ADDFN, "rl-complete",
    142 				    "ReadLine compatible completion function",
    143 				    _el_fn_complete);
    144 			} else {
    145 bad:
    146 				out2str("sh: can't initialize editing\n");
    147 			}
    148 			INTON;
    149 		} else if (!editing && el) {
    150 			INTOFF;
    151 			el_end(el);
    152 			el = NULL;
    153 			INTON;
    154 		}
    155 		if (el) {
    156 			INTOFF;
    157 			if (Vflag)
    158 				el_set(el, EL_EDITOR, "vi");
    159 			else if (Eflag)
    160 				el_set(el, EL_EDITOR, "emacs");
    161 			el_set(el, EL_BIND, "^I",
    162 			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
    163 			el_source(el, lookupvar("EDITRC"));
    164 			INTON;
    165 		}
    166 	} else {
    167 		INTOFF;
    168 		if (el) {	/* no editing if not interactive */
    169 			el_end(el);
    170 			el = NULL;
    171 		}
    172 		if (hist) {
    173 			history_end(hist);
    174 			hist = NULL;
    175 		}
    176 		INTON;
    177 	}
    178 }
    179 
    180 void
    181 set_prompt_lit(const char *lit_ch)
    182 {
    183 	wchar_t wc;
    184 
    185 	if (!(iflag && editing && el))
    186 		return;
    187 
    188 	if (lit_ch == NULL) {
    189 		el_set(el, EL_PROMPT, getprompt);
    190 		return;
    191 	}
    192 
    193 	mbtowc(&wc, NULL, 1);		/* state init */
    194 
    195 	INTOFF;
    196 	if (mbtowc(&wc, lit_ch, strlen(lit_ch)) <= 0)
    197 		el_set(el, EL_PROMPT, getprompt);
    198 	else
    199 		el_set(el, EL_PROMPT_ESC, getprompt, (int)wc);
    200 	INTON;
    201 }
    202 
    203 void
    204 set_editrc(const char *fname)
    205 {
    206 	INTOFF;
    207 	if (iflag && editing && el)
    208 		el_source(el, fname);
    209 	INTON;
    210 }
    211 
    212 void
    213 sethistsize(const char *hs)
    214 {
    215 	int histsize;
    216 	HistEvent he;
    217 
    218 	if (hist != NULL) {
    219 		if (hs == NULL || *hs == '\0' || *hs == '-' ||
    220 		   (histsize = number(hs)) < 0)
    221 			histsize = 100;
    222 		INTOFF;
    223 		history(hist, &he, H_SETSIZE, histsize);
    224 		history(hist, &he, H_SETUNIQUE, 1);
    225 		INTON;
    226 	}
    227 }
    228 
    229 void
    230 setterm(const char *term)
    231 {
    232 	INTOFF;
    233 	if (el != NULL && term != NULL)
    234 		if (el_set(el, EL_TERMINAL, term) != 0) {
    235 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
    236 			outfmt(out2, "sh: Using dumb terminal settings.\n");
    237 		}
    238 	INTON;
    239 }
    240 
    241 int
    242 inputrc(int argc, char **argv)
    243 {
    244 	if (argc != 2) {
    245 		out2str("usage: inputrc file\n");
    246 		return 1;
    247 	}
    248 	if (el != NULL) {
    249 		INTOFF;
    250 		if (el_source(el, argv[1])) {
    251 			INTON;
    252 			out2str("inputrc: failed\n");
    253 			return 1;
    254 		}
    255 		INTON;
    256 		return 0;
    257 	} else {
    258 		out2str("sh: inputrc ignored, not editing\n");
    259 		return 1;
    260 	}
    261 }
    262 
    263 /*
    264  *  This command is provided since POSIX decided to standardize
    265  *  the Korn shell fc command.  Oh well...
    266  */
    267 int
    268 histcmd(volatile int argc, char ** volatile argv)
    269 {
    270 	int ch;
    271 	const char * volatile editor = NULL;
    272 	HistEvent he;
    273 	volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
    274 	int i, retval;
    275 	const char *firststr, *laststr;
    276 	int first, last, direction;
    277 	char * volatile pat = NULL, * volatile repl;	/* ksh "fc old=new" crap */
    278 	static int active = 0;
    279 	struct jmploc jmploc;
    280 	struct jmploc *volatile savehandler;
    281 	char editfile[MAXPATHLEN + 1];
    282 	FILE * volatile efp;
    283 #ifdef __GNUC__
    284 	repl = NULL;	/* XXX gcc4 */
    285 	efp = NULL;	/* XXX gcc4 */
    286 #endif
    287 
    288 	if (hist == NULL)
    289 		error("history not active");
    290 
    291 	if (argc == 1)
    292 		error("missing history argument");
    293 
    294 	optreset = 1; optind = 1; /* initialize getopt */
    295 	while (not_fcnumber(argv[optind]) &&
    296 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
    297 		switch ((char)ch) {
    298 		case 'e':
    299 			editor = optionarg;
    300 			break;
    301 		case 'l':
    302 			lflg = 1;
    303 			break;
    304 		case 'n':
    305 			nflg = 1;
    306 			break;
    307 		case 'r':
    308 			rflg = 1;
    309 			break;
    310 		case 's':
    311 			sflg = 1;
    312 			break;
    313 		case ':':
    314 			error("option -%c expects argument", optopt);
    315 			/* NOTREACHED */
    316 		case '?':
    317 		default:
    318 			error("unknown option: -%c", optopt);
    319 			/* NOTREACHED */
    320 		}
    321 	argc -= optind, argv += optind;
    322 
    323 	/*
    324 	 * If executing...
    325 	 */
    326 	if (lflg == 0 || editor || sflg) {
    327 		lflg = 0;	/* ignore */
    328 		editfile[0] = '\0';
    329 		/*
    330 		 * Catch interrupts to reset active counter and
    331 		 * cleanup temp files.
    332 		 */
    333 		savehandler = handler;
    334 		if (setjmp(jmploc.loc)) {
    335 			active = 0;
    336 			if (*editfile)
    337 				unlink(editfile);
    338 			handler = savehandler;
    339 			longjmp(handler->loc, 1);
    340 		}
    341 		handler = &jmploc;
    342 		if (++active > MAXHISTLOOPS) {
    343 			active = 0;
    344 			displayhist = 0;
    345 			error("called recursively too many times");
    346 		}
    347 		/*
    348 		 * Set editor.
    349 		 */
    350 		if (sflg == 0) {
    351 			if (editor == NULL &&
    352 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
    353 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
    354 				editor = DEFEDITOR;
    355 			if (editor[0] == '-' && editor[1] == '\0') {
    356 				sflg = 1;	/* no edit */
    357 				editor = NULL;
    358 			}
    359 		}
    360 	}
    361 
    362 	/*
    363 	 * If executing, parse [old=new] now
    364 	 */
    365 	if (lflg == 0 && argc > 0 &&
    366 	     ((repl = strchr(argv[0], '=')) != NULL)) {
    367 		pat = argv[0];
    368 		*repl++ = '\0';
    369 		argc--, argv++;
    370 	}
    371 
    372 	/*
    373 	 * If -s is specified, accept only one operand
    374 	 */
    375 	if (sflg && argc >= 2)
    376 		error("too many args");
    377 
    378 	/*
    379 	 * determine [first] and [last]
    380 	 */
    381 	switch (argc) {
    382 	case 0:
    383 		firststr = lflg ? "-16" : "-1";
    384 		laststr = "-1";
    385 		break;
    386 	case 1:
    387 		firststr = argv[0];
    388 		laststr = lflg ? "-1" : argv[0];
    389 		break;
    390 	case 2:
    391 		firststr = argv[0];
    392 		laststr = argv[1];
    393 		break;
    394 	default:
    395 		error("too many args");
    396 		/* NOTREACHED */
    397 	}
    398 	/*
    399 	 * Turn into event numbers.
    400 	 */
    401 	first = str_to_event(firststr, 0);
    402 	last = str_to_event(laststr, 1);
    403 
    404 	if (rflg) {
    405 		i = last;
    406 		last = first;
    407 		first = i;
    408 	}
    409 	/*
    410 	 * XXX - this should not depend on the event numbers
    411 	 * always increasing.  Add sequence numbers or offset
    412 	 * to the history element in next (diskbased) release.
    413 	 */
    414 	direction = first < last ? H_PREV : H_NEXT;
    415 
    416 	/*
    417 	 * If editing, grab a temp file.
    418 	 */
    419 	if (editor) {
    420 		int fd;
    421 		INTOFF;		/* easier */
    422 		snprintf(editfile, sizeof(editfile), "%s_shXXXXXX", _PATH_TMP);
    423 		if ((fd = mkstemp(editfile)) < 0)
    424 			error("can't create temporary file %s", editfile);
    425 		if ((efp = fdopen(fd, "w")) == NULL) {
    426 			close(fd);
    427 			error("can't allocate stdio buffer for temp");
    428 		}
    429 	}
    430 
    431 	/*
    432 	 * Loop through selected history events.  If listing or executing,
    433 	 * do it now.  Otherwise, put into temp file and call the editor
    434 	 * after.
    435 	 *
    436 	 * The history interface needs rethinking, as the following
    437 	 * convolutions will demonstrate.
    438 	 */
    439 	history(hist, &he, H_FIRST);
    440 	retval = history(hist, &he, H_NEXT_EVENT, first);
    441 	for (;retval != -1; retval = history(hist, &he, direction)) {
    442 		if (lflg) {
    443 			if (!nflg)
    444 				out1fmt("%5d ", he.num);
    445 			out1str(he.str);
    446 		} else {
    447 			const char *s = pat ?
    448 			   fc_replace(he.str, pat, repl) : he.str;
    449 
    450 			if (sflg) {
    451 				if (displayhist) {
    452 					out2str(s);
    453 				}
    454 
    455 				evalstring(strcpy(stalloc(strlen(s) + 1), s), 0);
    456 				if (displayhist && hist) {
    457 					/*
    458 					 *  XXX what about recursive and
    459 					 *  relative histnums.
    460 					 */
    461 					history(hist, &he, H_ENTER, s);
    462 				}
    463 
    464 				break;
    465 			} else
    466 				fputs(s, efp);
    467 		}
    468 		/*
    469 		 * At end?  (if we were to lose last, we'd sure be
    470 		 * messed up).
    471 		 */
    472 		if (he.num == last)
    473 			break;
    474 	}
    475 	if (editor) {
    476 		char *editcmd;
    477 		size_t cmdlen;
    478 
    479 		fclose(efp);
    480 		cmdlen = strlen(editor) + strlen(editfile) + 2;
    481 		editcmd = stalloc(cmdlen);
    482 		snprintf(editcmd, cmdlen, "%s %s", editor, editfile);
    483 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
    484 		stunalloc(editcmd);
    485 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
    486 		unlink(editfile);
    487 		INTON;
    488 	}
    489 
    490 	if (lflg == 0 && active > 0)
    491 		--active;
    492 	if (displayhist)
    493 		displayhist = 0;
    494 	return 0;
    495 }
    496 
    497 STATIC const char *
    498 fc_replace(const char *s, char *p, char *r)
    499 {
    500 	char *dest;
    501 	int plen = strlen(p);
    502 
    503 	STARTSTACKSTR(dest);
    504 	while (*s) {
    505 		if (*s == *p && strncmp(s, p, plen) == 0) {
    506 			while (*r)
    507 				STPUTC(*r++, dest);
    508 			s += plen;
    509 			*p = '\0';	/* so no more matches */
    510 		} else
    511 			STPUTC(*s++, dest);
    512 	}
    513 	STACKSTRNUL(dest);
    514 	dest = grabstackstr(dest);
    515 
    516 	return (dest);
    517 }
    518 
    519 int
    520 not_fcnumber(char *s)
    521 {
    522 	if (s == NULL)
    523 		return 0;
    524         if (*s == '-')
    525                 s++;
    526 	return (!is_number(s));
    527 }
    528 
    529 int
    530 str_to_event(const char *str, int last)
    531 {
    532 	HistEvent he;
    533 	const char *s = str;
    534 	int relative = 0;
    535 	int i, retval;
    536 
    537 	retval = history(hist, &he, H_FIRST);
    538 	switch (*s) {
    539 	case '-':
    540 		relative = 1;
    541 		/*FALLTHROUGH*/
    542 	case '+':
    543 		s++;
    544 	}
    545 	if (is_number(s)) {
    546 		i = number(s);
    547 		if (relative) {
    548 			while (retval != -1 && i--) {
    549 				retval = history(hist, &he, H_NEXT);
    550 			}
    551 			if (retval == -1)
    552 				retval = history(hist, &he, H_LAST);
    553 		} else {
    554 			retval = history(hist, &he, H_NEXT_EVENT, i);
    555 			if (retval == -1) {
    556 				/*
    557 				 * the notion of first and last is
    558 				 * backwards to that of the history package
    559 				 */
    560 				retval = history(hist, &he,
    561 						last ? H_FIRST : H_LAST);
    562 			}
    563 		}
    564 		if (retval == -1)
    565 			error("history number %s not found (internal error)",
    566 			       str);
    567 	} else {
    568 		/*
    569 		 * pattern
    570 		 */
    571 		retval = history(hist, &he, H_PREV_STR, str);
    572 		if (retval == -1)
    573 			error("history pattern not found: %s", str);
    574 	}
    575 	return (he.num);
    576 }
    577 #else
    578 int
    579 histcmd(int argc, char **argv)
    580 {
    581 	error("not compiled with history support");
    582 	/* NOTREACHED */
    583 }
    584 int
    585 inputrc(int argc, char **argv)
    586 {
    587 	error("not compiled with history support");
    588 	/* NOTREACHED */
    589 }
    590 #endif
    591