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