1/*-
2 * Copyright (c) 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34#if 0
35static char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
36#endif
37#endif /* not lint */
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD$");
40
41#include <sys/param.h>
42#include <limits.h>
43#include <paths.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <unistd.h>
47/*
48 * Editline and history functions (and glue).
49 */
50#include "shell.h"
51#include "parser.h"
52#include "var.h"
53#include "options.h"
54#include "main.h"
55#include "output.h"
56#include "mystring.h"
57#ifndef NO_HISTORY
58#include "myhistedit.h"
59#include "error.h"
60#include "eval.h"
61#include "memalloc.h"
62#include "builtins.h"
63
64#define MAXHISTLOOPS	4	/* max recursions through fc */
65#define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
66
67History *hist;	/* history cookie */
68EditLine *el;	/* editline cookie */
69int displayhist;
70static FILE *el_in, *el_out, *el_err;
71
72static char *fc_replace(const char *, char *, char *);
73static int not_fcnumber(const char *);
74static int str_to_event(const char *, int);
75
76/*
77 * Set history and editing status.  Called whenever the status may
78 * have changed (figures out what to do).
79 */
80void
81histedit(void)
82{
83
84#define editing (Eflag || Vflag)
85
86	if (iflag) {
87		if (!hist) {
88			/*
89			 * turn history on
90			 */
91			INTOFF;
92			hist = history_init();
93			INTON;
94
95			if (hist != NULL)
96				sethistsize(histsizeval());
97			else
98				out2fmt_flush("sh: can't initialize history\n");
99		}
100		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
101			/*
102			 * turn editing on
103			 */
104			char *term;
105
106			INTOFF;
107			if (el_in == NULL)
108				el_in = fdopen(0, "r");
109			if (el_err == NULL)
110				el_err = fdopen(1, "w");
111			if (el_out == NULL)
112				el_out = fdopen(2, "w");
113			if (el_in == NULL || el_err == NULL || el_out == NULL)
114				goto bad;
115			term = lookupvar("TERM");
116			if (term)
117				setenv("TERM", term, 1);
118			else
119				unsetenv("TERM");
120			el = el_init(arg0, el_in, el_out, el_err);
121			if (el != NULL) {
122				if (hist)
123					el_set(el, EL_HIST, history, hist);
124				el_set(el, EL_PROMPT, getprompt);
125				el_set(el, EL_ADDFN, "sh-complete",
126				    "Filename completion",
127				    _el_fn_sh_complete);
128			} else {
129bad:
130				out2fmt_flush("sh: can't initialize editing\n");
131			}
132			INTON;
133		} else if (!editing && el) {
134			INTOFF;
135			el_end(el);
136			el = NULL;
137			INTON;
138		}
139		if (el) {
140			if (Vflag)
141				el_set(el, EL_EDITOR, "vi");
142			else if (Eflag)
143				el_set(el, EL_EDITOR, "emacs");
144			el_set(el, EL_BIND, "^I", "sh-complete", NULL);
145			el_source(el, NULL);
146		}
147	} else {
148		INTOFF;
149		if (el) {	/* no editing if not interactive */
150			el_end(el);
151			el = NULL;
152		}
153		if (hist) {
154			history_end(hist);
155			hist = NULL;
156		}
157		INTON;
158	}
159}
160
161
162void
163sethistsize(hs)
164	const char *hs;
165{
166	int histsize;
167	HistEvent he;
168
169	if (hist != NULL) {
170		if (hs == NULL || *hs == '\0' ||
171		   (histsize = atoi(hs)) < 0)
172			histsize = 100;
173		history(hist, &he, H_SETSIZE, histsize);
174		history(hist, &he, H_SETUNIQUE, 1);
175	}
176}
177
178void
179setterm(const char *term)
180{
181	if (rootshell && el != NULL && term != NULL)
182		el_set(el, EL_TERMINAL, term);
183}
184
185int
186histcmd(int argc, char **argv)
187{
188	int ch;
189	const char *editor = NULL;
190	HistEvent he;
191	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
192	int i, retval;
193	const char *firststr, *laststr;
194	int first, last, direction;
195	char *pat = NULL, *repl = NULL;
196	static int active = 0;
197	struct jmploc jmploc;
198	struct jmploc *savehandler;
199	char editfilestr[PATH_MAX];
200	char *volatile editfile;
201	FILE *efp = NULL;
202	int oldhistnum;
203
204	if (hist == NULL)
205		error("history not active");
206
207	if (argc == 1)
208		error("missing history argument");
209
210	optreset = 1; optind = 1; /* initialize getopt */
211	opterr = 0;
212	while (not_fcnumber(argv[optind]) &&
213	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
214		switch ((char)ch) {
215		case 'e':
216			editor = optarg;
217			break;
218		case 'l':
219			lflg = 1;
220			break;
221		case 'n':
222			nflg = 1;
223			break;
224		case 'r':
225			rflg = 1;
226			break;
227		case 's':
228			sflg = 1;
229			break;
230		case ':':
231			error("option -%c expects argument", optopt);
232		case '?':
233		default:
234			error("unknown option: -%c", optopt);
235		}
236	argc -= optind, argv += optind;
237
238	savehandler = handler;
239	/*
240	 * If executing...
241	 */
242	if (lflg == 0 || editor || sflg) {
243		lflg = 0;	/* ignore */
244		editfile = NULL;
245		/*
246		 * Catch interrupts to reset active counter and
247		 * cleanup temp files.
248		 */
249		if (setjmp(jmploc.loc)) {
250			active = 0;
251			if (editfile)
252				unlink(editfile);
253			handler = savehandler;
254			longjmp(handler->loc, 1);
255		}
256		handler = &jmploc;
257		if (++active > MAXHISTLOOPS) {
258			active = 0;
259			displayhist = 0;
260			error("called recursively too many times");
261		}
262		/*
263		 * Set editor.
264		 */
265		if (sflg == 0) {
266			if (editor == NULL &&
267			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
268			    (editor = bltinlookup("EDITOR", 1)) == NULL)
269				editor = DEFEDITOR;
270			if (editor[0] == '-' && editor[1] == '\0') {
271				sflg = 1;	/* no edit */
272				editor = NULL;
273			}
274		}
275	}
276
277	/*
278	 * If executing, parse [old=new] now
279	 */
280	if (lflg == 0 && argc > 0 &&
281	     ((repl = strchr(argv[0], '=')) != NULL)) {
282		pat = argv[0];
283		*repl++ = '\0';
284		argc--, argv++;
285	}
286	/*
287	 * determine [first] and [last]
288	 */
289	switch (argc) {
290	case 0:
291		firststr = lflg ? "-16" : "-1";
292		laststr = "-1";
293		break;
294	case 1:
295		firststr = argv[0];
296		laststr = lflg ? "-1" : argv[0];
297		break;
298	case 2:
299		firststr = argv[0];
300		laststr = argv[1];
301		break;
302	default:
303		error("too many arguments");
304	}
305	/*
306	 * Turn into event numbers.
307	 */
308	first = str_to_event(firststr, 0);
309	last = str_to_event(laststr, 1);
310
311	if (rflg) {
312		i = last;
313		last = first;
314		first = i;
315	}
316	/*
317	 * XXX - this should not depend on the event numbers
318	 * always increasing.  Add sequence numbers or offset
319	 * to the history element in next (diskbased) release.
320	 */
321	direction = first < last ? H_PREV : H_NEXT;
322
323	/*
324	 * If editing, grab a temp file.
325	 */
326	if (editor) {
327		int fd;
328		INTOFF;		/* easier */
329		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
330		if ((fd = mkstemp(editfilestr)) < 0)
331			error("can't create temporary file %s", editfile);
332		editfile = editfilestr;
333		if ((efp = fdopen(fd, "w")) == NULL) {
334			close(fd);
335			error("Out of space");
336		}
337	}
338
339	/*
340	 * Loop through selected history events.  If listing or executing,
341	 * do it now.  Otherwise, put into temp file and call the editor
342	 * after.
343	 *
344	 * The history interface needs rethinking, as the following
345	 * convolutions will demonstrate.
346	 */
347	history(hist, &he, H_FIRST);
348	retval = history(hist, &he, H_NEXT_EVENT, first);
349	for (;retval != -1; retval = history(hist, &he, direction)) {
350		if (lflg) {
351			if (!nflg)
352				out1fmt("%5d ", he.num);
353			out1str(he.str);
354		} else {
355			char *s = pat ?
356			   fc_replace(he.str, pat, repl) : (char *)he.str;
357
358			if (sflg) {
359				if (displayhist) {
360					out2str(s);
361					flushout(out2);
362				}
363				evalstring(s, 0);
364				if (displayhist && hist) {
365					/*
366					 *  XXX what about recursive and
367					 *  relative histnums.
368					 */
369					oldhistnum = he.num;
370					history(hist, &he, H_ENTER, s);
371					/*
372					 * XXX H_ENTER moves the internal
373					 * cursor, set it back to the current
374					 * entry.
375					 */
376					retval = history(hist, &he,
377					    H_NEXT_EVENT, oldhistnum);
378				}
379			} else
380				fputs(s, efp);
381		}
382		/*
383		 * At end?  (if we were to lose last, we'd sure be
384		 * messed up).
385		 */
386		if (he.num == last)
387			break;
388	}
389	if (editor) {
390		char *editcmd;
391
392		fclose(efp);
393		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
394		sprintf(editcmd, "%s %s", editor, editfile);
395		evalstring(editcmd, 0);	/* XXX - should use no JC command */
396		INTON;
397		readcmdfile(editfile);	/* XXX - should read back - quick tst */
398		unlink(editfile);
399	}
400
401	if (lflg == 0 && active > 0)
402		--active;
403	if (displayhist)
404		displayhist = 0;
405	handler = savehandler;
406	return 0;
407}
408
409static char *
410fc_replace(const char *s, char *p, char *r)
411{
412	char *dest;
413	int plen = strlen(p);
414
415	STARTSTACKSTR(dest);
416	while (*s) {
417		if (*s == *p && strncmp(s, p, plen) == 0) {
418			STPUTS(r, dest);
419			s += plen;
420			*p = '\0';	/* so no more matches */
421		} else
422			STPUTC(*s++, dest);
423	}
424	STPUTC('\0', dest);
425	dest = grabstackstr(dest);
426
427	return (dest);
428}
429
430static int
431not_fcnumber(const char *s)
432{
433	if (s == NULL)
434		return (0);
435	if (*s == '-')
436		s++;
437	return (!is_number(s));
438}
439
440static int
441str_to_event(const char *str, int last)
442{
443	HistEvent he;
444	const char *s = str;
445	int relative = 0;
446	int i, retval;
447
448	retval = history(hist, &he, H_FIRST);
449	switch (*s) {
450	case '-':
451		relative = 1;
452		/*FALLTHROUGH*/
453	case '+':
454		s++;
455	}
456	if (is_number(s)) {
457		i = atoi(s);
458		if (relative) {
459			while (retval != -1 && i--) {
460				retval = history(hist, &he, H_NEXT);
461			}
462			if (retval == -1)
463				retval = history(hist, &he, H_LAST);
464		} else {
465			retval = history(hist, &he, H_NEXT_EVENT, i);
466			if (retval == -1) {
467				/*
468				 * the notion of first and last is
469				 * backwards to that of the history package
470				 */
471				retval = history(hist, &he, last ? H_FIRST : H_LAST);
472			}
473		}
474		if (retval == -1)
475			error("history number %s not found (internal error)",
476			       str);
477	} else {
478		/*
479		 * pattern
480		 */
481		retval = history(hist, &he, H_PREV_STR, str);
482		if (retval == -1)
483			error("history pattern not found: %s", str);
484	}
485	return (he.num);
486}
487
488int
489bindcmd(int argc, char **argv)
490{
491
492	if (el == NULL)
493		error("line editing is disabled");
494	return (el_parse(el, argc, (const char **)argv));
495}
496
497#else
498#include "error.h"
499
500int
501histcmd(int argc, char **argv)
502{
503
504	error("not compiled with history support");
505	/*NOTREACHED*/
506	return (0);
507}
508
509int
510bindcmd(int argc, char **argv)
511{
512
513	error("not compiled with line editing support");
514	return (0);
515}
516#endif
517