histedit.c revision 213814
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 213814 2010-10-13 23:29:09Z obrien $");
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				out2fmt_flush("sh: can't initialize history\n");
96		}
97		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
98			/*
99			 * turn editing on
100			 */
101			char *term;
102
103			INTOFF;
104			if (el_in == NULL)
105				el_in = fdopen(0, "r");
106			if (el_err == NULL)
107				el_err = fdopen(1, "w");
108			if (el_out == NULL)
109				el_out = fdopen(2, "w");
110			if (el_in == NULL || el_err == NULL || el_out == NULL)
111				goto bad;
112			term = lookupvar("TERM");
113			if (term)
114				setenv("TERM", term, 1);
115			else
116				unsetenv("TERM");
117			el = el_init(arg0, el_in, el_out, el_err);
118			if (el != NULL) {
119				if (hist)
120					el_set(el, EL_HIST, history, hist);
121				el_set(el, EL_PROMPT, getprompt);
122				el_set(el, EL_ADDFN, "sh-complete",
123				    "Filename completion",
124				    _el_fn_sh_complete);
125			} else {
126bad:
127				out2fmt_flush("sh: can't initialize editing\n");
128			}
129			INTON;
130		} else if (!editing && el) {
131			INTOFF;
132			el_end(el);
133			el = NULL;
134			INTON;
135		}
136		if (el) {
137			if (Vflag)
138				el_set(el, EL_EDITOR, "vi");
139			else if (Eflag)
140				el_set(el, EL_EDITOR, "emacs");
141			el_set(el, EL_BIND, "^I", "sh-complete", NULL);
142			el_source(el, NULL);
143		}
144	} else {
145		INTOFF;
146		if (el) {	/* no editing if not interactive */
147			el_end(el);
148			el = NULL;
149		}
150		if (hist) {
151			history_end(hist);
152			hist = NULL;
153		}
154		INTON;
155	}
156}
157
158
159void
160sethistsize(hs)
161	const char *hs;
162{
163	int histsize;
164	HistEvent he;
165
166	if (hist != NULL) {
167		if (hs == NULL || *hs == '\0' ||
168		   (histsize = atoi(hs)) < 0)
169			histsize = 100;
170		history(hist, &he, H_SETSIZE, histsize);
171		history(hist, &he, H_SETUNIQUE, 1);
172	}
173}
174
175void
176setterm(const char *term)
177{
178	if (rootshell && el != NULL && term != NULL)
179		el_set(el, EL_TERMINAL, term);
180}
181
182int
183histcmd(int argc, char **argv)
184{
185	int ch;
186	const char *editor = NULL;
187	HistEvent he;
188	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
189	int i, retval;
190	const char *firststr, *laststr;
191	int first, last, direction;
192	char *pat = NULL, *repl = NULL;
193	static int active = 0;
194	struct jmploc jmploc;
195	struct jmploc *savehandler;
196	char editfilestr[PATH_MAX];
197	char *volatile editfile;
198	FILE *efp = NULL;
199	int oldhistnum;
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	opterr = 0;
209	while (not_fcnumber(argv[optind]) &&
210	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
211		switch ((char)ch) {
212		case 'e':
213			editor = optarg;
214			break;
215		case 'l':
216			lflg = 1;
217			break;
218		case 'n':
219			nflg = 1;
220			break;
221		case 'r':
222			rflg = 1;
223			break;
224		case 's':
225			sflg = 1;
226			break;
227		case ':':
228			error("option -%c expects argument", optopt);
229		case '?':
230		default:
231			error("unknown option: -%c", optopt);
232		}
233	argc -= optind, argv += optind;
234
235	/*
236	 * If executing...
237	 */
238	if (lflg == 0 || editor || sflg) {
239		lflg = 0;	/* ignore */
240		editfile = NULL;
241		/*
242		 * Catch interrupts to reset active counter and
243		 * cleanup temp files.
244		 */
245		savehandler = handler;
246		if (setjmp(jmploc.loc)) {
247			active = 0;
248			if (editfile)
249				unlink(editfile);
250			handler = savehandler;
251			longjmp(handler->loc, 1);
252		}
253		handler = &jmploc;
254		if (++active > MAXHISTLOOPS) {
255			active = 0;
256			displayhist = 0;
257			error("called recursively too many times");
258		}
259		/*
260		 * Set editor.
261		 */
262		if (sflg == 0) {
263			if (editor == NULL &&
264			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
265			    (editor = bltinlookup("EDITOR", 1)) == NULL)
266				editor = DEFEDITOR;
267			if (editor[0] == '-' && editor[1] == '\0') {
268				sflg = 1;	/* no edit */
269				editor = NULL;
270			}
271		}
272	}
273
274	/*
275	 * If executing, parse [old=new] now
276	 */
277	if (lflg == 0 && argc > 0 &&
278	     ((repl = strchr(argv[0], '=')) != NULL)) {
279		pat = argv[0];
280		*repl++ = '\0';
281		argc--, argv++;
282	}
283	/*
284	 * determine [first] and [last]
285	 */
286	switch (argc) {
287	case 0:
288		firststr = lflg ? "-16" : "-1";
289		laststr = "-1";
290		break;
291	case 1:
292		firststr = argv[0];
293		laststr = lflg ? "-1" : argv[0];
294		break;
295	case 2:
296		firststr = argv[0];
297		laststr = argv[1];
298		break;
299	default:
300		error("too many args");
301	}
302	/*
303	 * Turn into event numbers.
304	 */
305	first = str_to_event(firststr, 0);
306	last = str_to_event(laststr, 1);
307
308	if (rflg) {
309		i = last;
310		last = first;
311		first = i;
312	}
313	/*
314	 * XXX - this should not depend on the event numbers
315	 * always increasing.  Add sequence numbers or offset
316	 * to the history element in next (diskbased) release.
317	 */
318	direction = first < last ? H_PREV : H_NEXT;
319
320	/*
321	 * If editing, grab a temp file.
322	 */
323	if (editor) {
324		int fd;
325		INTOFF;		/* easier */
326		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
327		if ((fd = mkstemp(editfilestr)) < 0)
328			error("can't create temporary file %s", editfile);
329		editfile = editfilestr;
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					flushout(out2);
359				}
360				evalstring(s, 0);
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 lose 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, 0);	/* 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	STPUTC('\0', dest);
422	dest = grabstackstr(dest);
423
424	return (dest);
425}
426
427int
428not_fcnumber(const 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(const char *str, int last)
439{
440	HistEvent he;
441	const 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, (const char **)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