Home | History | Annotate | Line # | Download | only in sh
histedit.c revision 1.48
      1 /*	$NetBSD: histedit.c,v 1.48 2016/03/16 22:36:40 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.48 2016/03/16 22:36:40 christos 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 				el_set(el, EL_PROMPT, getprompt);
    138 				el_set(el, EL_SIGNAL, 1);
    139 				el_set(el, EL_ALIAS_TEXT, alias_text, NULL);
    140 				el_set(el, EL_ADDFN, "rl-complete",
    141 				    "ReadLine compatible completion function",
    142 				    _el_fn_complete);
    143 			} else {
    144 bad:
    145 				out2str("sh: can't initialize editing\n");
    146 			}
    147 			INTON;
    148 		} else if (!editing && el) {
    149 			INTOFF;
    150 			el_end(el);
    151 			el = NULL;
    152 			INTON;
    153 		}
    154 		if (el) {
    155 			el_source(el, NULL);
    156 			if (Vflag)
    157 				el_set(el, EL_EDITOR, "vi");
    158 			else if (Eflag)
    159 				el_set(el, EL_EDITOR, "emacs");
    160 			el_set(el, EL_BIND, "^I",
    161 			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
    162 		}
    163 	} else {
    164 		INTOFF;
    165 		if (el) {	/* no editing if not interactive */
    166 			el_end(el);
    167 			el = NULL;
    168 		}
    169 		if (hist) {
    170 			history_end(hist);
    171 			hist = NULL;
    172 		}
    173 		INTON;
    174 	}
    175 }
    176 
    177 
    178 void
    179 sethistsize(const char *hs)
    180 {
    181 	int histsize;
    182 	HistEvent he;
    183 
    184 	if (hist != NULL) {
    185 		if (hs == NULL || *hs == '\0' ||
    186 		   (histsize = atoi(hs)) < 0)
    187 			histsize = 100;
    188 		history(hist, &he, H_SETSIZE, histsize);
    189 		history(hist, &he, H_SETUNIQUE, 1);
    190 	}
    191 }
    192 
    193 void
    194 setterm(const char *term)
    195 {
    196 	if (el != NULL && term != NULL)
    197 		if (el_set(el, EL_TERMINAL, term) != 0) {
    198 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
    199 			outfmt(out2, "sh: Using dumb terminal settings.\n");
    200 		}
    201 }
    202 
    203 int
    204 inputrc(int argc, char **argv)
    205 {
    206 	if (argc != 2) {
    207 		out2str("usage: inputrc file\n");
    208 		return 1;
    209 	}
    210 	if (el != NULL) {
    211 		if (el_source(el, argv[1])) {
    212 			out2str("inputrc: failed\n");
    213 			return 1;
    214 		} else
    215 			return 0;
    216 	} else {
    217 		out2str("sh: inputrc ignored, not editing\n");
    218 		return 1;
    219 	}
    220 }
    221 
    222 /*
    223  *  This command is provided since POSIX decided to standardize
    224  *  the Korn shell fc command.  Oh well...
    225  */
    226 int
    227 histcmd(volatile int argc, char ** volatile argv)
    228 {
    229 	int ch;
    230 	const char * volatile editor = NULL;
    231 	HistEvent he;
    232 	volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
    233 	int i, retval;
    234 	const char *firststr, *laststr;
    235 	int first, last, direction;
    236 	char * volatile pat = NULL, * volatile repl;	/* ksh "fc old=new" crap */
    237 	static int active = 0;
    238 	struct jmploc jmploc;
    239 	struct jmploc *volatile savehandler;
    240 	char editfile[MAXPATHLEN + 1];
    241 	FILE * volatile efp;
    242 #ifdef __GNUC__
    243 	repl = NULL;	/* XXX gcc4 */
    244 	efp = NULL;	/* XXX gcc4 */
    245 #endif
    246 
    247 	if (hist == NULL)
    248 		error("history not active");
    249 
    250 	if (argc == 1)
    251 		error("missing history argument");
    252 
    253 	optreset = 1; optind = 1; /* initialize getopt */
    254 	while (not_fcnumber(argv[optind]) &&
    255 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
    256 		switch ((char)ch) {
    257 		case 'e':
    258 			editor = optionarg;
    259 			break;
    260 		case 'l':
    261 			lflg = 1;
    262 			break;
    263 		case 'n':
    264 			nflg = 1;
    265 			break;
    266 		case 'r':
    267 			rflg = 1;
    268 			break;
    269 		case 's':
    270 			sflg = 1;
    271 			break;
    272 		case ':':
    273 			error("option -%c expects argument", optopt);
    274 			/* NOTREACHED */
    275 		case '?':
    276 		default:
    277 			error("unknown option: -%c", optopt);
    278 			/* NOTREACHED */
    279 		}
    280 	argc -= optind, argv += optind;
    281 
    282 	/*
    283 	 * If executing...
    284 	 */
    285 	if (lflg == 0 || editor || sflg) {
    286 		lflg = 0;	/* ignore */
    287 		editfile[0] = '\0';
    288 		/*
    289 		 * Catch interrupts to reset active counter and
    290 		 * cleanup temp files.
    291 		 */
    292 		savehandler = handler;
    293 		if (setjmp(jmploc.loc)) {
    294 			active = 0;
    295 			if (*editfile)
    296 				unlink(editfile);
    297 			handler = savehandler;
    298 			longjmp(handler->loc, 1);
    299 		}
    300 		handler = &jmploc;
    301 		if (++active > MAXHISTLOOPS) {
    302 			active = 0;
    303 			displayhist = 0;
    304 			error("called recursively too many times");
    305 		}
    306 		/*
    307 		 * Set editor.
    308 		 */
    309 		if (sflg == 0) {
    310 			if (editor == NULL &&
    311 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
    312 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
    313 				editor = DEFEDITOR;
    314 			if (editor[0] == '-' && editor[1] == '\0') {
    315 				sflg = 1;	/* no edit */
    316 				editor = NULL;
    317 			}
    318 		}
    319 	}
    320 
    321 	/*
    322 	 * If executing, parse [old=new] now
    323 	 */
    324 	if (lflg == 0 && argc > 0 &&
    325 	     ((repl = strchr(argv[0], '=')) != NULL)) {
    326 		pat = argv[0];
    327 		*repl++ = '\0';
    328 		argc--, argv++;
    329 	}
    330 
    331 	/*
    332 	 * If -s is specified, accept only one operand
    333 	 */
    334 	if (sflg && argc >= 2)
    335 		error("too many args");
    336 
    337 	/*
    338 	 * determine [first] and [last]
    339 	 */
    340 	switch (argc) {
    341 	case 0:
    342 		firststr = lflg ? "-16" : "-1";
    343 		laststr = "-1";
    344 		break;
    345 	case 1:
    346 		firststr = argv[0];
    347 		laststr = lflg ? "-1" : argv[0];
    348 		break;
    349 	case 2:
    350 		firststr = argv[0];
    351 		laststr = argv[1];
    352 		break;
    353 	default:
    354 		error("too many args");
    355 		/* NOTREACHED */
    356 	}
    357 	/*
    358 	 * Turn into event numbers.
    359 	 */
    360 	first = str_to_event(firststr, 0);
    361 	last = str_to_event(laststr, 1);
    362 
    363 	if (rflg) {
    364 		i = last;
    365 		last = first;
    366 		first = i;
    367 	}
    368 	/*
    369 	 * XXX - this should not depend on the event numbers
    370 	 * always increasing.  Add sequence numbers or offset
    371 	 * to the history element in next (diskbased) release.
    372 	 */
    373 	direction = first < last ? H_PREV : H_NEXT;
    374 
    375 	/*
    376 	 * If editing, grab a temp file.
    377 	 */
    378 	if (editor) {
    379 		int fd;
    380 		INTOFF;		/* easier */
    381 		snprintf(editfile, sizeof(editfile), "%s_shXXXXXX", _PATH_TMP);
    382 		if ((fd = mkstemp(editfile)) < 0)
    383 			error("can't create temporary file %s", editfile);
    384 		if ((efp = fdopen(fd, "w")) == NULL) {
    385 			close(fd);
    386 			error("can't allocate stdio buffer for temp");
    387 		}
    388 	}
    389 
    390 	/*
    391 	 * Loop through selected history events.  If listing or executing,
    392 	 * do it now.  Otherwise, put into temp file and call the editor
    393 	 * after.
    394 	 *
    395 	 * The history interface needs rethinking, as the following
    396 	 * convolutions will demonstrate.
    397 	 */
    398 	history(hist, &he, H_FIRST);
    399 	retval = history(hist, &he, H_NEXT_EVENT, first);
    400 	for (;retval != -1; retval = history(hist, &he, direction)) {
    401 		if (lflg) {
    402 			if (!nflg)
    403 				out1fmt("%5d ", he.num);
    404 			out1str(he.str);
    405 		} else {
    406 			const char *s = pat ?
    407 			   fc_replace(he.str, pat, repl) : he.str;
    408 
    409 			if (sflg) {
    410 				if (displayhist) {
    411 					out2str(s);
    412 				}
    413 
    414 				evalstring(strcpy(stalloc(strlen(s) + 1), s), 0);
    415 				if (displayhist && hist) {
    416 					/*
    417 					 *  XXX what about recursive and
    418 					 *  relative histnums.
    419 					 */
    420 					history(hist, &he, H_ENTER, s);
    421 				}
    422 
    423 				break;
    424 			} else
    425 				fputs(s, efp);
    426 		}
    427 		/*
    428 		 * At end?  (if we were to lose last, we'd sure be
    429 		 * messed up).
    430 		 */
    431 		if (he.num == last)
    432 			break;
    433 	}
    434 	if (editor) {
    435 		char *editcmd;
    436 		size_t cmdlen;
    437 
    438 		fclose(efp);
    439 		cmdlen = strlen(editor) + strlen(editfile) + 2;
    440 		editcmd = stalloc(cmdlen);
    441 		snprintf(editcmd, cmdlen, "%s %s", editor, editfile);
    442 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
    443 		INTON;
    444 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
    445 		unlink(editfile);
    446 	}
    447 
    448 	if (lflg == 0 && active > 0)
    449 		--active;
    450 	if (displayhist)
    451 		displayhist = 0;
    452 	return 0;
    453 }
    454 
    455 STATIC const char *
    456 fc_replace(const char *s, char *p, char *r)
    457 {
    458 	char *dest;
    459 	int plen = strlen(p);
    460 
    461 	STARTSTACKSTR(dest);
    462 	while (*s) {
    463 		if (*s == *p && strncmp(s, p, plen) == 0) {
    464 			while (*r)
    465 				STPUTC(*r++, dest);
    466 			s += plen;
    467 			*p = '\0';	/* so no more matches */
    468 		} else
    469 			STPUTC(*s++, dest);
    470 	}
    471 	STACKSTRNUL(dest);
    472 	dest = grabstackstr(dest);
    473 
    474 	return (dest);
    475 }
    476 
    477 int
    478 not_fcnumber(char *s)
    479 {
    480 	if (s == NULL)
    481 		return 0;
    482         if (*s == '-')
    483                 s++;
    484 	return (!is_number(s));
    485 }
    486 
    487 int
    488 str_to_event(const char *str, int last)
    489 {
    490 	HistEvent he;
    491 	const char *s = str;
    492 	int relative = 0;
    493 	int i, retval;
    494 
    495 	retval = history(hist, &he, H_FIRST);
    496 	switch (*s) {
    497 	case '-':
    498 		relative = 1;
    499 		/*FALLTHROUGH*/
    500 	case '+':
    501 		s++;
    502 	}
    503 	if (is_number(s)) {
    504 		i = atoi(s);
    505 		if (relative) {
    506 			while (retval != -1 && i--) {
    507 				retval = history(hist, &he, H_NEXT);
    508 			}
    509 			if (retval == -1)
    510 				retval = history(hist, &he, H_LAST);
    511 		} else {
    512 			retval = history(hist, &he, H_NEXT_EVENT, i);
    513 			if (retval == -1) {
    514 				/*
    515 				 * the notion of first and last is
    516 				 * backwards to that of the history package
    517 				 */
    518 				retval = history(hist, &he,
    519 						last ? H_FIRST : H_LAST);
    520 			}
    521 		}
    522 		if (retval == -1)
    523 			error("history number %s not found (internal error)",
    524 			       str);
    525 	} else {
    526 		/*
    527 		 * pattern
    528 		 */
    529 		retval = history(hist, &he, H_PREV_STR, str);
    530 		if (retval == -1)
    531 			error("history pattern not found: %s", str);
    532 	}
    533 	return (he.num);
    534 }
    535 #else
    536 int
    537 histcmd(int argc, char **argv)
    538 {
    539 	error("not compiled with history support");
    540 	/* NOTREACHED */
    541 }
    542 int
    543 inputrc(int argc, char **argv)
    544 {
    545 	error("not compiled with history support");
    546 	/* NOTREACHED */
    547 }
    548 #endif
    549