Home | History | Annotate | Line # | Download | only in sh
histedit.c revision 1.12
      1 /*	$NetBSD: histedit.c,v 1.12 1997/03/14 01:42:20 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.12 1997/03/14 01:42:20 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 SMALL
     63 #include "myhistedit.h"
     64 #include "error.h"
     65 #include "eval.h"
     66 #include "memalloc.h"
     67 
     68 #define MAXHISTLOOPS	4	/* max recursions through fc */
     69 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
     70 
     71 History *hist;	/* history cookie */
     72 EditLine *el;	/* editline cookie */
     73 int displayhist;
     74 static FILE *el_in, *el_out;
     75 
     76 STATIC char *fc_replace __P((const char *, char *, char *));
     77 
     78 /*
     79  * Set history and editing status.  Called whenever the status may
     80  * have changed (figures out what to do).
     81  */
     82 void
     83 histedit()
     84 {
     85 
     86 #define editing (Eflag || Vflag)
     87 
     88 	if (iflag) {
     89 		if (!hist) {
     90 			/*
     91 			 * turn history on
     92 			 */
     93 			INTOFF;
     94 			hist = history_init();
     95 			INTON;
     96 
     97 			if (hist != NULL)
     98 				sethistsize(histsizeval());
     99 			else
    100 				out2str("sh: can't initialize history\n");
    101 		}
    102 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
    103 			/*
    104 			 * turn editing on
    105 			 */
    106 			INTOFF;
    107 			if (el_in == NULL)
    108 				el_in = fdopen(0, "r");
    109 			if (el_out == NULL)
    110 				el_out = fdopen(2, "w");
    111 			if (el_in == NULL || el_out == NULL)
    112 				goto bad;
    113 			el = el_init(arg0, el_in, el_out);
    114 			if (el != NULL) {
    115 				if (hist)
    116 					el_set(el, EL_HIST, history, hist);
    117 				el_set(el, EL_PROMPT, getprompt);
    118 			} else {
    119 bad:
    120 				out2str("sh: can't initialize editing\n");
    121 			}
    122 			INTON;
    123 		} else if (!editing && el) {
    124 			INTOFF;
    125 			el_end(el);
    126 			el = NULL;
    127 			INTON;
    128 		}
    129 		if (el) {
    130 			if (Vflag)
    131 				el_set(el, EL_EDITOR, "vi");
    132 			else if (Eflag)
    133 				el_set(el, EL_EDITOR, "emacs");
    134 		}
    135 	} else {
    136 		INTOFF;
    137 		if (el) {	/* no editing if not interactive */
    138 			el_end(el);
    139 			el = NULL;
    140 		}
    141 		if (hist) {
    142 			history_end(hist);
    143 			hist = NULL;
    144 		}
    145 		INTON;
    146 	}
    147 }
    148 
    149 
    150 void
    151 sethistsize(hs)
    152 	const char *hs;
    153 {
    154 	int histsize;
    155 
    156 	if (hist != NULL) {
    157 		if (hs == NULL || *hs == '\0' ||
    158 		   (histsize = atoi(hs)) < 0)
    159 			histsize = 100;
    160 		history(hist, H_EVENT, histsize);
    161 	}
    162 }
    163 
    164 /*
    165  *  This command is provided since POSIX decided to standardize
    166  *  the Korn shell fc command.  Oh well...
    167  */
    168 int
    169 histcmd(argc, argv)
    170 	int argc;
    171 	char **argv;
    172 {
    173 	extern char *optarg;
    174 	extern int optind, optopt, optreset;
    175 	int ch;
    176 	char *editor = NULL;
    177 	const HistEvent *he;
    178 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
    179 	int i;
    180 	char *firststr, *laststr;
    181 	int first, last, direction;
    182 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
    183 	static int active = 0;
    184 	struct jmploc jmploc;
    185 	struct jmploc *volatile savehandler;
    186 	char editfile[MAXPATHLEN + 1];
    187 	FILE *efp;
    188 #ifdef __GNUC__
    189 	/* Avoid longjmp clobbering */
    190 	(void) &editor;
    191 	(void) &lflg;
    192 	(void) &nflg;
    193 	(void) &rflg;
    194 	(void) &sflg;
    195 	(void) &firststr;
    196 	(void) &laststr;
    197 	(void) &pat;
    198 	(void) &repl;
    199 	(void) &efp;
    200 	(void) &argc;
    201 	(void) &argv;
    202 #endif
    203 
    204 	if (hist == NULL)
    205 		error("history not active");
    206 
    207 	if (argc == 1)
    208 		error("missing history argument");
    209 
    210 	optreset = 1; optind = 1; /* initialize getopt */
    211 	while (not_fcnumber(argv[optind]) &&
    212 	      (ch = getopt(argc, argv, ":e:lnrs")) != EOF)
    213 		switch ((char)ch) {
    214 		case 'e':
    215 			editor = optarg;
    216 			break;
    217 		case 'l':
    218 			lflg = 1;
    219 			break;
    220 		case 'n':
    221 			nflg = 1;
    222 			break;
    223 		case 'r':
    224 			rflg = 1;
    225 			break;
    226 		case 's':
    227 			sflg = 1;
    228 			break;
    229 		case ':':
    230 			error("option -%c expects argument", optopt);
    231 		case '?':
    232 		default:
    233 			error("unknown option: -%c", optopt);
    234 		}
    235 	argc -= optind, argv += optind;
    236 
    237 	/*
    238 	 * If executing...
    239 	 */
    240 	if (lflg == 0 || editor || sflg) {
    241 		lflg = 0;	/* ignore */
    242 		editfile[0] = '\0';
    243 		/*
    244 		 * Catch interrupts to reset active counter and
    245 		 * cleanup temp files.
    246 		 */
    247 		if (setjmp(jmploc.loc)) {
    248 			active = 0;
    249 			if (*editfile)
    250 				unlink(editfile);
    251 			handler = savehandler;
    252 			longjmp(handler->loc, 1);
    253 		}
    254 		savehandler = handler;
    255 		handler = &jmploc;
    256 		if (++active > MAXHISTLOOPS) {
    257 			active = 0;
    258 			displayhist = 0;
    259 			error("called recursively too many times");
    260 		}
    261 		/*
    262 		 * Set editor.
    263 		 */
    264 		if (sflg == 0) {
    265 			if (editor == NULL &&
    266 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
    267 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
    268 				editor = DEFEDITOR;
    269 			if (editor[0] == '-' && editor[1] == '\0') {
    270 				sflg = 1;	/* no edit */
    271 				editor = NULL;
    272 			}
    273 		}
    274 	}
    275 
    276 	/*
    277 	 * If executing, parse [old=new] now
    278 	 */
    279 	if (lflg == 0 && argc > 0 &&
    280 	     ((repl = strchr(argv[0], '=')) != NULL)) {
    281 		pat = argv[0];
    282 		*repl++ = '\0';
    283 		argc--, argv++;
    284 	}
    285 	/*
    286 	 * determine [first] and [last]
    287 	 */
    288 	switch (argc) {
    289 	case 0:
    290 		firststr = lflg ? "-16" : "-1";
    291 		laststr = "-1";
    292 		break;
    293 	case 1:
    294 		firststr = argv[0];
    295 		laststr = lflg ? "-1" : argv[0];
    296 		break;
    297 	case 2:
    298 		firststr = argv[0];
    299 		laststr = argv[1];
    300 		break;
    301 	default:
    302 		error("too many args");
    303 	}
    304 	/*
    305 	 * Turn into event numbers.
    306 	 */
    307 	first = str_to_event(firststr, 0);
    308 	last = str_to_event(laststr, 1);
    309 
    310 	if (rflg) {
    311 		i = last;
    312 		last = first;
    313 		first = i;
    314 	}
    315 	/*
    316 	 * XXX - this should not depend on the event numbers
    317 	 * always increasing.  Add sequence numbers or offset
    318 	 * to the history element in next (diskbased) release.
    319 	 */
    320 	direction = first < last ? H_PREV : H_NEXT;
    321 
    322 	/*
    323 	 * If editing, grab a temp file.
    324 	 */
    325 	if (editor) {
    326 		int fd;
    327 		INTOFF;		/* easier */
    328 		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
    329 		if ((fd = mkstemp(editfile)) < 0)
    330 			error("can't create temporary file %s", editfile);
    331 		if ((efp = fdopen(fd, "w")) == NULL) {
    332 			close(fd);
    333 			error("can't allocate stdio buffer for temp");
    334 		}
    335 	}
    336 
    337 	/*
    338 	 * Loop through selected history events.  If listing or executing,
    339 	 * do it now.  Otherwise, put into temp file and call the editor
    340 	 * after.
    341 	 *
    342 	 * The history interface needs rethinking, as the following
    343 	 * convolutions will demonstrate.
    344 	 */
    345 	history(hist, H_FIRST);
    346 	he = history(hist, H_NEXT_EVENT, first);
    347 	for (;he != NULL; he = history(hist, direction)) {
    348 		if (lflg) {
    349 			if (!nflg)
    350 				out1fmt("%5d ", he->num);
    351 			out1str(he->str);
    352 		} else {
    353 			char *s = pat ?
    354 			   fc_replace(he->str, pat, repl) : (char *)he->str;
    355 
    356 			if (sflg) {
    357 				if (displayhist) {
    358 					out2str(s);
    359 				}
    360 				evalstring(s);
    361 				if (displayhist && hist) {
    362 					/*
    363 					 *  XXX what about recursive and
    364 					 *  relative histnums.
    365 					 */
    366 					history(hist, H_ENTER, s);
    367 				}
    368 			} else
    369 				fputs(s, efp);
    370 		}
    371 		/*
    372 		 * At end?  (if we were to loose last, we'd sure be
    373 		 * messed up).
    374 		 */
    375 		if (he->num == last)
    376 			break;
    377 	}
    378 	if (editor) {
    379 		char *editcmd;
    380 
    381 		fclose(efp);
    382 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
    383 		sprintf(editcmd, "%s %s", editor, editfile);
    384 		evalstring(editcmd);	/* XXX - should use no JC command */
    385 		INTON;
    386 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
    387 		unlink(editfile);
    388 	}
    389 
    390 	if (lflg == 0 && active > 0)
    391 		--active;
    392 	if (displayhist)
    393 		displayhist = 0;
    394 	return 0;
    395 }
    396 
    397 STATIC char *
    398 fc_replace(s, p, r)
    399 	const char *s;
    400 	char *p, *r;
    401 {
    402 	char *dest;
    403 	int plen = strlen(p);
    404 
    405 	STARTSTACKSTR(dest);
    406 	while (*s) {
    407 		if (*s == *p && strncmp(s, p, plen) == 0) {
    408 			while (*r)
    409 				STPUTC(*r++, dest);
    410 			s += plen;
    411 			*p = '\0';	/* so no more matches */
    412 		} else
    413 			STPUTC(*s++, dest);
    414 	}
    415 	STACKSTRNUL(dest);
    416 	dest = grabstackstr(dest);
    417 
    418 	return (dest);
    419 }
    420 
    421 int
    422 not_fcnumber(s)
    423         char *s;
    424 {
    425 	if (s == NULL)
    426 		return 0;
    427         if (*s == '-')
    428                 s++;
    429 	return (!is_number(s));
    430 }
    431 
    432 int
    433 str_to_event(str, last)
    434 	char *str;
    435 	int last;
    436 {
    437 	const HistEvent *he;
    438 	char *s = str;
    439 	int relative = 0;
    440 	int i;
    441 
    442 	he = history(hist, H_FIRST);
    443 	switch (*s) {
    444 	case '-':
    445 		relative = 1;
    446 		/*FALLTHROUGH*/
    447 	case '+':
    448 		s++;
    449 	}
    450 	if (is_number(s)) {
    451 		i = atoi(s);
    452 		if (relative) {
    453 			while (he != NULL && i--) {
    454 				he = history(hist, H_NEXT);
    455 			}
    456 			if (he == NULL)
    457 				he = history(hist, H_LAST);
    458 		} else {
    459 			he = history(hist, H_NEXT_EVENT, i);
    460 			if (he == NULL) {
    461 				/*
    462 				 * the notion of first and last is
    463 				 * backwards to that of the history package
    464 				 */
    465 				he = history(hist, last ? H_FIRST : H_LAST);
    466 			}
    467 		}
    468 		if (he == NULL)
    469 			error("history number %s not found (internal error)",
    470 			       str);
    471 	} else {
    472 		/*
    473 		 * pattern
    474 		 */
    475 		he = history(hist, H_PREV_STR, str);
    476 		if (he == NULL)
    477 			error("history pattern not found: %s", str);
    478 	}
    479 	return (he->num);
    480 }
    481 #else
    482 int
    483 histcmd(argc, argv)
    484 	int argc;
    485 	char **argv;
    486 {
    487 	error("not compiled with history support");
    488 }
    489 #endif
    490