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 *);
73229220Sjillesstatic int not_fcnumber(const char *);
74229220Sjillesstatic 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
163230530Scharniersethistsize(const char *hs)
16417987Speter{
1651556Srgrimes	int histsize;
16684261Sobrien	HistEvent he;
1671556Srgrimes
1681556Srgrimes	if (hist != NULL) {
16920425Ssteve		if (hs == NULL || *hs == '\0' ||
17020425Ssteve		   (histsize = atoi(hs)) < 0)
1711556Srgrimes			histsize = 100;
172151471Sstefanf		history(hist, &he, H_SETSIZE, histsize);
173210736Sjilles		history(hist, &he, H_SETUNIQUE, 1);
1741556Srgrimes	}
1751556Srgrimes}
1761556Srgrimes
177208755Sjillesvoid
178208755Sjillessetterm(const char *term)
179208755Sjilles{
180208755Sjilles	if (rootshell && el != NULL && term != NULL)
181208755Sjilles		el_set(el, EL_TERMINAL, term);
182208755Sjilles}
183208755Sjilles
18417987Speterint
185240541Sjilleshistcmd(int argc, char **argv __unused)
1861556Srgrimes{
1871556Srgrimes	int ch;
188201053Sjilles	const char *editor = NULL;
18984261Sobrien	HistEvent he;
1901556Srgrimes	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
19184261Sobrien	int i, retval;
192201053Sjilles	const char *firststr, *laststr;
1931556Srgrimes	int first, last, direction;
194201053Sjilles	char *pat = NULL, *repl = NULL;
1951556Srgrimes	static int active = 0;
1961556Srgrimes	struct jmploc jmploc;
197194765Sjilles	struct jmploc *savehandler;
198194765Sjilles	char editfilestr[PATH_MAX];
199194765Sjilles	char *volatile editfile;
200201053Sjilles	FILE *efp = NULL;
20197730Stjr	int oldhistnum;
2021556Srgrimes
2031556Srgrimes	if (hist == NULL)
2041556Srgrimes		error("history not active");
2058855Srgrimes
2061556Srgrimes	if (argc == 1)
2071556Srgrimes		error("missing history argument");
2081556Srgrimes
209240541Sjilles	while (not_fcnumber(*argptr) && (ch = nextopt("e:lnrs")) != '\0')
2101556Srgrimes		switch ((char)ch) {
2111556Srgrimes		case 'e':
212240541Sjilles			editor = shoptarg;
2131556Srgrimes			break;
2141556Srgrimes		case 'l':
2151556Srgrimes			lflg = 1;
2161556Srgrimes			break;
2171556Srgrimes		case 'n':
2181556Srgrimes			nflg = 1;
2191556Srgrimes			break;
2201556Srgrimes		case 'r':
2211556Srgrimes			rflg = 1;
2221556Srgrimes			break;
2231556Srgrimes		case 's':
2241556Srgrimes			sflg = 1;
2251556Srgrimes			break;
2261556Srgrimes		}
2271556Srgrimes
228216806Sjilles	savehandler = handler;
2291556Srgrimes	/*
2301556Srgrimes	 * If executing...
2311556Srgrimes	 */
2321556Srgrimes	if (lflg == 0 || editor || sflg) {
2331556Srgrimes		lflg = 0;	/* ignore */
234194765Sjilles		editfile = NULL;
2351556Srgrimes		/*
2361556Srgrimes		 * Catch interrupts to reset active counter and
2371556Srgrimes		 * cleanup temp files.
2381556Srgrimes		 */
2391556Srgrimes		if (setjmp(jmploc.loc)) {
2401556Srgrimes			active = 0;
241194765Sjilles			if (editfile)
2421556Srgrimes				unlink(editfile);
2431556Srgrimes			handler = savehandler;
2441556Srgrimes			longjmp(handler->loc, 1);
2451556Srgrimes		}
2461556Srgrimes		handler = &jmploc;
2471556Srgrimes		if (++active > MAXHISTLOOPS) {
2481556Srgrimes			active = 0;
2491556Srgrimes			displayhist = 0;
2501556Srgrimes			error("called recursively too many times");
2511556Srgrimes		}
2521556Srgrimes		/*
2531556Srgrimes		 * Set editor.
2541556Srgrimes		 */
2551556Srgrimes		if (sflg == 0) {
2561556Srgrimes			if (editor == NULL &&
2571556Srgrimes			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
2581556Srgrimes			    (editor = bltinlookup("EDITOR", 1)) == NULL)
2591556Srgrimes				editor = DEFEDITOR;
2601556Srgrimes			if (editor[0] == '-' && editor[1] == '\0') {
2611556Srgrimes				sflg = 1;	/* no edit */
2621556Srgrimes				editor = NULL;
2631556Srgrimes			}
2641556Srgrimes		}
2651556Srgrimes	}
2661556Srgrimes
2671556Srgrimes	/*
2681556Srgrimes	 * If executing, parse [old=new] now
2691556Srgrimes	 */
270240541Sjilles	if (lflg == 0 && *argptr != NULL &&
271240541Sjilles	     ((repl = strchr(*argptr, '=')) != NULL)) {
272240541Sjilles		pat = *argptr;
2731556Srgrimes		*repl++ = '\0';
274240541Sjilles		argptr++;
2751556Srgrimes	}
2761556Srgrimes	/*
2771556Srgrimes	 * determine [first] and [last]
2781556Srgrimes	 */
279240541Sjilles	if (*argptr == NULL) {
2801556Srgrimes		firststr = lflg ? "-16" : "-1";
2811556Srgrimes		laststr = "-1";
282240541Sjilles	} else if (argptr[1] == NULL) {
283240541Sjilles		firststr = argptr[0];
284240541Sjilles		laststr = lflg ? "-1" : argptr[0];
285240541Sjilles	} else if (argptr[2] == NULL) {
286240541Sjilles		firststr = argptr[0];
287240541Sjilles		laststr = argptr[1];
288240541Sjilles	} else
289214538Sjilles		error("too many arguments");
2901556Srgrimes	/*
2911556Srgrimes	 * Turn into event numbers.
2921556Srgrimes	 */
2931556Srgrimes	first = str_to_event(firststr, 0);
2941556Srgrimes	last = str_to_event(laststr, 1);
2951556Srgrimes
2961556Srgrimes	if (rflg) {
2971556Srgrimes		i = last;
2981556Srgrimes		last = first;
2991556Srgrimes		first = i;
3001556Srgrimes	}
3011556Srgrimes	/*
3021556Srgrimes	 * XXX - this should not depend on the event numbers
3038855Srgrimes	 * always increasing.  Add sequence numbers or offset
3041556Srgrimes	 * to the history element in next (diskbased) release.
3051556Srgrimes	 */
3061556Srgrimes	direction = first < last ? H_PREV : H_NEXT;
3071556Srgrimes
3081556Srgrimes	/*
3091556Srgrimes	 * If editing, grab a temp file.
3101556Srgrimes	 */
3111556Srgrimes	if (editor) {
3121556Srgrimes		int fd;
3131556Srgrimes		INTOFF;		/* easier */
314194765Sjilles		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
315194765Sjilles		if ((fd = mkstemp(editfilestr)) < 0)
3161556Srgrimes			error("can't create temporary file %s", editfile);
317194765Sjilles		editfile = editfilestr;
3181556Srgrimes		if ((efp = fdopen(fd, "w")) == NULL) {
3191556Srgrimes			close(fd);
320214538Sjilles			error("Out of space");
3211556Srgrimes		}
3221556Srgrimes	}
3231556Srgrimes
3241556Srgrimes	/*
3251556Srgrimes	 * Loop through selected history events.  If listing or executing,
3261556Srgrimes	 * do it now.  Otherwise, put into temp file and call the editor
3271556Srgrimes	 * after.
3281556Srgrimes	 *
3291556Srgrimes	 * The history interface needs rethinking, as the following
3301556Srgrimes	 * convolutions will demonstrate.
3311556Srgrimes	 */
33284261Sobrien	history(hist, &he, H_FIRST);
33384261Sobrien	retval = history(hist, &he, H_NEXT_EVENT, first);
33484261Sobrien	for (;retval != -1; retval = history(hist, &he, direction)) {
3351556Srgrimes		if (lflg) {
3361556Srgrimes			if (!nflg)
33784261Sobrien				out1fmt("%5d ", he.num);
33884261Sobrien			out1str(he.str);
3391556Srgrimes		} else {
3408855Srgrimes			char *s = pat ?
34184261Sobrien			   fc_replace(he.str, pat, repl) : (char *)he.str;
3421556Srgrimes
3431556Srgrimes			if (sflg) {
3441556Srgrimes				if (displayhist) {
3451556Srgrimes					out2str(s);
346199629Sjilles					flushout(out2);
3471556Srgrimes				}
348193169Sstefanf				evalstring(s, 0);
3491556Srgrimes				if (displayhist && hist) {
3501556Srgrimes					/*
3518855Srgrimes					 *  XXX what about recursive and
3521556Srgrimes					 *  relative histnums.
3531556Srgrimes					 */
35497730Stjr					oldhistnum = he.num;
35584261Sobrien					history(hist, &he, H_ENTER, s);
35697730Stjr					/*
35797730Stjr					 * XXX H_ENTER moves the internal
35897730Stjr					 * cursor, set it back to the current
35997730Stjr					 * entry.
36097730Stjr					 */
36197730Stjr					retval = history(hist, &he,
36297730Stjr					    H_NEXT_EVENT, oldhistnum);
3631556Srgrimes				}
3641556Srgrimes			} else
3651556Srgrimes				fputs(s, efp);
3661556Srgrimes		}
3671556Srgrimes		/*
368160964Syar		 * At end?  (if we were to lose last, we'd sure be
3691556Srgrimes		 * messed up).
3701556Srgrimes		 */
37184261Sobrien		if (he.num == last)
3721556Srgrimes			break;
3731556Srgrimes	}
3741556Srgrimes	if (editor) {
3751556Srgrimes		char *editcmd;
3761556Srgrimes
3771556Srgrimes		fclose(efp);
3781556Srgrimes		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
3791556Srgrimes		sprintf(editcmd, "%s %s", editor, editfile);
380193169Sstefanf		evalstring(editcmd, 0);	/* XXX - should use no JC command */
3811556Srgrimes		INTON;
3821556Srgrimes		readcmdfile(editfile);	/* XXX - should read back - quick tst */
3831556Srgrimes		unlink(editfile);
3841556Srgrimes	}
3858855Srgrimes
3861556Srgrimes	if (lflg == 0 && active > 0)
3871556Srgrimes		--active;
3881556Srgrimes	if (displayhist)
3891556Srgrimes		displayhist = 0;
390216806Sjilles	handler = savehandler;
39117987Speter	return 0;
3921556Srgrimes}
3931556Srgrimes
394213811Sobrienstatic char *
39590111Simpfc_replace(const char *s, char *p, char *r)
3961556Srgrimes{
3971556Srgrimes	char *dest;
3981556Srgrimes	int plen = strlen(p);
3991556Srgrimes
4001556Srgrimes	STARTSTACKSTR(dest);
4011556Srgrimes	while (*s) {
4021556Srgrimes		if (*s == *p && strncmp(s, p, plen) == 0) {
403215783Sjilles			STPUTS(r, dest);
4041556Srgrimes			s += plen;
4051556Srgrimes			*p = '\0';	/* so no more matches */
4061556Srgrimes		} else
4071556Srgrimes			STPUTC(*s++, dest);
4081556Srgrimes	}
409213814Sobrien	STPUTC('\0', dest);
4101556Srgrimes	dest = grabstackstr(dest);
4111556Srgrimes
4121556Srgrimes	return (dest);
4131556Srgrimes}
4141556Srgrimes
415229220Sjillesstatic int
416200956Sjillesnot_fcnumber(const char *s)
4171556Srgrimes{
41820425Ssteve	if (s == NULL)
41925224Ssteve		return (0);
42020425Ssteve	if (*s == '-')
42120425Ssteve		s++;
4221556Srgrimes	return (!is_number(s));
4231556Srgrimes}
4241556Srgrimes
425229220Sjillesstatic int
426200956Sjillesstr_to_event(const char *str, int last)
4271556Srgrimes{
42884261Sobrien	HistEvent he;
429200956Sjilles	const char *s = str;
4301556Srgrimes	int relative = 0;
43184261Sobrien	int i, retval;
4321556Srgrimes
43384261Sobrien	retval = history(hist, &he, H_FIRST);
4341556Srgrimes	switch (*s) {
4351556Srgrimes	case '-':
4361556Srgrimes		relative = 1;
4371556Srgrimes		/*FALLTHROUGH*/
4381556Srgrimes	case '+':
4391556Srgrimes		s++;
4401556Srgrimes	}
4411556Srgrimes	if (is_number(s)) {
4421556Srgrimes		i = atoi(s);
4431556Srgrimes		if (relative) {
44484261Sobrien			while (retval != -1 && i--) {
44584261Sobrien				retval = history(hist, &he, H_NEXT);
4461556Srgrimes			}
44784261Sobrien			if (retval == -1)
44884261Sobrien				retval = history(hist, &he, H_LAST);
4491556Srgrimes		} else {
45084261Sobrien			retval = history(hist, &he, H_NEXT_EVENT, i);
45184261Sobrien			if (retval == -1) {
4521556Srgrimes				/*
4531556Srgrimes				 * the notion of first and last is
4541556Srgrimes				 * backwards to that of the history package
4551556Srgrimes				 */
45684261Sobrien				retval = history(hist, &he, last ? H_FIRST : H_LAST);
4571556Srgrimes			}
4581556Srgrimes		}
45984261Sobrien		if (retval == -1)
4601556Srgrimes			error("history number %s not found (internal error)",
4611556Srgrimes			       str);
4621556Srgrimes	} else {
4631556Srgrimes		/*
4648855Srgrimes		 * pattern
4651556Srgrimes		 */
46684261Sobrien		retval = history(hist, &he, H_PREV_STR, str);
46784261Sobrien		if (retval == -1)
4681556Srgrimes			error("history pattern not found: %s", str);
4691556Srgrimes	}
47084261Sobrien	return (he.num);
4711556Srgrimes}
472100565Stjr
473100565Stjrint
474100565Stjrbindcmd(int argc, char **argv)
475100565Stjr{
476100565Stjr
477100565Stjr	if (el == NULL)
478100565Stjr		error("line editing is disabled");
479148974Sstefanf	return (el_parse(el, argc, (const char **)argv));
480100565Stjr}
481100565Stjr
48225224Ssteve#else
48325224Ssteve#include "error.h"
48425224Ssteve
48525224Ssteveint
48690111Simphistcmd(int argc, char **argv)
48725224Ssteve{
48825224Ssteve
48925224Ssteve	error("not compiled with history support");
49025224Ssteve	/*NOTREACHED*/
49125224Ssteve	return (0);
49225224Ssteve}
493100565Stjr
494100565Stjrint
495100565Stjrbindcmd(int argc, char **argv)
496100565Stjr{
497100565Stjr
498100565Stjr	error("not compiled with line editing support");
499100565Stjr	return (0);
500100565Stjr}
50125224Ssteve#endif
502