histedit.c revision 77463
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 77463 2001-05-30 03:37:28Z imp $";
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;
74
75STATIC char *fc_replace __P((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()
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_out == NULL)
109				el_out = fdopen(2, "w");
110			if (el_in == NULL || el_out == NULL)
111				goto bad;
112			el = el_init(arg0, el_in, el_out);
113			if (el != NULL) {
114				if (hist)
115					el_set(el, EL_HIST, history, hist);
116				el_set(el, EL_PROMPT, getprompt);
117			} else {
118bad:
119				out2str("sh: can't initialize editing\n");
120			}
121			INTON;
122		} else if (!editing && el) {
123			INTOFF;
124			el_end(el);
125			el = NULL;
126			INTON;
127		}
128		if (el) {
129			if (Vflag)
130				el_set(el, EL_EDITOR, "vi");
131			else if (Eflag)
132				el_set(el, EL_EDITOR, "emacs");
133		}
134	} else {
135		INTOFF;
136		if (el) {	/* no editing if not interactive */
137			el_end(el);
138			el = NULL;
139		}
140		if (hist) {
141			history_end(hist);
142			hist = NULL;
143		}
144		INTON;
145	}
146}
147
148
149void
150sethistsize(hs)
151	const char *hs;
152{
153	int histsize;
154
155	if (hist != NULL) {
156		if (hs == NULL || *hs == '\0' ||
157		   (histsize = atoi(hs)) < 0)
158			histsize = 100;
159		history(hist, H_EVENT, histsize);
160	}
161}
162
163/*
164 *  This command is provided since POSIX decided to standardize
165 *  the Korn shell fc command.  Oh well...
166 */
167int
168histcmd(argc, argv)
169	int argc;
170	char **argv;
171{
172	int ch;
173	char *editor = NULL;
174	const HistEvent *he;
175	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
176	int i;
177	char *firststr, *laststr;
178	int first, last, direction;
179	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
180	static int active = 0;
181	struct jmploc jmploc;
182	struct jmploc *volatile savehandler;
183	char editfile[PATH_MAX];
184	FILE *efp;
185#ifdef __GNUC__
186	/* Avoid longjmp clobbering */
187	(void) &editor;
188	(void) &lflg;
189	(void) &nflg;
190	(void) &rflg;
191	(void) &sflg;
192	(void) &firststr;
193	(void) &laststr;
194	(void) &pat;
195	(void) &repl;
196	(void) &efp;
197	(void) &argc;
198	(void) &argv;
199#endif
200
201	if (hist == NULL)
202		error("history not active");
203
204	if (argc == 1)
205		error("missing history argument");
206
207	optreset = 1; optind = 1; /* initialize getopt */
208	while (not_fcnumber(argv[optind]) &&
209	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
210		switch ((char)ch) {
211		case 'e':
212			editor = shoptarg;
213			break;
214		case 'l':
215			lflg = 1;
216			break;
217		case 'n':
218			nflg = 1;
219			break;
220		case 'r':
221			rflg = 1;
222			break;
223		case 's':
224			sflg = 1;
225			break;
226		case ':':
227			error("option -%c expects argument", optopt);
228		case '?':
229		default:
230			error("unknown option: -%c", optopt);
231		}
232	argc -= optind, argv += optind;
233
234	/*
235	 * If executing...
236	 */
237	if (lflg == 0 || editor || sflg) {
238		lflg = 0;	/* ignore */
239		editfile[0] = '\0';
240		/*
241		 * Catch interrupts to reset active counter and
242		 * cleanup temp files.
243		 */
244		if (setjmp(jmploc.loc)) {
245			active = 0;
246			if (*editfile)
247				unlink(editfile);
248			handler = savehandler;
249			longjmp(handler->loc, 1);
250		}
251		savehandler = handler;
252		handler = &jmploc;
253		if (++active > MAXHISTLOOPS) {
254			active = 0;
255			displayhist = 0;
256			error("called recursively too many times");
257		}
258		/*
259		 * Set editor.
260		 */
261		if (sflg == 0) {
262			if (editor == NULL &&
263			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
264			    (editor = bltinlookup("EDITOR", 1)) == NULL)
265				editor = DEFEDITOR;
266			if (editor[0] == '-' && editor[1] == '\0') {
267				sflg = 1;	/* no edit */
268				editor = NULL;
269			}
270		}
271	}
272
273	/*
274	 * If executing, parse [old=new] now
275	 */
276	if (lflg == 0 && argc > 0 &&
277	     ((repl = strchr(argv[0], '=')) != NULL)) {
278		pat = argv[0];
279		*repl++ = '\0';
280		argc--, argv++;
281	}
282	/*
283	 * determine [first] and [last]
284	 */
285	switch (argc) {
286	case 0:
287		firststr = lflg ? "-16" : "-1";
288		laststr = "-1";
289		break;
290	case 1:
291		firststr = argv[0];
292		laststr = lflg ? "-1" : argv[0];
293		break;
294	case 2:
295		firststr = argv[0];
296		laststr = argv[1];
297		break;
298	default:
299		error("too many args");
300	}
301	/*
302	 * Turn into event numbers.
303	 */
304	first = str_to_event(firststr, 0);
305	last = str_to_event(laststr, 1);
306
307	if (rflg) {
308		i = last;
309		last = first;
310		first = i;
311	}
312	/*
313	 * XXX - this should not depend on the event numbers
314	 * always increasing.  Add sequence numbers or offset
315	 * to the history element in next (diskbased) release.
316	 */
317	direction = first < last ? H_PREV : H_NEXT;
318
319	/*
320	 * If editing, grab a temp file.
321	 */
322	if (editor) {
323		int fd;
324		INTOFF;		/* easier */
325		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
326		if ((fd = mkstemp(editfile)) < 0)
327			error("can't create temporary file %s", editfile);
328		if ((efp = fdopen(fd, "w")) == NULL) {
329			close(fd);
330			error("can't allocate stdio buffer for temp");
331		}
332	}
333
334	/*
335	 * Loop through selected history events.  If listing or executing,
336	 * do it now.  Otherwise, put into temp file and call the editor
337	 * after.
338	 *
339	 * The history interface needs rethinking, as the following
340	 * convolutions will demonstrate.
341	 */
342	history(hist, H_FIRST);
343	he = history(hist, H_NEXT_EVENT, first);
344	for (;he != NULL; he = history(hist, direction)) {
345		if (lflg) {
346			if (!nflg)
347				out1fmt("%5d ", he->num);
348			out1str(he->str);
349		} else {
350			char *s = pat ?
351			   fc_replace(he->str, pat, repl) : (char *)he->str;
352
353			if (sflg) {
354				if (displayhist) {
355					out2str(s);
356				}
357				evalstring(s);
358				if (displayhist && hist) {
359					/*
360					 *  XXX what about recursive and
361					 *  relative histnums.
362					 */
363					history(hist, H_ENTER, s);
364				}
365			} else
366				fputs(s, efp);
367		}
368		/*
369		 * At end?  (if we were to loose last, we'd sure be
370		 * messed up).
371		 */
372		if (he->num == last)
373			break;
374	}
375	if (editor) {
376		char *editcmd;
377
378		fclose(efp);
379		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
380		sprintf(editcmd, "%s %s", editor, editfile);
381		evalstring(editcmd);	/* XXX - should use no JC command */
382		INTON;
383		readcmdfile(editfile);	/* XXX - should read back - quick tst */
384		unlink(editfile);
385	}
386
387	if (lflg == 0 && active > 0)
388		--active;
389	if (displayhist)
390		displayhist = 0;
391	return 0;
392}
393
394STATIC char *
395fc_replace(s, p, r)
396	const char *s;
397	char *p, *r;
398{
399	char *dest;
400	int plen = strlen(p);
401
402	STARTSTACKSTR(dest);
403	while (*s) {
404		if (*s == *p && strncmp(s, p, plen) == 0) {
405			while (*r)
406				STPUTC(*r++, dest);
407			s += plen;
408			*p = '\0';	/* so no more matches */
409		} else
410			STPUTC(*s++, dest);
411	}
412	STACKSTRNUL(dest);
413	dest = grabstackstr(dest);
414
415	return (dest);
416}
417
418int
419not_fcnumber(s)
420	char *s;
421{
422	if (s == NULL)
423		return (0);
424	if (*s == '-')
425		s++;
426	return (!is_number(s));
427}
428
429int
430str_to_event(str, last)
431	char *str;
432	int last;
433{
434	const HistEvent *he;
435	char *s = str;
436	int relative = 0;
437	int i;
438
439	he = history(hist, H_FIRST);
440	switch (*s) {
441	case '-':
442		relative = 1;
443		/*FALLTHROUGH*/
444	case '+':
445		s++;
446	}
447	if (is_number(s)) {
448		i = atoi(s);
449		if (relative) {
450			while (he != NULL && i--) {
451				he = history(hist, H_NEXT);
452			}
453			if (he == NULL)
454				he = history(hist, H_LAST);
455		} else {
456			he = history(hist, H_NEXT_EVENT, i);
457			if (he == NULL) {
458				/*
459				 * the notion of first and last is
460				 * backwards to that of the history package
461				 */
462				he = history(hist, last ? H_FIRST : H_LAST);
463			}
464		}
465		if (he == NULL)
466			error("history number %s not found (internal error)",
467			       str);
468	} else {
469		/*
470		 * pattern
471		 */
472		he = history(hist, H_PREV_STR, str);
473		if (he == NULL)
474			error("history pattern not found: %s", str);
475	}
476	return (he->num);
477}
478#else
479#include "error.h"
480
481int
482histcmd(argc, argv)
483	int argc;
484	char **argv;
485{
486
487	error("not compiled with history support");
488	/*NOTREACHED*/
489	return (0);
490}
491#endif
492