histedit.c revision 215783
1219820Sjeff/*-
2219820Sjeff * Copyright (c) 1993
3219820Sjeff *	The Regents of the University of California.  All rights reserved.
4219820Sjeff *
5329973Shselasky * This code is derived from software contributed to Berkeley by
6219820Sjeff * Kenneth Almquist.
7219820Sjeff *
8219820Sjeff * Redistribution and use in source and binary forms, with or without
9219820Sjeff * modification, are permitted provided that the following conditions
10219820Sjeff * are met:
11219820Sjeff * 1. Redistributions of source code must retain the above copyright
12219820Sjeff *    notice, this list of conditions and the following disclaimer.
13219820Sjeff * 2. Redistributions in binary form must reproduce the above copyright
14219820Sjeff *    notice, this list of conditions and the following disclaimer in the
15219820Sjeff *    documentation and/or other materials provided with the distribution.
16219820Sjeff * 4. Neither the name of the University nor the names of its contributors
17219820Sjeff *    may be used to endorse or promote products derived from this software
18219820Sjeff *    without specific prior written permission.
19219820Sjeff *
20219820Sjeff * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21219820Sjeff * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22219820Sjeff * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23219820Sjeff * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24219820Sjeff * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25219820Sjeff * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26219820Sjeff * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27219820Sjeff * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28289644Shselasky * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29289644Shselasky * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30219820Sjeff * SUCH DAMAGE.
31219820Sjeff */
32219820Sjeff
33219820Sjeff#ifndef lint
34290335Shselasky#if 0
35290335Shselaskystatic char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
36219820Sjeff#endif
37329973Shselasky#endif /* not lint */
38329973Shselasky#include <sys/cdefs.h>
39329973Shselasky__FBSDID("$FreeBSD: head/bin/sh/histedit.c 215783 2010-11-23 22:17:39Z jilles $");
40329973Shselasky
41219820Sjeff#include <sys/param.h>
42329973Shselasky#include <limits.h>
43329973Shselasky#include <paths.h>
44329973Shselasky#include <stdio.h>
45329973Shselasky#include <stdlib.h>
46219820Sjeff#include <unistd.h>
47219820Sjeff/*
48219820Sjeff * Editline and history functions (and glue).
49219820Sjeff */
50219820Sjeff#include "shell.h"
51219820Sjeff#include "parser.h"
52219820Sjeff#include "var.h"
53219820Sjeff#include "options.h"
54219820Sjeff#include "main.h"
55219820Sjeff#include "output.h"
56219820Sjeff#include "mystring.h"
57329973Shselasky#ifndef NO_HISTORY
58329973Shselasky#include "myhistedit.h"
59329973Shselasky#include "error.h"
60329973Shselasky#include "eval.h"
61219820Sjeff#include "memalloc.h"
62219820Sjeff
63219820Sjeff#define MAXHISTLOOPS	4	/* max recursions through fc */
64219820Sjeff#define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
65219820Sjeff
66219820SjeffHistory *hist;	/* history cookie */
67219820SjeffEditLine *el;	/* editline cookie */
68329973Shselaskyint displayhist;
69329973Shselaskystatic FILE *el_in, *el_out, *el_err;
70329973Shselasky
71329973Shselaskystatic char *fc_replace(const char *, char *, char *);
72329973Shselasky
73329973Shselasky/*
74329973Shselasky * Set history and editing status.  Called whenever the status may
75329973Shselasky * have changed (figures out what to do).
76329973Shselasky */
77329973Shselaskyvoid
78219820Sjeffhistedit(void)
79219820Sjeff{
80219820Sjeff
81329973Shselasky#define editing (Eflag || Vflag)
82219820Sjeff
83219820Sjeff	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 arguments");
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("Out of space");
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			STPUTS(r, dest);
415			s += plen;
416			*p = '\0';	/* so no more matches */
417		} else
418			STPUTC(*s++, dest);
419	}
420	STPUTC('\0', dest);
421	dest = grabstackstr(dest);
422
423	return (dest);
424}
425
426int
427not_fcnumber(const char *s)
428{
429	if (s == NULL)
430		return (0);
431	if (*s == '-')
432		s++;
433	return (!is_number(s));
434}
435
436int
437str_to_event(const char *str, int last)
438{
439	HistEvent he;
440	const char *s = str;
441	int relative = 0;
442	int i, retval;
443
444	retval = history(hist, &he, H_FIRST);
445	switch (*s) {
446	case '-':
447		relative = 1;
448		/*FALLTHROUGH*/
449	case '+':
450		s++;
451	}
452	if (is_number(s)) {
453		i = atoi(s);
454		if (relative) {
455			while (retval != -1 && i--) {
456				retval = history(hist, &he, H_NEXT);
457			}
458			if (retval == -1)
459				retval = history(hist, &he, H_LAST);
460		} else {
461			retval = history(hist, &he, H_NEXT_EVENT, i);
462			if (retval == -1) {
463				/*
464				 * the notion of first and last is
465				 * backwards to that of the history package
466				 */
467				retval = history(hist, &he, last ? H_FIRST : H_LAST);
468			}
469		}
470		if (retval == -1)
471			error("history number %s not found (internal error)",
472			       str);
473	} else {
474		/*
475		 * pattern
476		 */
477		retval = history(hist, &he, H_PREV_STR, str);
478		if (retval == -1)
479			error("history pattern not found: %s", str);
480	}
481	return (he.num);
482}
483
484int
485bindcmd(int argc, char **argv)
486{
487
488	if (el == NULL)
489		error("line editing is disabled");
490	return (el_parse(el, argc, (const char **)argv));
491}
492
493#else
494#include "error.h"
495
496int
497histcmd(int argc, char **argv)
498{
499
500	error("not compiled with history support");
501	/*NOTREACHED*/
502	return (0);
503}
504
505int
506bindcmd(int argc, char **argv)
507{
508
509	error("not compiled with line editing support");
510	return (0);
511}
512#endif
513