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