histedit.c revision 201053
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 201053 2009-12-27 18:04:05Z 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				out2fmt_flush("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				out2fmt_flush("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	const char *editor = NULL;
168	HistEvent he;
169	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
170	int i, retval;
171	const char *firststr, *laststr;
172	int first, last, direction;
173	char *pat = NULL, *repl = NULL;
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 = NULL;
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					flushout(out2);
340				}
341				evalstring(s, 0);
342				if (displayhist && hist) {
343					/*
344					 *  XXX what about recursive and
345					 *  relative histnums.
346					 */
347					oldhistnum = he.num;
348					history(hist, &he, H_ENTER, s);
349					/*
350					 * XXX H_ENTER moves the internal
351					 * cursor, set it back to the current
352					 * entry.
353					 */
354					retval = history(hist, &he,
355					    H_NEXT_EVENT, oldhistnum);
356				}
357			} else
358				fputs(s, efp);
359		}
360		/*
361		 * At end?  (if we were to lose last, we'd sure be
362		 * messed up).
363		 */
364		if (he.num == last)
365			break;
366	}
367	if (editor) {
368		char *editcmd;
369
370		fclose(efp);
371		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
372		sprintf(editcmd, "%s %s", editor, editfile);
373		evalstring(editcmd, 0);	/* XXX - should use no JC command */
374		INTON;
375		readcmdfile(editfile);	/* XXX - should read back - quick tst */
376		unlink(editfile);
377	}
378
379	if (lflg == 0 && active > 0)
380		--active;
381	if (displayhist)
382		displayhist = 0;
383	return 0;
384}
385
386STATIC char *
387fc_replace(const char *s, char *p, char *r)
388{
389	char *dest;
390	int plen = strlen(p);
391
392	STARTSTACKSTR(dest);
393	while (*s) {
394		if (*s == *p && strncmp(s, p, plen) == 0) {
395			while (*r)
396				STPUTC(*r++, dest);
397			s += plen;
398			*p = '\0';	/* so no more matches */
399		} else
400			STPUTC(*s++, dest);
401	}
402	STACKSTRNUL(dest);
403	dest = grabstackstr(dest);
404
405	return (dest);
406}
407
408int
409not_fcnumber(const char *s)
410{
411	if (s == NULL)
412		return (0);
413	if (*s == '-')
414		s++;
415	return (!is_number(s));
416}
417
418int
419str_to_event(const char *str, int last)
420{
421	HistEvent he;
422	const char *s = str;
423	int relative = 0;
424	int i, retval;
425
426	retval = history(hist, &he, H_FIRST);
427	switch (*s) {
428	case '-':
429		relative = 1;
430		/*FALLTHROUGH*/
431	case '+':
432		s++;
433	}
434	if (is_number(s)) {
435		i = atoi(s);
436		if (relative) {
437			while (retval != -1 && i--) {
438				retval = history(hist, &he, H_NEXT);
439			}
440			if (retval == -1)
441				retval = history(hist, &he, H_LAST);
442		} else {
443			retval = history(hist, &he, H_NEXT_EVENT, i);
444			if (retval == -1) {
445				/*
446				 * the notion of first and last is
447				 * backwards to that of the history package
448				 */
449				retval = history(hist, &he, last ? H_FIRST : H_LAST);
450			}
451		}
452		if (retval == -1)
453			error("history number %s not found (internal error)",
454			       str);
455	} else {
456		/*
457		 * pattern
458		 */
459		retval = history(hist, &he, H_PREV_STR, str);
460		if (retval == -1)
461			error("history pattern not found: %s", str);
462	}
463	return (he.num);
464}
465
466int
467bindcmd(int argc, char **argv)
468{
469
470	if (el == NULL)
471		error("line editing is disabled");
472	return (el_parse(el, argc, (const char **)argv));
473}
474
475#else
476#include "error.h"
477
478int
479histcmd(int argc, char **argv)
480{
481
482	error("not compiled with history support");
483	/*NOTREACHED*/
484	return (0);
485}
486
487int
488bindcmd(int argc, char **argv)
489{
490
491	error("not compiled with line editing support");
492	return (0);
493}
494#endif
495