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