Home | History | Annotate | Line # | Download | only in sh
histedit.c revision 1.6
      1 /*	$NetBSD: histedit.c,v 1.6 1995/03/21 09:09:09 cgd 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.1 (Berkeley) 5/31/93";
     42 #else
     43 static char rcsid[] = "$NetBSD: histedit.c,v 1.6 1995/03/21 09:09:09 cgd Exp $";
     44 #endif
     45 #endif /* not lint */
     46 
     47 /*
     48  * Editline and history functions (and glue).
     49  */
     50 #include <sys/param.h>
     51 #include <paths.h>
     52 #include <stdio.h>
     53 #include <stdlib.h>
     54 #include <unistd.h>
     55 #include "shell.h"
     56 #include "parser.h"
     57 #include "var.h"
     58 #include "options.h"
     59 #include "output.h"
     60 #include "mystring.h"
     61 #include "error.h"
     62 #include "eval.h"
     63 #include "histedit.h"
     64 #include "memalloc.h"
     65 #include "extern.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 
     75 STATIC char *fc_replace __P((const char *, char *, char *));
     76 int not_fcnumber __P((char *));
     77 int str_to_event __P((char *, int));
     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 	char *cp;
    154 	int histsize;
    155 
    156 	if (hist != NULL) {
    157 		cp = lookupvar("HISTSIZE");
    158 		if (cp == NULL || *cp == '\0' ||
    159 		   (histsize = atoi(cp)) < 0)
    160 			histsize = 100;
    161 		history(hist, H_EVENT, histsize);
    162 	}
    163 }
    164 
    165 /*
    166  *  This command is provided since POSIX decided to standardize
    167  *  the Korn shell fc command.  Oh well...
    168  */
    169 int
    170 histcmd(argc, argv)
    171 	int argc;
    172 	char *argv[];
    173 {
    174 	extern char *optarg;
    175 	extern int optind, optopt, optreset;
    176 	int ch;
    177 	char *editor = NULL;
    178 	const HistEvent *he;
    179 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
    180 	int i;
    181 	char *firststr, *laststr;
    182 	int first, last, direction;
    183 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
    184 	static int active = 0;
    185 	struct jmploc jmploc;
    186 	struct jmploc *volatile savehandler;
    187 	char editfile[MAXPATHLEN + 1];
    188 	FILE *efp;
    189 
    190 	if (hist == NULL)
    191 		error("history not active");
    192 
    193 	if (argc == 1)
    194 		error("missing history argument");
    195 
    196 	optreset = 1; optind = 1; /* initialize getopt */
    197 	while (not_fcnumber(argv[optind]) &&
    198 	      (ch = getopt(argc, argv, ":e:lnrs")) != EOF)
    199 		switch ((char)ch) {
    200 		case 'e':
    201 			editor = optarg;
    202 			break;
    203 		case 'l':
    204 			lflg = 1;
    205 			break;
    206 		case 'n':
    207 			nflg = 1;
    208 			break;
    209 		case 'r':
    210 			rflg = 1;
    211 			break;
    212 		case 's':
    213 			sflg = 1;
    214 			break;
    215 		case ':':
    216 			error("option -%c expects argument", optopt);
    217 		case '?':
    218 		default:
    219 			error("unknown option: -%c", optopt);
    220 		}
    221 	argc -= optind, argv += optind;
    222 
    223 	/*
    224 	 * If executing...
    225 	 */
    226 	if (lflg == 0 || editor || sflg) {
    227 		lflg = 0;	/* ignore */
    228 		editfile[0] = '\0';
    229 		/*
    230 		 * Catch interrupts to reset active counter and
    231 		 * cleanup temp files.
    232 		 */
    233 		if (setjmp(jmploc.loc)) {
    234 			active = 0;
    235 			if (*editfile)
    236 				unlink(editfile);
    237 			handler = savehandler;
    238 			longjmp(handler->loc, 1);
    239 		}
    240 		savehandler = handler;
    241 		handler = &jmploc;
    242 		if (++active > MAXHISTLOOPS) {
    243 			active = 0;
    244 			displayhist = 0;
    245 			error("called recursively too many times");
    246 		}
    247 		/*
    248 		 * Set editor.
    249 		 */
    250 		if (sflg == 0) {
    251 			if (editor == NULL &&
    252 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
    253 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
    254 				editor = DEFEDITOR;
    255 			if (editor[0] == '-' && editor[1] == '\0') {
    256 				sflg = 1;	/* no edit */
    257 				editor = NULL;
    258 			}
    259 		}
    260 	}
    261 
    262 	/*
    263 	 * If executing, parse [old=new] now
    264 	 */
    265 	if (lflg == 0 && argc > 0 &&
    266 	     ((repl = strchr(argv[0], '=')) != NULL)) {
    267 		pat = argv[0];
    268 		*repl++ = '\0';
    269 		argc--, argv++;
    270 	}
    271 	/*
    272 	 * determine [first] and [last]
    273 	 */
    274 	switch (argc) {
    275 	case 0:
    276 		firststr = lflg ? "-16" : "-1";
    277 		laststr = "-1";
    278 		break;
    279 	case 1:
    280 		firststr = argv[0];
    281 		laststr = lflg ? "-1" : argv[0];
    282 		break;
    283 	case 2:
    284 		firststr = argv[0];
    285 		laststr = argv[1];
    286 		break;
    287 	default:
    288 		error("too many args");
    289 	}
    290 	/*
    291 	 * Turn into event numbers.
    292 	 */
    293 	first = str_to_event(firststr, 0);
    294 	last = str_to_event(laststr, 1);
    295 
    296 	if (rflg) {
    297 		i = last;
    298 		last = first;
    299 		first = i;
    300 	}
    301 	/*
    302 	 * XXX - this should not depend on the event numbers
    303 	 * always increasing.  Add sequence numbers or offset
    304 	 * to the history element in next (diskbased) release.
    305 	 */
    306 	direction = first < last ? H_PREV : H_NEXT;
    307 
    308 	/*
    309 	 * If editing, grab a temp file.
    310 	 */
    311 	if (editor) {
    312 		int fd;
    313 		INTOFF;		/* easier */
    314 		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
    315 		if ((fd = mkstemp(editfile)) < 0)
    316 			error("can't create temporary file %s", editfile);
    317 		if ((efp = fdopen(fd, "w")) == NULL) {
    318 			close(fd);
    319 			error("can't allocate stdio buffer for temp\n");
    320 		}
    321 	}
    322 
    323 	/*
    324 	 * Loop through selected history events.  If listing or executing,
    325 	 * do it now.  Otherwise, put into temp file and call the editor
    326 	 * after.
    327 	 *
    328 	 * The history interface needs rethinking, as the following
    329 	 * convolutions will demonstrate.
    330 	 */
    331 	history(hist, H_FIRST);
    332 	he = history(hist, H_NEXT_EVENT, first);
    333 	for (;he != NULL; he = history(hist, direction)) {
    334 		if (lflg) {
    335 			if (!nflg)
    336 				out1fmt("%5d ", he->num);
    337 			out1str(he->str);
    338 		} else {
    339 			char *s = pat ?
    340 			   fc_replace(he->str, pat, repl) : (char *)he->str;
    341 
    342 			if (sflg) {
    343 				if (displayhist) {
    344 					out2str(s);
    345 				}
    346 				evalstring(s);
    347 				if (displayhist && hist) {
    348 					/*
    349 					 *  XXX what about recursive and
    350 					 *  relative histnums.
    351 					 */
    352 					history(hist, H_ENTER, s);
    353 				}
    354 			} else
    355 				fputs(s, efp);
    356 		}
    357 		/*
    358 		 * At end?  (if we were to loose last, we'd sure be
    359 		 * messed up).
    360 		 */
    361 		if (he->num == last)
    362 			break;
    363 	}
    364 	if (editor) {
    365 		char *editcmd;
    366 
    367 		fclose(efp);
    368 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
    369 		sprintf(editcmd, "%s %s", editor, editfile);
    370 		evalstring(editcmd);	/* XXX - should use no JC command */
    371 		INTON;
    372 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
    373 		unlink(editfile);
    374 	}
    375 
    376 	if (lflg == 0 && active > 0)
    377 		--active;
    378 	if (displayhist)
    379 		displayhist = 0;
    380 }
    381 
    382 STATIC char *
    383 fc_replace(s, p, r)
    384 	const char *s;
    385 	char *p, *r;
    386 {
    387 	char *dest;
    388 	int plen = strlen(p);
    389 
    390 	STARTSTACKSTR(dest);
    391 	while (*s) {
    392 		if (*s == *p && strncmp(s, p, plen) == 0) {
    393 			while (*r)
    394 				STPUTC(*r++, dest);
    395 			s += plen;
    396 			*p = '\0';	/* so no more matches */
    397 		} else
    398 			STPUTC(*s++, dest);
    399 	}
    400 	STACKSTRNUL(dest);
    401 	dest = grabstackstr(dest);
    402 
    403 	return (dest);
    404 }
    405 
    406 int
    407 not_fcnumber(s)
    408         char *s;
    409 {
    410         if (*s == '-')
    411                 s++;
    412 	return (!is_number(s));
    413 }
    414 
    415 int
    416 str_to_event(str, last)
    417 	char *str;
    418 	int last;
    419 {
    420 	const HistEvent *he;
    421 	char *s = str;
    422 	int relative = 0;
    423 	int i;
    424 
    425 	he = history(hist, H_FIRST);
    426 	switch (*s) {
    427 	case '-':
    428 		relative = 1;
    429 		/*FALLTHROUGH*/
    430 	case '+':
    431 		s++;
    432 	}
    433 	if (is_number(s)) {
    434 		i = atoi(s);
    435 		if (relative) {
    436 			while (he != NULL && i--) {
    437 				he = history(hist, H_NEXT);
    438 			}
    439 			if (he == NULL)
    440 				he = history(hist, H_LAST);
    441 		} else {
    442 			he = history(hist, H_NEXT_EVENT, i);
    443 			if (he == NULL) {
    444 				/*
    445 				 * the notion of first and last is
    446 				 * backwards to that of the history package
    447 				 */
    448 				he = history(hist, last ? H_FIRST : H_LAST);
    449 			}
    450 		}
    451 		if (he == NULL)
    452 			error("history number %s not found (internal error)",
    453 			       str);
    454 	} else {
    455 		/*
    456 		 * pattern
    457 		 */
    458 		he = history(hist, H_PREV_STR, str);
    459 		if (he == NULL)
    460 			error("history pattern not found: %s", str);
    461 	}
    462 	return (he->num);
    463 }
    464