histedit.c revision 100568
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 100568 2002-07-23 12:26:34Z 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	while (not_fcnumber(argv[optind]) &&
212	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
213		switch ((char)ch) {
214		case 'e':
215			editor = optarg;
216			break;
217		case 'l':
218			lflg = 1;
219			break;
220		case 'n':
221			nflg = 1;
222			break;
223		case 'r':
224			rflg = 1;
225			break;
226		case 's':
227			sflg = 1;
228			break;
229		case ':':
230			error("option -%c expects argument", optopt);
231		case '?':
232		default:
233			error("unknown option: -%c", optopt);
234		}
235	argc -= optind, argv += optind;
236
237	/*
238	 * If executing...
239	 */
240	if (lflg == 0 || editor || sflg) {
241		lflg = 0;	/* ignore */
242		editfile[0] = '\0';
243		/*
244		 * Catch interrupts to reset active counter and
245		 * cleanup temp files.
246		 */
247		if (setjmp(jmploc.loc)) {
248			active = 0;
249			if (*editfile)
250				unlink(editfile);
251			handler = savehandler;
252			longjmp(handler->loc, 1);
253		}
254		savehandler = handler;
255		handler = &jmploc;
256		if (++active > MAXHISTLOOPS) {
257			active = 0;
258			displayhist = 0;
259			error("called recursively too many times");
260		}
261		/*
262		 * Set editor.
263		 */
264		if (sflg == 0) {
265			if (editor == NULL &&
266			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
267			    (editor = bltinlookup("EDITOR", 1)) == NULL)
268				editor = DEFEDITOR;
269			if (editor[0] == '-' && editor[1] == '\0') {
270				sflg = 1;	/* no edit */
271				editor = NULL;
272			}
273		}
274	}
275
276	/*
277	 * If executing, parse [old=new] now
278	 */
279	if (lflg == 0 && argc > 0 &&
280	     ((repl = strchr(argv[0], '=')) != NULL)) {
281		pat = argv[0];
282		*repl++ = '\0';
283		argc--, argv++;
284	}
285	/*
286	 * determine [first] and [last]
287	 */
288	switch (argc) {
289	case 0:
290		firststr = lflg ? "-16" : "-1";
291		laststr = "-1";
292		break;
293	case 1:
294		firststr = argv[0];
295		laststr = lflg ? "-1" : argv[0];
296		break;
297	case 2:
298		firststr = argv[0];
299		laststr = argv[1];
300		break;
301	default:
302		error("too many args");
303	}
304	/*
305	 * Turn into event numbers.
306	 */
307	first = str_to_event(firststr, 0);
308	last = str_to_event(laststr, 1);
309
310	if (rflg) {
311		i = last;
312		last = first;
313		first = i;
314	}
315	/*
316	 * XXX - this should not depend on the event numbers
317	 * always increasing.  Add sequence numbers or offset
318	 * to the history element in next (diskbased) release.
319	 */
320	direction = first < last ? H_PREV : H_NEXT;
321
322	/*
323	 * If editing, grab a temp file.
324	 */
325	if (editor) {
326		int fd;
327		INTOFF;		/* easier */
328		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
329		if ((fd = mkstemp(editfile)) < 0)
330			error("can't create temporary file %s", editfile);
331		if ((efp = fdopen(fd, "w")) == NULL) {
332			close(fd);
333			error("can't allocate stdio buffer for temp");
334		}
335	}
336
337	/*
338	 * Loop through selected history events.  If listing or executing,
339	 * do it now.  Otherwise, put into temp file and call the editor
340	 * after.
341	 *
342	 * The history interface needs rethinking, as the following
343	 * convolutions will demonstrate.
344	 */
345	history(hist, &he, H_FIRST);
346	retval = history(hist, &he, H_NEXT_EVENT, first);
347	for (;retval != -1; retval = history(hist, &he, direction)) {
348		if (lflg) {
349			if (!nflg)
350				out1fmt("%5d ", he.num);
351			out1str(he.str);
352		} else {
353			char *s = pat ?
354			   fc_replace(he.str, pat, repl) : (char *)he.str;
355
356			if (sflg) {
357				if (displayhist) {
358					out2str(s);
359				}
360				evalstring(s);
361				if (displayhist && hist) {
362					/*
363					 *  XXX what about recursive and
364					 *  relative histnums.
365					 */
366					oldhistnum = he.num;
367					history(hist, &he, H_ENTER, s);
368					/*
369					 * XXX H_ENTER moves the internal
370					 * cursor, set it back to the current
371					 * entry.
372					 */
373					retval = history(hist, &he,
374					    H_NEXT_EVENT, oldhistnum);
375				}
376			} else
377				fputs(s, efp);
378		}
379		/*
380		 * At end?  (if we were to loose last, we'd sure be
381		 * messed up).
382		 */
383		if (he.num == last)
384			break;
385	}
386	if (editor) {
387		char *editcmd;
388
389		fclose(efp);
390		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
391		sprintf(editcmd, "%s %s", editor, editfile);
392		evalstring(editcmd);	/* XXX - should use no JC command */
393		INTON;
394		readcmdfile(editfile);	/* XXX - should read back - quick tst */
395		unlink(editfile);
396	}
397
398	if (lflg == 0 && active > 0)
399		--active;
400	if (displayhist)
401		displayhist = 0;
402	return 0;
403}
404
405STATIC char *
406fc_replace(const char *s, char *p, char *r)
407{
408	char *dest;
409	int plen = strlen(p);
410
411	STARTSTACKSTR(dest);
412	while (*s) {
413		if (*s == *p && strncmp(s, p, plen) == 0) {
414			while (*r)
415				STPUTC(*r++, dest);
416			s += plen;
417			*p = '\0';	/* so no more matches */
418		} else
419			STPUTC(*s++, dest);
420	}
421	STACKSTRNUL(dest);
422	dest = grabstackstr(dest);
423
424	return (dest);
425}
426
427int
428not_fcnumber(char *s)
429{
430	if (s == NULL)
431		return (0);
432	if (*s == '-')
433		s++;
434	return (!is_number(s));
435}
436
437int
438str_to_event(char *str, int last)
439{
440	HistEvent he;
441	char *s = str;
442	int relative = 0;
443	int i, retval;
444
445	retval = history(hist, &he, H_FIRST);
446	switch (*s) {
447	case '-':
448		relative = 1;
449		/*FALLTHROUGH*/
450	case '+':
451		s++;
452	}
453	if (is_number(s)) {
454		i = atoi(s);
455		if (relative) {
456			while (retval != -1 && i--) {
457				retval = history(hist, &he, H_NEXT);
458			}
459			if (retval == -1)
460				retval = history(hist, &he, H_LAST);
461		} else {
462			retval = history(hist, &he, H_NEXT_EVENT, i);
463			if (retval == -1) {
464				/*
465				 * the notion of first and last is
466				 * backwards to that of the history package
467				 */
468				retval = history(hist, &he, last ? H_FIRST : H_LAST);
469			}
470		}
471		if (retval == -1)
472			error("history number %s not found (internal error)",
473			       str);
474	} else {
475		/*
476		 * pattern
477		 */
478		retval = history(hist, &he, H_PREV_STR, str);
479		if (retval == -1)
480			error("history pattern not found: %s", str);
481	}
482	return (he.num);
483}
484
485int
486bindcmd(int argc, char **argv)
487{
488
489	if (el == NULL)
490		error("line editing is disabled");
491	return (el_parse(el, argc, argv));
492}
493
494#else
495#include "error.h"
496
497int
498histcmd(int argc, char **argv)
499{
500
501	error("not compiled with history support");
502	/*NOTREACHED*/
503	return (0);
504}
505
506int
507bindcmd(int argc, char **argv)
508{
509
510	error("not compiled with line editing support");
511	return (0);
512}
513#endif
514