Home | History | Annotate | Line # | Download | only in sh
histedit.c revision 1.8
      1 /*	$NetBSD: histedit.c,v 1.8 1995/05/11 21:29:12 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. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 #ifndef lint
     40 #if 0
     41 static char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
     42 #else
     43 static char rcsid[] = "$NetBSD: histedit.c,v 1.8 1995/05/11 21:29:12 christos Exp $";
     44 #endif
     45 #endif /* not lint */
     46 
     47 #include <sys/param.h>
     48 #include <paths.h>
     49 #include <stdio.h>
     50 #include <stdlib.h>
     51 #include <unistd.h>
     52 /*
     53  * Editline and history functions (and glue).
     54  */
     55 #include "shell.h"
     56 #include "parser.h"
     57 #include "var.h"
     58 #include "options.h"
     59 #include "main.h"
     60 #include "output.h"
     61 #include "mystring.h"
     62 #ifndef NO_HISTORY
     63 #include "myhistedit.h"
     64 #endif
     65 #include "error.h"
     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 
     77 STATIC char *fc_replace __P((const char *, char *, char *));
     78 
     79 /*
     80  * Set history and editing status.  Called whenever the status may
     81  * have changed (figures out what to do).
     82  */
     83 void
     84 histedit()
     85 {
     86 
     87 #define editing (Eflag || Vflag)
     88 
     89 	if (iflag) {
     90 		if (!hist) {
     91 			/*
     92 			 * turn history on
     93 			 */
     94 			INTOFF;
     95 			hist = history_init();
     96 			INTON;
     97 
     98 			if (hist != NULL)
     99 				sethistsize();
    100 			else
    101 				out2str("sh: can't initialize history\n");
    102 		}
    103 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
    104 			/*
    105 			 * turn editing on
    106 			 */
    107 			INTOFF;
    108 			if (el_in == NULL)
    109 				el_in = fdopen(0, "r");
    110 			if (el_out == NULL)
    111 				el_out = fdopen(2, "w");
    112 			if (el_in == NULL || el_out == NULL)
    113 				goto bad;
    114 			el = el_init(arg0, el_in, el_out);
    115 			if (el != NULL) {
    116 				if (hist)
    117 					el_set(el, EL_HIST, history, hist);
    118 				el_set(el, EL_PROMPT, getprompt);
    119 			} else {
    120 bad:
    121 				out2str("sh: can't initialize editing\n");
    122 			}
    123 			INTON;
    124 		} else if (!editing && el) {
    125 			INTOFF;
    126 			el_end(el);
    127 			el = NULL;
    128 			INTON;
    129 		}
    130 		if (el) {
    131 			if (Vflag)
    132 				el_set(el, EL_EDITOR, "vi");
    133 			else if (Eflag)
    134 				el_set(el, EL_EDITOR, "emacs");
    135 		}
    136 	} else {
    137 		INTOFF;
    138 		if (el) {	/* no editing if not interactive */
    139 			el_end(el);
    140 			el = NULL;
    141 		}
    142 		if (hist) {
    143 			history_end(hist);
    144 			hist = NULL;
    145 		}
    146 		INTON;
    147 	}
    148 }
    149 
    150 
    151 void
    152 sethistsize()
    153 {
    154 	char *cp;
    155 	int histsize;
    156 
    157 	if (hist != NULL) {
    158 		cp = lookupvar("HISTSIZE");
    159 		if (cp == NULL || *cp == '\0' ||
    160 		   (histsize = atoi(cp)) < 0)
    161 			histsize = 100;
    162 		history(hist, H_EVENT, histsize);
    163 	}
    164 }
    165 
    166 /*
    167  *  This command is provided since POSIX decided to standardize
    168  *  the Korn shell fc command.  Oh well...
    169  */
    170 int
    171 histcmd(argc, argv)
    172 	int argc;
    173 	char **argv;
    174 {
    175 	extern char *optarg;
    176 	extern int optind, optopt, optreset;
    177 	int ch;
    178 	char *editor = NULL;
    179 	const HistEvent *he;
    180 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
    181 	int i;
    182 	char *firststr, *laststr;
    183 	int first, last, direction;
    184 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
    185 	static int active = 0;
    186 	struct jmploc jmploc;
    187 	struct jmploc *volatile savehandler;
    188 	char editfile[MAXPATHLEN + 1];
    189 	FILE *efp;
    190 #ifdef __GNUC__
    191 	/* Avoid longjmp clobbering */
    192 	(void) &editor;
    193 	(void) &lflg;
    194 	(void) &nflg;
    195 	(void) &rflg;
    196 	(void) &sflg;
    197 	(void) &firststr;
    198 	(void) &laststr;
    199 	(void) &pat;
    200 	(void) &repl;
    201 	(void) &efp;
    202 	(void) &argc;
    203 	(void) &argv;
    204 #endif
    205 
    206 	if (hist == NULL)
    207 		error("history not active");
    208 
    209 	if (argc == 1)
    210 		error("missing history argument");
    211 
    212 	optreset = 1; optind = 1; /* initialize getopt */
    213 	while (not_fcnumber(argv[optind]) &&
    214 	      (ch = getopt(argc, argv, ":e:lnrs")) != EOF)
    215 		switch ((char)ch) {
    216 		case 'e':
    217 			editor = optarg;
    218 			break;
    219 		case 'l':
    220 			lflg = 1;
    221 			break;
    222 		case 'n':
    223 			nflg = 1;
    224 			break;
    225 		case 'r':
    226 			rflg = 1;
    227 			break;
    228 		case 's':
    229 			sflg = 1;
    230 			break;
    231 		case ':':
    232 			error("option -%c expects argument", optopt);
    233 		case '?':
    234 		default:
    235 			error("unknown option: -%c", optopt);
    236 		}
    237 	argc -= optind, argv += optind;
    238 
    239 	/*
    240 	 * If executing...
    241 	 */
    242 	if (lflg == 0 || editor || sflg) {
    243 		lflg = 0;	/* ignore */
    244 		editfile[0] = '\0';
    245 		/*
    246 		 * Catch interrupts to reset active counter and
    247 		 * cleanup temp files.
    248 		 */
    249 		if (setjmp(jmploc.loc)) {
    250 			active = 0;
    251 			if (*editfile)
    252 				unlink(editfile);
    253 			handler = savehandler;
    254 			longjmp(handler->loc, 1);
    255 		}
    256 		savehandler = handler;
    257 		handler = &jmploc;
    258 		if (++active > MAXHISTLOOPS) {
    259 			active = 0;
    260 			displayhist = 0;
    261 			error("called recursively too many times");
    262 		}
    263 		/*
    264 		 * Set editor.
    265 		 */
    266 		if (sflg == 0) {
    267 			if (editor == NULL &&
    268 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
    269 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
    270 				editor = DEFEDITOR;
    271 			if (editor[0] == '-' && editor[1] == '\0') {
    272 				sflg = 1;	/* no edit */
    273 				editor = NULL;
    274 			}
    275 		}
    276 	}
    277 
    278 	/*
    279 	 * If executing, parse [old=new] now
    280 	 */
    281 	if (lflg == 0 && argc > 0 &&
    282 	     ((repl = strchr(argv[0], '=')) != NULL)) {
    283 		pat = argv[0];
    284 		*repl++ = '\0';
    285 		argc--, argv++;
    286 	}
    287 	/*
    288 	 * determine [first] and [last]
    289 	 */
    290 	switch (argc) {
    291 	case 0:
    292 		firststr = lflg ? "-16" : "-1";
    293 		laststr = "-1";
    294 		break;
    295 	case 1:
    296 		firststr = argv[0];
    297 		laststr = lflg ? "-1" : argv[0];
    298 		break;
    299 	case 2:
    300 		firststr = argv[0];
    301 		laststr = argv[1];
    302 		break;
    303 	default:
    304 		error("too many args");
    305 	}
    306 	/*
    307 	 * Turn into event numbers.
    308 	 */
    309 	first = str_to_event(firststr, 0);
    310 	last = str_to_event(laststr, 1);
    311 
    312 	if (rflg) {
    313 		i = last;
    314 		last = first;
    315 		first = i;
    316 	}
    317 	/*
    318 	 * XXX - this should not depend on the event numbers
    319 	 * always increasing.  Add sequence numbers or offset
    320 	 * to the history element in next (diskbased) release.
    321 	 */
    322 	direction = first < last ? H_PREV : H_NEXT;
    323 
    324 	/*
    325 	 * If editing, grab a temp file.
    326 	 */
    327 	if (editor) {
    328 		int fd;
    329 		INTOFF;		/* easier */
    330 		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
    331 		if ((fd = mkstemp(editfile)) < 0)
    332 			error("can't create temporary file %s", editfile);
    333 		if ((efp = fdopen(fd, "w")) == NULL) {
    334 			close(fd);
    335 			error("can't allocate stdio buffer for temp\n");
    336 		}
    337 	}
    338 
    339 	/*
    340 	 * Loop through selected history events.  If listing or executing,
    341 	 * do it now.  Otherwise, put into temp file and call the editor
    342 	 * after.
    343 	 *
    344 	 * The history interface needs rethinking, as the following
    345 	 * convolutions will demonstrate.
    346 	 */
    347 	history(hist, H_FIRST);
    348 	he = history(hist, H_NEXT_EVENT, first);
    349 	for (;he != NULL; he = history(hist, direction)) {
    350 		if (lflg) {
    351 			if (!nflg)
    352 				out1fmt("%5d ", he->num);
    353 			out1str(he->str);
    354 		} else {
    355 			char *s = pat ?
    356 			   fc_replace(he->str, pat, repl) : (char *)he->str;
    357 
    358 			if (sflg) {
    359 				if (displayhist) {
    360 					out2str(s);
    361 				}
    362 				evalstring(s);
    363 				if (displayhist && hist) {
    364 					/*
    365 					 *  XXX what about recursive and
    366 					 *  relative histnums.
    367 					 */
    368 					history(hist, H_ENTER, s);
    369 				}
    370 			} else
    371 				fputs(s, efp);
    372 		}
    373 		/*
    374 		 * At end?  (if we were to loose last, we'd sure be
    375 		 * messed up).
    376 		 */
    377 		if (he->num == last)
    378 			break;
    379 	}
    380 	if (editor) {
    381 		char *editcmd;
    382 
    383 		fclose(efp);
    384 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
    385 		sprintf(editcmd, "%s %s", editor, editfile);
    386 		evalstring(editcmd);	/* XXX - should use no JC command */
    387 		INTON;
    388 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
    389 		unlink(editfile);
    390 	}
    391 
    392 	if (lflg == 0 && active > 0)
    393 		--active;
    394 	if (displayhist)
    395 		displayhist = 0;
    396 	return 0;
    397 }
    398 
    399 STATIC char *
    400 fc_replace(s, p, r)
    401 	const char *s;
    402 	char *p, *r;
    403 {
    404 	char *dest;
    405 	int plen = strlen(p);
    406 
    407 	STARTSTACKSTR(dest);
    408 	while (*s) {
    409 		if (*s == *p && strncmp(s, p, plen) == 0) {
    410 			while (*r)
    411 				STPUTC(*r++, dest);
    412 			s += plen;
    413 			*p = '\0';	/* so no more matches */
    414 		} else
    415 			STPUTC(*s++, dest);
    416 	}
    417 	STACKSTRNUL(dest);
    418 	dest = grabstackstr(dest);
    419 
    420 	return (dest);
    421 }
    422 
    423 int
    424 not_fcnumber(s)
    425         char *s;
    426 {
    427 	if (s == NULL)
    428 		return 0;
    429         if (*s == '-')
    430                 s++;
    431 	return (!is_number(s));
    432 }
    433 
    434 int
    435 str_to_event(str, last)
    436 	char *str;
    437 	int last;
    438 {
    439 	const HistEvent *he;
    440 	char *s = str;
    441 	int relative = 0;
    442 	int i;
    443 
    444 	he = history(hist, H_FIRST);
    445 	switch (*s) {
    446 	case '-':
    447 		relative = 1;
    448 		/*FALLTHROUGH*/
    449 	case '+':
    450 		s++;
    451 	}
    452 	if (is_number(s)) {
    453 		i = atoi(s);
    454 		if (relative) {
    455 			while (he != NULL && i--) {
    456 				he = history(hist, H_NEXT);
    457 			}
    458 			if (he == NULL)
    459 				he = history(hist, H_LAST);
    460 		} else {
    461 			he = history(hist, H_NEXT_EVENT, i);
    462 			if (he == NULL) {
    463 				/*
    464 				 * the notion of first and last is
    465 				 * backwards to that of the history package
    466 				 */
    467 				he = history(hist, last ? H_FIRST : H_LAST);
    468 			}
    469 		}
    470 		if (he == NULL)
    471 			error("history number %s not found (internal error)",
    472 			       str);
    473 	} else {
    474 		/*
    475 		 * pattern
    476 		 */
    477 		he = history(hist, H_PREV_STR, str);
    478 		if (he == NULL)
    479 			error("history pattern not found: %s", str);
    480 	}
    481 	return (he->num);
    482 }
    483