11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD$");
401556Srgrimes
4117987Speter#include <sys/param.h>
4277463Simp#include <limits.h>
4317987Speter#include <paths.h>
4417987Speter#include <stdio.h>
4517987Speter#include <stdlib.h>
4617987Speter#include <unistd.h>
471556Srgrimes/*
481556Srgrimes * Editline and history functions (and glue).
491556Srgrimes */
501556Srgrimes#include "shell.h"
511556Srgrimes#include "parser.h"
521556Srgrimes#include "var.h"
531556Srgrimes#include "options.h"
5417987Speter#include "main.h"
5517987Speter#include "output.h"
561556Srgrimes#include "mystring.h"
5717987Speter#ifndef NO_HISTORY
5817987Speter#include "myhistedit.h"
591556Srgrimes#include "error.h"
6017987Speter#include "eval.h"
611556Srgrimes#include "memalloc.h"
62223060Sjilles#include "builtins.h"
631556Srgrimes
641556Srgrimes#define MAXHISTLOOPS	4	/* max recursions through fc */
651556Srgrimes#define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
661556Srgrimes
671556SrgrimesHistory *hist;	/* history cookie */
681556SrgrimesEditLine *el;	/* editline cookie */
691556Srgrimesint displayhist;
7084261Sobrienstatic FILE *el_in, *el_out, *el_err;
711556Srgrimes
72213811Sobrienstatic char *fc_replace(const char *, char *, char *);
73231790Sjillesstatic int not_fcnumber(const char *);
74231790Sjillesstatic int str_to_event(const char *, int);
751556Srgrimes
761556Srgrimes/*
771556Srgrimes * Set history and editing status.  Called whenever the status may
781556Srgrimes * have changed (figures out what to do).
791556Srgrimes */
8017987Spetervoid
8190111Simphistedit(void)
8217987Speter{
831556Srgrimes
841556Srgrimes#define editing (Eflag || Vflag)
851556Srgrimes
861556Srgrimes	if (iflag) {
871556Srgrimes		if (!hist) {
881556Srgrimes			/*
891556Srgrimes			 * turn history on
901556Srgrimes			 */
911556Srgrimes			INTOFF;
921556Srgrimes			hist = history_init();
931556Srgrimes			INTON;
941556Srgrimes
951556Srgrimes			if (hist != NULL)
9620425Ssteve				sethistsize(histsizeval());
971556Srgrimes			else
98199629Sjilles				out2fmt_flush("sh: can't initialize history\n");
991556Srgrimes		}
1001556Srgrimes		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
1011556Srgrimes			/*
1021556Srgrimes			 * turn editing on
1031556Srgrimes			 */
104208755Sjilles			char *term;
105208755Sjilles
1061556Srgrimes			INTOFF;
1071556Srgrimes			if (el_in == NULL)
1081556Srgrimes				el_in = fdopen(0, "r");
10984261Sobrien			if (el_err == NULL)
11084261Sobrien				el_err = fdopen(1, "w");
1111556Srgrimes			if (el_out == NULL)
1121556Srgrimes				el_out = fdopen(2, "w");
11384261Sobrien			if (el_in == NULL || el_err == NULL || el_out == NULL)
1141556Srgrimes				goto bad;
115208755Sjilles			term = lookupvar("TERM");
116208755Sjilles			if (term)
117208755Sjilles				setenv("TERM", term, 1);
118208755Sjilles			else
119208755Sjilles				unsetenv("TERM");
12084261Sobrien			el = el_init(arg0, el_in, el_out, el_err);
1211556Srgrimes			if (el != NULL) {
1221556Srgrimes				if (hist)
1231556Srgrimes					el_set(el, EL_HIST, history, hist);
1241556Srgrimes				el_set(el, EL_PROMPT, getprompt);
125209221Sjilles				el_set(el, EL_ADDFN, "sh-complete",
126209221Sjilles				    "Filename completion",
127209221Sjilles				    _el_fn_sh_complete);
1281556Srgrimes			} else {
1291556Srgrimesbad:
130199629Sjilles				out2fmt_flush("sh: can't initialize editing\n");
1311556Srgrimes			}
1321556Srgrimes			INTON;
1331556Srgrimes		} else if (!editing && el) {
1341556Srgrimes			INTOFF;
1351556Srgrimes			el_end(el);
1361556Srgrimes			el = NULL;
1371556Srgrimes			INTON;
1381556Srgrimes		}
1391556Srgrimes		if (el) {
1401556Srgrimes			if (Vflag)
1411556Srgrimes				el_set(el, EL_EDITOR, "vi");
1421556Srgrimes			else if (Eflag)
1431556Srgrimes				el_set(el, EL_EDITOR, "emacs");
144209221Sjilles			el_set(el, EL_BIND, "^I", "sh-complete", NULL);
145100568Stjr			el_source(el, NULL);
1461556Srgrimes		}
1471556Srgrimes	} else {
1481556Srgrimes		INTOFF;
1491556Srgrimes		if (el) {	/* no editing if not interactive */
1501556Srgrimes			el_end(el);
1511556Srgrimes			el = NULL;
1521556Srgrimes		}
1531556Srgrimes		if (hist) {
1541556Srgrimes			history_end(hist);
1551556Srgrimes			hist = NULL;
1561556Srgrimes		}
1571556Srgrimes		INTON;
1581556Srgrimes	}
1591556Srgrimes}
1601556Srgrimes
16117987Speter
16217987Spetervoid
16320425Sstevesethistsize(hs)
16420425Ssteve	const char *hs;
16517987Speter{
1661556Srgrimes	int histsize;
16784261Sobrien	HistEvent he;
1681556Srgrimes
1691556Srgrimes	if (hist != NULL) {
17020425Ssteve		if (hs == NULL || *hs == '\0' ||
17120425Ssteve		   (histsize = atoi(hs)) < 0)
1721556Srgrimes			histsize = 100;
173151471Sstefanf		history(hist, &he, H_SETSIZE, histsize);
174210736Sjilles		history(hist, &he, H_SETUNIQUE, 1);
1751556Srgrimes	}
1761556Srgrimes}
1771556Srgrimes
178208755Sjillesvoid
179208755Sjillessetterm(const char *term)
180208755Sjilles{
181208755Sjilles	if (rootshell && el != NULL && term != NULL)
182208755Sjilles		el_set(el, EL_TERMINAL, term);
183208755Sjilles}
184208755Sjilles
18517987Speterint
18690111Simphistcmd(int argc, char **argv)
1871556Srgrimes{
1881556Srgrimes	int ch;
189201053Sjilles	const char *editor = NULL;
19084261Sobrien	HistEvent he;
1911556Srgrimes	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
19284261Sobrien	int i, retval;
193201053Sjilles	const char *firststr, *laststr;
1941556Srgrimes	int first, last, direction;
195201053Sjilles	char *pat = NULL, *repl = NULL;
1961556Srgrimes	static int active = 0;
1971556Srgrimes	struct jmploc jmploc;
198194765Sjilles	struct jmploc *savehandler;
199194765Sjilles	char editfilestr[PATH_MAX];
200194765Sjilles	char *volatile editfile;
201201053Sjilles	FILE *efp = NULL;
20297730Stjr	int oldhistnum;
2031556Srgrimes
2041556Srgrimes	if (hist == NULL)
2051556Srgrimes		error("history not active");
2068855Srgrimes
2071556Srgrimes	if (argc == 1)
2081556Srgrimes		error("missing history argument");
2091556Srgrimes
2101556Srgrimes	optreset = 1; optind = 1; /* initialize getopt */
211100663Stjr	opterr = 0;
2121556Srgrimes	while (not_fcnumber(argv[optind]) &&
21324348Simp	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
2141556Srgrimes		switch ((char)ch) {
2151556Srgrimes		case 'e':
21697731Stjr			editor = optarg;
2171556Srgrimes			break;
2181556Srgrimes		case 'l':
2191556Srgrimes			lflg = 1;
2201556Srgrimes			break;
2211556Srgrimes		case 'n':
2221556Srgrimes			nflg = 1;
2231556Srgrimes			break;
2241556Srgrimes		case 'r':
2251556Srgrimes			rflg = 1;
2261556Srgrimes			break;
2271556Srgrimes		case 's':
2281556Srgrimes			sflg = 1;
2291556Srgrimes			break;
2301556Srgrimes		case ':':
2311556Srgrimes			error("option -%c expects argument", optopt);
2321556Srgrimes		case '?':
2331556Srgrimes		default:
2341556Srgrimes			error("unknown option: -%c", optopt);
2351556Srgrimes		}
2361556Srgrimes	argc -= optind, argv += optind;
2371556Srgrimes
238216806Sjilles	savehandler = handler;
2391556Srgrimes	/*
2401556Srgrimes	 * If executing...
2411556Srgrimes	 */
2421556Srgrimes	if (lflg == 0 || editor || sflg) {
2431556Srgrimes		lflg = 0;	/* ignore */
244194765Sjilles		editfile = NULL;
2451556Srgrimes		/*
2461556Srgrimes		 * Catch interrupts to reset active counter and
2471556Srgrimes		 * cleanup temp files.
2481556Srgrimes		 */
2491556Srgrimes		if (setjmp(jmploc.loc)) {
2501556Srgrimes			active = 0;
251194765Sjilles			if (editfile)
2521556Srgrimes				unlink(editfile);
2531556Srgrimes			handler = savehandler;
2541556Srgrimes			longjmp(handler->loc, 1);
2551556Srgrimes		}
2561556Srgrimes		handler = &jmploc;
2571556Srgrimes		if (++active > MAXHISTLOOPS) {
2581556Srgrimes			active = 0;
2591556Srgrimes			displayhist = 0;
2601556Srgrimes			error("called recursively too many times");
2611556Srgrimes		}
2621556Srgrimes		/*
2631556Srgrimes		 * Set editor.
2641556Srgrimes		 */
2651556Srgrimes		if (sflg == 0) {
2661556Srgrimes			if (editor == NULL &&
2671556Srgrimes			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
2681556Srgrimes			    (editor = bltinlookup("EDITOR", 1)) == NULL)
2691556Srgrimes				editor = DEFEDITOR;
2701556Srgrimes			if (editor[0] == '-' && editor[1] == '\0') {
2711556Srgrimes				sflg = 1;	/* no edit */
2721556Srgrimes				editor = NULL;
2731556Srgrimes			}
2741556Srgrimes		}
2751556Srgrimes	}
2761556Srgrimes
2771556Srgrimes	/*
2781556Srgrimes	 * If executing, parse [old=new] now
2791556Srgrimes	 */
2808855Srgrimes	if (lflg == 0 && argc > 0 &&
2811556Srgrimes	     ((repl = strchr(argv[0], '=')) != NULL)) {
2821556Srgrimes		pat = argv[0];
2831556Srgrimes		*repl++ = '\0';
2841556Srgrimes		argc--, argv++;
2851556Srgrimes	}
2861556Srgrimes	/*
2871556Srgrimes	 * determine [first] and [last]
2881556Srgrimes	 */
2891556Srgrimes	switch (argc) {
2901556Srgrimes	case 0:
2911556Srgrimes		firststr = lflg ? "-16" : "-1";
2921556Srgrimes		laststr = "-1";
2931556Srgrimes		break;
2941556Srgrimes	case 1:
2951556Srgrimes		firststr = argv[0];
2961556Srgrimes		laststr = lflg ? "-1" : argv[0];
2971556Srgrimes		break;
2981556Srgrimes	case 2:
2991556Srgrimes		firststr = argv[0];
3001556Srgrimes		laststr = argv[1];
3011556Srgrimes		break;
3021556Srgrimes	default:
303214538Sjilles		error("too many arguments");
3041556Srgrimes	}
3051556Srgrimes	/*
3061556Srgrimes	 * Turn into event numbers.
3071556Srgrimes	 */
3081556Srgrimes	first = str_to_event(firststr, 0);
3091556Srgrimes	last = str_to_event(laststr, 1);
3101556Srgrimes
3111556Srgrimes	if (rflg) {
3121556Srgrimes		i = last;
3131556Srgrimes		last = first;
3141556Srgrimes		first = i;
3151556Srgrimes	}
3161556Srgrimes	/*
3171556Srgrimes	 * XXX - this should not depend on the event numbers
3188855Srgrimes	 * always increasing.  Add sequence numbers or offset
3191556Srgrimes	 * to the history element in next (diskbased) release.
3201556Srgrimes	 */
3211556Srgrimes	direction = first < last ? H_PREV : H_NEXT;
3221556Srgrimes
3231556Srgrimes	/*
3241556Srgrimes	 * If editing, grab a temp file.
3251556Srgrimes	 */
3261556Srgrimes	if (editor) {
3271556Srgrimes		int fd;
3281556Srgrimes		INTOFF;		/* easier */
329194765Sjilles		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
330194765Sjilles		if ((fd = mkstemp(editfilestr)) < 0)
3311556Srgrimes			error("can't create temporary file %s", editfile);
332194765Sjilles		editfile = editfilestr;
3331556Srgrimes		if ((efp = fdopen(fd, "w")) == NULL) {
3341556Srgrimes			close(fd);
335214538Sjilles			error("Out of space");
3361556Srgrimes		}
3371556Srgrimes	}
3381556Srgrimes
3391556Srgrimes	/*
3401556Srgrimes	 * Loop through selected history events.  If listing or executing,
3411556Srgrimes	 * do it now.  Otherwise, put into temp file and call the editor
3421556Srgrimes	 * after.
3431556Srgrimes	 *
3441556Srgrimes	 * The history interface needs rethinking, as the following
3451556Srgrimes	 * convolutions will demonstrate.
3461556Srgrimes	 */
34784261Sobrien	history(hist, &he, H_FIRST);
34884261Sobrien	retval = history(hist, &he, H_NEXT_EVENT, first);
34984261Sobrien	for (;retval != -1; retval = history(hist, &he, direction)) {
3501556Srgrimes		if (lflg) {
3511556Srgrimes			if (!nflg)
35284261Sobrien				out1fmt("%5d ", he.num);
35384261Sobrien			out1str(he.str);
3541556Srgrimes		} else {
3558855Srgrimes			char *s = pat ?
35684261Sobrien			   fc_replace(he.str, pat, repl) : (char *)he.str;
3571556Srgrimes
3581556Srgrimes			if (sflg) {
3591556Srgrimes				if (displayhist) {
3601556Srgrimes					out2str(s);
361199629Sjilles					flushout(out2);
3621556Srgrimes				}
363193169Sstefanf				evalstring(s, 0);
3641556Srgrimes				if (displayhist && hist) {
3651556Srgrimes					/*
3668855Srgrimes					 *  XXX what about recursive and
3671556Srgrimes					 *  relative histnums.
3681556Srgrimes					 */
36997730Stjr					oldhistnum = he.num;
37084261Sobrien					history(hist, &he, H_ENTER, s);
37197730Stjr					/*
37297730Stjr					 * XXX H_ENTER moves the internal
37397730Stjr					 * cursor, set it back to the current
37497730Stjr					 * entry.
37597730Stjr					 */
37697730Stjr					retval = history(hist, &he,
37797730Stjr					    H_NEXT_EVENT, oldhistnum);
3781556Srgrimes				}
3791556Srgrimes			} else
3801556Srgrimes				fputs(s, efp);
3811556Srgrimes		}
3821556Srgrimes		/*
383160964Syar		 * At end?  (if we were to lose last, we'd sure be
3841556Srgrimes		 * messed up).
3851556Srgrimes		 */
38684261Sobrien		if (he.num == last)
3871556Srgrimes			break;
3881556Srgrimes	}
3891556Srgrimes	if (editor) {
3901556Srgrimes		char *editcmd;
3911556Srgrimes
3921556Srgrimes		fclose(efp);
3931556Srgrimes		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
3941556Srgrimes		sprintf(editcmd, "%s %s", editor, editfile);
395193169Sstefanf		evalstring(editcmd, 0);	/* XXX - should use no JC command */
3961556Srgrimes		INTON;
3971556Srgrimes		readcmdfile(editfile);	/* XXX - should read back - quick tst */
3981556Srgrimes		unlink(editfile);
3991556Srgrimes	}
4008855Srgrimes
4011556Srgrimes	if (lflg == 0 && active > 0)
4021556Srgrimes		--active;
4031556Srgrimes	if (displayhist)
4041556Srgrimes		displayhist = 0;
405216806Sjilles	handler = savehandler;
40617987Speter	return 0;
4071556Srgrimes}
4081556Srgrimes
409213811Sobrienstatic char *
41090111Simpfc_replace(const char *s, char *p, char *r)
4111556Srgrimes{
4121556Srgrimes	char *dest;
4131556Srgrimes	int plen = strlen(p);
4141556Srgrimes
4151556Srgrimes	STARTSTACKSTR(dest);
4161556Srgrimes	while (*s) {
4171556Srgrimes		if (*s == *p && strncmp(s, p, plen) == 0) {
418215783Sjilles			STPUTS(r, dest);
4191556Srgrimes			s += plen;
4201556Srgrimes			*p = '\0';	/* so no more matches */
4211556Srgrimes		} else
4221556Srgrimes			STPUTC(*s++, dest);
4231556Srgrimes	}
424213814Sobrien	STPUTC('\0', dest);
4251556Srgrimes	dest = grabstackstr(dest);
4261556Srgrimes
4271556Srgrimes	return (dest);
4281556Srgrimes}
4291556Srgrimes
430231790Sjillesstatic int
431200956Sjillesnot_fcnumber(const char *s)
4321556Srgrimes{
43320425Ssteve	if (s == NULL)
43425224Ssteve		return (0);
43520425Ssteve	if (*s == '-')
43620425Ssteve		s++;
4371556Srgrimes	return (!is_number(s));
4381556Srgrimes}
4391556Srgrimes
440231790Sjillesstatic int
441200956Sjillesstr_to_event(const char *str, int last)
4421556Srgrimes{
44384261Sobrien	HistEvent he;
444200956Sjilles	const char *s = str;
4451556Srgrimes	int relative = 0;
44684261Sobrien	int i, retval;
4471556Srgrimes
44884261Sobrien	retval = history(hist, &he, H_FIRST);
4491556Srgrimes	switch (*s) {
4501556Srgrimes	case '-':
4511556Srgrimes		relative = 1;
4521556Srgrimes		/*FALLTHROUGH*/
4531556Srgrimes	case '+':
4541556Srgrimes		s++;
4551556Srgrimes	}
4561556Srgrimes	if (is_number(s)) {
4571556Srgrimes		i = atoi(s);
4581556Srgrimes		if (relative) {
45984261Sobrien			while (retval != -1 && i--) {
46084261Sobrien				retval = history(hist, &he, H_NEXT);
4611556Srgrimes			}
46284261Sobrien			if (retval == -1)
46384261Sobrien				retval = history(hist, &he, H_LAST);
4641556Srgrimes		} else {
46584261Sobrien			retval = history(hist, &he, H_NEXT_EVENT, i);
46684261Sobrien			if (retval == -1) {
4671556Srgrimes				/*
4681556Srgrimes				 * the notion of first and last is
4691556Srgrimes				 * backwards to that of the history package
4701556Srgrimes				 */
47184261Sobrien				retval = history(hist, &he, last ? H_FIRST : H_LAST);
4721556Srgrimes			}
4731556Srgrimes		}
47484261Sobrien		if (retval == -1)
4751556Srgrimes			error("history number %s not found (internal error)",
4761556Srgrimes			       str);
4771556Srgrimes	} else {
4781556Srgrimes		/*
4798855Srgrimes		 * pattern
4801556Srgrimes		 */
48184261Sobrien		retval = history(hist, &he, H_PREV_STR, str);
48284261Sobrien		if (retval == -1)
4831556Srgrimes			error("history pattern not found: %s", str);
4841556Srgrimes	}
48584261Sobrien	return (he.num);
4861556Srgrimes}
487100565Stjr
488100565Stjrint
489100565Stjrbindcmd(int argc, char **argv)
490100565Stjr{
491100565Stjr
492100565Stjr	if (el == NULL)
493100565Stjr		error("line editing is disabled");
494148974Sstefanf	return (el_parse(el, argc, (const char **)argv));
495100565Stjr}
496100565Stjr
49725224Ssteve#else
49825224Ssteve#include "error.h"
49925224Ssteve
50025224Ssteveint
50190111Simphistcmd(int argc, char **argv)
50225224Ssteve{
50325224Ssteve
50425224Ssteve	error("not compiled with history support");
50525224Ssteve	/*NOTREACHED*/
50625224Ssteve	return (0);
50725224Ssteve}
508100565Stjr
509100565Stjrint
510100565Stjrbindcmd(int argc, char **argv)
511100565Stjr{
512100565Stjr
513100565Stjr	error("not compiled with line editing support");
514100565Stjr	return (0);
515100565Stjr}
51625224Ssteve#endif
517