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