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