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