histedit.c revision 215783
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: head/bin/sh/histedit.c 215783 2010-11-23 22:17:39Z jilles $");
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"
621556Srgrimes
631556Srgrimes#define MAXHISTLOOPS	4	/* max recursions through fc */
641556Srgrimes#define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
651556Srgrimes
661556SrgrimesHistory *hist;	/* history cookie */
671556SrgrimesEditLine *el;	/* editline cookie */
681556Srgrimesint displayhist;
6984261Sobrienstatic FILE *el_in, *el_out, *el_err;
701556Srgrimes
71213811Sobrienstatic char *fc_replace(const char *, char *, char *);
721556Srgrimes
731556Srgrimes/*
741556Srgrimes * Set history and editing status.  Called whenever the status may
751556Srgrimes * have changed (figures out what to do).
761556Srgrimes */
7717987Spetervoid
7890111Simphistedit(void)
7917987Speter{
801556Srgrimes
811556Srgrimes#define editing (Eflag || Vflag)
821556Srgrimes
831556Srgrimes	if (iflag) {
841556Srgrimes		if (!hist) {
851556Srgrimes			/*
861556Srgrimes			 * turn history on
871556Srgrimes			 */
881556Srgrimes			INTOFF;
891556Srgrimes			hist = history_init();
901556Srgrimes			INTON;
911556Srgrimes
921556Srgrimes			if (hist != NULL)
9320425Ssteve				sethistsize(histsizeval());
941556Srgrimes			else
95199629Sjilles				out2fmt_flush("sh: can't initialize history\n");
961556Srgrimes		}
971556Srgrimes		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
981556Srgrimes			/*
991556Srgrimes			 * turn editing on
1001556Srgrimes			 */
101208755Sjilles			char *term;
102208755Sjilles
1031556Srgrimes			INTOFF;
1041556Srgrimes			if (el_in == NULL)
1051556Srgrimes				el_in = fdopen(0, "r");
10684261Sobrien			if (el_err == NULL)
10784261Sobrien				el_err = fdopen(1, "w");
1081556Srgrimes			if (el_out == NULL)
1091556Srgrimes				el_out = fdopen(2, "w");
11084261Sobrien			if (el_in == NULL || el_err == NULL || el_out == NULL)
1111556Srgrimes				goto bad;
112208755Sjilles			term = lookupvar("TERM");
113208755Sjilles			if (term)
114208755Sjilles				setenv("TERM", term, 1);
115208755Sjilles			else
116208755Sjilles				unsetenv("TERM");
11784261Sobrien			el = el_init(arg0, el_in, el_out, el_err);
1181556Srgrimes			if (el != NULL) {
1191556Srgrimes				if (hist)
1201556Srgrimes					el_set(el, EL_HIST, history, hist);
1211556Srgrimes				el_set(el, EL_PROMPT, getprompt);
122209221Sjilles				el_set(el, EL_ADDFN, "sh-complete",
123209221Sjilles				    "Filename completion",
124209221Sjilles				    _el_fn_sh_complete);
1251556Srgrimes			} else {
1261556Srgrimesbad:
127199629Sjilles				out2fmt_flush("sh: can't initialize editing\n");
1281556Srgrimes			}
1291556Srgrimes			INTON;
1301556Srgrimes		} else if (!editing && el) {
1311556Srgrimes			INTOFF;
1321556Srgrimes			el_end(el);
1331556Srgrimes			el = NULL;
1341556Srgrimes			INTON;
1351556Srgrimes		}
1361556Srgrimes		if (el) {
1371556Srgrimes			if (Vflag)
1381556Srgrimes				el_set(el, EL_EDITOR, "vi");
1391556Srgrimes			else if (Eflag)
1401556Srgrimes				el_set(el, EL_EDITOR, "emacs");
141209221Sjilles			el_set(el, EL_BIND, "^I", "sh-complete", NULL);
142100568Stjr			el_source(el, NULL);
1431556Srgrimes		}
1441556Srgrimes	} else {
1451556Srgrimes		INTOFF;
1461556Srgrimes		if (el) {	/* no editing if not interactive */
1471556Srgrimes			el_end(el);
1481556Srgrimes			el = NULL;
1491556Srgrimes		}
1501556Srgrimes		if (hist) {
1511556Srgrimes			history_end(hist);
1521556Srgrimes			hist = NULL;
1531556Srgrimes		}
1541556Srgrimes		INTON;
1551556Srgrimes	}
1561556Srgrimes}
1571556Srgrimes
15817987Speter
15917987Spetervoid
16020425Sstevesethistsize(hs)
16120425Ssteve	const char *hs;
16217987Speter{
1631556Srgrimes	int histsize;
16484261Sobrien	HistEvent he;
1651556Srgrimes
1661556Srgrimes	if (hist != NULL) {
16720425Ssteve		if (hs == NULL || *hs == '\0' ||
16820425Ssteve		   (histsize = atoi(hs)) < 0)
1691556Srgrimes			histsize = 100;
170151471Sstefanf		history(hist, &he, H_SETSIZE, histsize);
171210736Sjilles		history(hist, &he, H_SETUNIQUE, 1);
1721556Srgrimes	}
1731556Srgrimes}
1741556Srgrimes
175208755Sjillesvoid
176208755Sjillessetterm(const char *term)
177208755Sjilles{
178208755Sjilles	if (rootshell && el != NULL && term != NULL)
179208755Sjilles		el_set(el, EL_TERMINAL, term);
180208755Sjilles}
181208755Sjilles
18217987Speterint
18390111Simphistcmd(int argc, char **argv)
1841556Srgrimes{
1851556Srgrimes	int ch;
186201053Sjilles	const char *editor = NULL;
18784261Sobrien	HistEvent he;
1881556Srgrimes	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
18984261Sobrien	int i, retval;
190201053Sjilles	const char *firststr, *laststr;
1911556Srgrimes	int first, last, direction;
192201053Sjilles	char *pat = NULL, *repl = NULL;
1931556Srgrimes	static int active = 0;
1941556Srgrimes	struct jmploc jmploc;
195194765Sjilles	struct jmploc *savehandler;
196194765Sjilles	char editfilestr[PATH_MAX];
197194765Sjilles	char *volatile editfile;
198201053Sjilles	FILE *efp = NULL;
19997730Stjr	int oldhistnum;
2001556Srgrimes
2011556Srgrimes	if (hist == NULL)
2021556Srgrimes		error("history not active");
2038855Srgrimes
2041556Srgrimes	if (argc == 1)
2051556Srgrimes		error("missing history argument");
2061556Srgrimes
2071556Srgrimes	optreset = 1; optind = 1; /* initialize getopt */
208100663Stjr	opterr = 0;
2091556Srgrimes	while (not_fcnumber(argv[optind]) &&
21024348Simp	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
2111556Srgrimes		switch ((char)ch) {
2121556Srgrimes		case 'e':
21397731Stjr			editor = optarg;
2141556Srgrimes			break;
2151556Srgrimes		case 'l':
2161556Srgrimes			lflg = 1;
2171556Srgrimes			break;
2181556Srgrimes		case 'n':
2191556Srgrimes			nflg = 1;
2201556Srgrimes			break;
2211556Srgrimes		case 'r':
2221556Srgrimes			rflg = 1;
2231556Srgrimes			break;
2241556Srgrimes		case 's':
2251556Srgrimes			sflg = 1;
2261556Srgrimes			break;
2271556Srgrimes		case ':':
2281556Srgrimes			error("option -%c expects argument", optopt);
2291556Srgrimes		case '?':
2301556Srgrimes		default:
2311556Srgrimes			error("unknown option: -%c", optopt);
2321556Srgrimes		}
2331556Srgrimes	argc -= optind, argv += optind;
2341556Srgrimes
2351556Srgrimes	/*
2361556Srgrimes	 * If executing...
2371556Srgrimes	 */
2381556Srgrimes	if (lflg == 0 || editor || sflg) {
2391556Srgrimes		lflg = 0;	/* ignore */
240194765Sjilles		editfile = NULL;
2411556Srgrimes		/*
2421556Srgrimes		 * Catch interrupts to reset active counter and
2431556Srgrimes		 * cleanup temp files.
2441556Srgrimes		 */
245194765Sjilles		savehandler = handler;
2461556Srgrimes		if (setjmp(jmploc.loc)) {
2471556Srgrimes			active = 0;
248194765Sjilles			if (editfile)
2491556Srgrimes				unlink(editfile);
2501556Srgrimes			handler = savehandler;
2511556Srgrimes			longjmp(handler->loc, 1);
2521556Srgrimes		}
2531556Srgrimes		handler = &jmploc;
2541556Srgrimes		if (++active > MAXHISTLOOPS) {
2551556Srgrimes			active = 0;
2561556Srgrimes			displayhist = 0;
2571556Srgrimes			error("called recursively too many times");
2581556Srgrimes		}
2591556Srgrimes		/*
2601556Srgrimes		 * Set editor.
2611556Srgrimes		 */
2621556Srgrimes		if (sflg == 0) {
2631556Srgrimes			if (editor == NULL &&
2641556Srgrimes			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
2651556Srgrimes			    (editor = bltinlookup("EDITOR", 1)) == NULL)
2661556Srgrimes				editor = DEFEDITOR;
2671556Srgrimes			if (editor[0] == '-' && editor[1] == '\0') {
2681556Srgrimes				sflg = 1;	/* no edit */
2691556Srgrimes				editor = NULL;
2701556Srgrimes			}
2711556Srgrimes		}
2721556Srgrimes	}
2731556Srgrimes
2741556Srgrimes	/*
2751556Srgrimes	 * If executing, parse [old=new] now
2761556Srgrimes	 */
2778855Srgrimes	if (lflg == 0 && argc > 0 &&
2781556Srgrimes	     ((repl = strchr(argv[0], '=')) != NULL)) {
2791556Srgrimes		pat = argv[0];
2801556Srgrimes		*repl++ = '\0';
2811556Srgrimes		argc--, argv++;
2821556Srgrimes	}
2831556Srgrimes	/*
2841556Srgrimes	 * determine [first] and [last]
2851556Srgrimes	 */
2861556Srgrimes	switch (argc) {
2871556Srgrimes	case 0:
2881556Srgrimes		firststr = lflg ? "-16" : "-1";
2891556Srgrimes		laststr = "-1";
2901556Srgrimes		break;
2911556Srgrimes	case 1:
2921556Srgrimes		firststr = argv[0];
2931556Srgrimes		laststr = lflg ? "-1" : argv[0];
2941556Srgrimes		break;
2951556Srgrimes	case 2:
2961556Srgrimes		firststr = argv[0];
2971556Srgrimes		laststr = argv[1];
2981556Srgrimes		break;
2991556Srgrimes	default:
300214538Sjilles		error("too many arguments");
3011556Srgrimes	}
3021556Srgrimes	/*
3031556Srgrimes	 * Turn into event numbers.
3041556Srgrimes	 */
3051556Srgrimes	first = str_to_event(firststr, 0);
3061556Srgrimes	last = str_to_event(laststr, 1);
3071556Srgrimes
3081556Srgrimes	if (rflg) {
3091556Srgrimes		i = last;
3101556Srgrimes		last = first;
3111556Srgrimes		first = i;
3121556Srgrimes	}
3131556Srgrimes	/*
3141556Srgrimes	 * XXX - this should not depend on the event numbers
3158855Srgrimes	 * always increasing.  Add sequence numbers or offset
3161556Srgrimes	 * to the history element in next (diskbased) release.
3171556Srgrimes	 */
3181556Srgrimes	direction = first < last ? H_PREV : H_NEXT;
3191556Srgrimes
3201556Srgrimes	/*
3211556Srgrimes	 * If editing, grab a temp file.
3221556Srgrimes	 */
3231556Srgrimes	if (editor) {
3241556Srgrimes		int fd;
3251556Srgrimes		INTOFF;		/* easier */
326194765Sjilles		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
327194765Sjilles		if ((fd = mkstemp(editfilestr)) < 0)
3281556Srgrimes			error("can't create temporary file %s", editfile);
329194765Sjilles		editfile = editfilestr;
3301556Srgrimes		if ((efp = fdopen(fd, "w")) == NULL) {
3311556Srgrimes			close(fd);
332214538Sjilles			error("Out of space");
3331556Srgrimes		}
3341556Srgrimes	}
3351556Srgrimes
3361556Srgrimes	/*
3371556Srgrimes	 * Loop through selected history events.  If listing or executing,
3381556Srgrimes	 * do it now.  Otherwise, put into temp file and call the editor
3391556Srgrimes	 * after.
3401556Srgrimes	 *
3411556Srgrimes	 * The history interface needs rethinking, as the following
3421556Srgrimes	 * convolutions will demonstrate.
3431556Srgrimes	 */
34484261Sobrien	history(hist, &he, H_FIRST);
34584261Sobrien	retval = history(hist, &he, H_NEXT_EVENT, first);
34684261Sobrien	for (;retval != -1; retval = history(hist, &he, direction)) {
3471556Srgrimes		if (lflg) {
3481556Srgrimes			if (!nflg)
34984261Sobrien				out1fmt("%5d ", he.num);
35084261Sobrien			out1str(he.str);
3511556Srgrimes		} else {
3528855Srgrimes			char *s = pat ?
35384261Sobrien			   fc_replace(he.str, pat, repl) : (char *)he.str;
3541556Srgrimes
3551556Srgrimes			if (sflg) {
3561556Srgrimes				if (displayhist) {
3571556Srgrimes					out2str(s);
358199629Sjilles					flushout(out2);
3591556Srgrimes				}
360193169Sstefanf				evalstring(s, 0);
3611556Srgrimes				if (displayhist && hist) {
3621556Srgrimes					/*
3638855Srgrimes					 *  XXX what about recursive and
3641556Srgrimes					 *  relative histnums.
3651556Srgrimes					 */
36697730Stjr					oldhistnum = he.num;
36784261Sobrien					history(hist, &he, H_ENTER, s);
36897730Stjr					/*
36997730Stjr					 * XXX H_ENTER moves the internal
37097730Stjr					 * cursor, set it back to the current
37197730Stjr					 * entry.
37297730Stjr					 */
37397730Stjr					retval = history(hist, &he,
37497730Stjr					    H_NEXT_EVENT, oldhistnum);
3751556Srgrimes				}
3761556Srgrimes			} else
3771556Srgrimes				fputs(s, efp);
3781556Srgrimes		}
3791556Srgrimes		/*
380160964Syar		 * At end?  (if we were to lose last, we'd sure be
3811556Srgrimes		 * messed up).
3821556Srgrimes		 */
38384261Sobrien		if (he.num == last)
3841556Srgrimes			break;
3851556Srgrimes	}
3861556Srgrimes	if (editor) {
3871556Srgrimes		char *editcmd;
3881556Srgrimes
3891556Srgrimes		fclose(efp);
3901556Srgrimes		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
3911556Srgrimes		sprintf(editcmd, "%s %s", editor, editfile);
392193169Sstefanf		evalstring(editcmd, 0);	/* XXX - should use no JC command */
3931556Srgrimes		INTON;
3941556Srgrimes		readcmdfile(editfile);	/* XXX - should read back - quick tst */
3951556Srgrimes		unlink(editfile);
3961556Srgrimes	}
3978855Srgrimes
3981556Srgrimes	if (lflg == 0 && active > 0)
3991556Srgrimes		--active;
4001556Srgrimes	if (displayhist)
4011556Srgrimes		displayhist = 0;
40217987Speter	return 0;
4031556Srgrimes}
4041556Srgrimes
405213811Sobrienstatic char *
40690111Simpfc_replace(const char *s, char *p, char *r)
4071556Srgrimes{
4081556Srgrimes	char *dest;
4091556Srgrimes	int plen = strlen(p);
4101556Srgrimes
4111556Srgrimes	STARTSTACKSTR(dest);
4121556Srgrimes	while (*s) {
4131556Srgrimes		if (*s == *p && strncmp(s, p, plen) == 0) {
414215783Sjilles			STPUTS(r, dest);
4151556Srgrimes			s += plen;
4161556Srgrimes			*p = '\0';	/* so no more matches */
4171556Srgrimes		} else
4181556Srgrimes			STPUTC(*s++, dest);
4191556Srgrimes	}
420213814Sobrien	STPUTC('\0', dest);
4211556Srgrimes	dest = grabstackstr(dest);
4221556Srgrimes
4231556Srgrimes	return (dest);
4241556Srgrimes}
4251556Srgrimes
42617987Speterint
427200956Sjillesnot_fcnumber(const char *s)
4281556Srgrimes{
42920425Ssteve	if (s == NULL)
43025224Ssteve		return (0);
43120425Ssteve	if (*s == '-')
43220425Ssteve		s++;
4331556Srgrimes	return (!is_number(s));
4341556Srgrimes}
4351556Srgrimes
43617987Speterint
437200956Sjillesstr_to_event(const char *str, int last)
4381556Srgrimes{
43984261Sobrien	HistEvent he;
440200956Sjilles	const char *s = str;
4411556Srgrimes	int relative = 0;
44284261Sobrien	int i, retval;
4431556Srgrimes
44484261Sobrien	retval = history(hist, &he, H_FIRST);
4451556Srgrimes	switch (*s) {
4461556Srgrimes	case '-':
4471556Srgrimes		relative = 1;
4481556Srgrimes		/*FALLTHROUGH*/
4491556Srgrimes	case '+':
4501556Srgrimes		s++;
4511556Srgrimes	}
4521556Srgrimes	if (is_number(s)) {
4531556Srgrimes		i = atoi(s);
4541556Srgrimes		if (relative) {
45584261Sobrien			while (retval != -1 && i--) {
45684261Sobrien				retval = history(hist, &he, H_NEXT);
4571556Srgrimes			}
45884261Sobrien			if (retval == -1)
45984261Sobrien				retval = history(hist, &he, H_LAST);
4601556Srgrimes		} else {
46184261Sobrien			retval = history(hist, &he, H_NEXT_EVENT, i);
46284261Sobrien			if (retval == -1) {
4631556Srgrimes				/*
4641556Srgrimes				 * the notion of first and last is
4651556Srgrimes				 * backwards to that of the history package
4661556Srgrimes				 */
46784261Sobrien				retval = history(hist, &he, last ? H_FIRST : H_LAST);
4681556Srgrimes			}
4691556Srgrimes		}
47084261Sobrien		if (retval == -1)
4711556Srgrimes			error("history number %s not found (internal error)",
4721556Srgrimes			       str);
4731556Srgrimes	} else {
4741556Srgrimes		/*
4758855Srgrimes		 * pattern
4761556Srgrimes		 */
47784261Sobrien		retval = history(hist, &he, H_PREV_STR, str);
47884261Sobrien		if (retval == -1)
4791556Srgrimes			error("history pattern not found: %s", str);
4801556Srgrimes	}
48184261Sobrien	return (he.num);
4821556Srgrimes}
483100565Stjr
484100565Stjrint
485100565Stjrbindcmd(int argc, char **argv)
486100565Stjr{
487100565Stjr
488100565Stjr	if (el == NULL)
489100565Stjr		error("line editing is disabled");
490148974Sstefanf	return (el_parse(el, argc, (const char **)argv));
491100565Stjr}
492100565Stjr
49325224Ssteve#else
49425224Ssteve#include "error.h"
49525224Ssteve
49625224Ssteveint
49790111Simphistcmd(int argc, char **argv)
49825224Ssteve{
49925224Ssteve
50025224Ssteve	error("not compiled with history support");
50125224Ssteve	/*NOTREACHED*/
50225224Ssteve	return (0);
50325224Ssteve}
504100565Stjr
505100565Stjrint
506100565Stjrbindcmd(int argc, char **argv)
507100565Stjr{
508100565Stjr
509100565Stjr	error("not compiled with line editing support");
510100565Stjr	return (0);
511100565Stjr}
51225224Ssteve#endif
513