histedit.c revision 100663
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
41#endif /* not lint */
42#include <sys/cdefs.h>
43__FBSDID("$FreeBSD: head/bin/sh/histedit.c 100663 2002-07-25 10:47:38Z tjr $");
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			el_source(el, NULL);
136		}
137	} else {
138		INTOFF;
139		if (el) {	/* no editing if not interactive */
140			el_end(el);
141			el = NULL;
142		}
143		if (hist) {
144			history_end(hist);
145			hist = NULL;
146		}
147		INTON;
148	}
149}
150
151
152void
153sethistsize(hs)
154	const char *hs;
155{
156	int histsize;
157	HistEvent he;
158
159	if (hist != NULL) {
160		if (hs == NULL || *hs == '\0' ||
161		   (histsize = atoi(hs)) < 0)
162			histsize = 100;
163		history(hist, &he, H_EVENT, histsize);
164	}
165}
166
167/*
168 *  This command is provided since POSIX decided to standardize
169 *  the Korn shell fc command.  Oh well...
170 */
171int
172histcmd(int argc, char **argv)
173{
174	int ch;
175	char *editor = NULL;
176	HistEvent he;
177	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
178	int i, retval;
179	char *firststr, *laststr;
180	int first, last, direction;
181	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
182	static int active = 0;
183	struct jmploc jmploc;
184	struct jmploc *volatile savehandler;
185	char editfile[PATH_MAX];
186	FILE *efp;
187	int oldhistnum;
188#ifdef __GNUC__
189	/* Avoid longjmp clobbering */
190	(void) &editor;
191	(void) &lflg;
192	(void) &nflg;
193	(void) &rflg;
194	(void) &sflg;
195	(void) &firststr;
196	(void) &laststr;
197	(void) &pat;
198	(void) &repl;
199	(void) &efp;
200	(void) &argc;
201	(void) &argv;
202#endif
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	/*
239	 * If executing...
240	 */
241	if (lflg == 0 || editor || sflg) {
242		lflg = 0;	/* ignore */
243		editfile[0] = '\0';
244		/*
245		 * Catch interrupts to reset active counter and
246		 * cleanup temp files.
247		 */
248		if (setjmp(jmploc.loc)) {
249			active = 0;
250			if (*editfile)
251				unlink(editfile);
252			handler = savehandler;
253			longjmp(handler->loc, 1);
254		}
255		savehandler = handler;
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 args");
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(editfile, "%s/_shXXXXXX", _PATH_TMP);
330		if ((fd = mkstemp(editfile)) < 0)
331			error("can't create temporary file %s", editfile);
332		if ((efp = fdopen(fd, "w")) == NULL) {
333			close(fd);
334			error("can't allocate stdio buffer for temp");
335		}
336	}
337
338	/*
339	 * Loop through selected history events.  If listing or executing,
340	 * do it now.  Otherwise, put into temp file and call the editor
341	 * after.
342	 *
343	 * The history interface needs rethinking, as the following
344	 * convolutions will demonstrate.
345	 */
346	history(hist, &he, H_FIRST);
347	retval = history(hist, &he, H_NEXT_EVENT, first);
348	for (;retval != -1; retval = history(hist, &he, direction)) {
349		if (lflg) {
350			if (!nflg)
351				out1fmt("%5d ", he.num);
352			out1str(he.str);
353		} else {
354			char *s = pat ?
355			   fc_replace(he.str, pat, repl) : (char *)he.str;
356
357			if (sflg) {
358				if (displayhist) {
359					out2str(s);
360				}
361				evalstring(s);
362				if (displayhist && hist) {
363					/*
364					 *  XXX what about recursive and
365					 *  relative histnums.
366					 */
367					oldhistnum = he.num;
368					history(hist, &he, H_ENTER, s);
369					/*
370					 * XXX H_ENTER moves the internal
371					 * cursor, set it back to the current
372					 * entry.
373					 */
374					retval = history(hist, &he,
375					    H_NEXT_EVENT, oldhistnum);
376				}
377			} else
378				fputs(s, efp);
379		}
380		/*
381		 * At end?  (if we were to loose last, we'd sure be
382		 * messed up).
383		 */
384		if (he.num == last)
385			break;
386	}
387	if (editor) {
388		char *editcmd;
389
390		fclose(efp);
391		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
392		sprintf(editcmd, "%s %s", editor, editfile);
393		evalstring(editcmd);	/* XXX - should use no JC command */
394		INTON;
395		readcmdfile(editfile);	/* XXX - should read back - quick tst */
396		unlink(editfile);
397	}
398
399	if (lflg == 0 && active > 0)
400		--active;
401	if (displayhist)
402		displayhist = 0;
403	return 0;
404}
405
406STATIC char *
407fc_replace(const char *s, char *p, char *r)
408{
409	char *dest;
410	int plen = strlen(p);
411
412	STARTSTACKSTR(dest);
413	while (*s) {
414		if (*s == *p && strncmp(s, p, plen) == 0) {
415			while (*r)
416				STPUTC(*r++, dest);
417			s += plen;
418			*p = '\0';	/* so no more matches */
419		} else
420			STPUTC(*s++, dest);
421	}
422	STACKSTRNUL(dest);
423	dest = grabstackstr(dest);
424
425	return (dest);
426}
427
428int
429not_fcnumber(char *s)
430{
431	if (s == NULL)
432		return (0);
433	if (*s == '-')
434		s++;
435	return (!is_number(s));
436}
437
438int
439str_to_event(char *str, int last)
440{
441	HistEvent he;
442	char *s = str;
443	int relative = 0;
444	int i, retval;
445
446	retval = history(hist, &he, H_FIRST);
447	switch (*s) {
448	case '-':
449		relative = 1;
450		/*FALLTHROUGH*/
451	case '+':
452		s++;
453	}
454	if (is_number(s)) {
455		i = atoi(s);
456		if (relative) {
457			while (retval != -1 && i--) {
458				retval = history(hist, &he, H_NEXT);
459			}
460			if (retval == -1)
461				retval = history(hist, &he, H_LAST);
462		} else {
463			retval = history(hist, &he, H_NEXT_EVENT, i);
464			if (retval == -1) {
465				/*
466				 * the notion of first and last is
467				 * backwards to that of the history package
468				 */
469				retval = history(hist, &he, last ? H_FIRST : H_LAST);
470			}
471		}
472		if (retval == -1)
473			error("history number %s not found (internal error)",
474			       str);
475	} else {
476		/*
477		 * pattern
478		 */
479		retval = history(hist, &he, H_PREV_STR, str);
480		if (retval == -1)
481			error("history pattern not found: %s", str);
482	}
483	return (he.num);
484}
485
486int
487bindcmd(int argc, char **argv)
488{
489
490	if (el == NULL)
491		error("line editing is disabled");
492	return (el_parse(el, argc, argv));
493}
494
495#else
496#include "error.h"
497
498int
499histcmd(int argc, char **argv)
500{
501
502	error("not compiled with history support");
503	/*NOTREACHED*/
504	return (0);
505}
506
507int
508bindcmd(int argc, char **argv)
509{
510
511	error("not compiled with line editing support");
512	return (0);
513}
514#endif
515