xref: /freebsd/bin/sh/histedit.c (revision 17d6c636720d00f77e5d098daf4c278f89d84f7b)
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
39 static char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
40 #endif
41 static const char rcsid[] =
42   "$FreeBSD$";
43 #endif /* not lint */
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 
70 History *hist;	/* history cookie */
71 EditLine *el;	/* editline cookie */
72 int displayhist;
73 static FILE *el_in, *el_out, *el_err;
74 
75 STATIC char *fc_replace __P((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  */
81 void
82 histedit()
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 {
120 bad:
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 		}
136 	} else {
137 		INTOFF;
138 		if (el) {	/* no editing if not interactive */
139 			el_end(el);
140 			el = NULL;
141 		}
142 		if (hist) {
143 			history_end(hist);
144 			hist = NULL;
145 		}
146 		INTON;
147 	}
148 }
149 
150 
151 void
152 sethistsize(hs)
153 	const char *hs;
154 {
155 	int histsize;
156 	HistEvent he;
157 
158 	if (hist != NULL) {
159 		if (hs == NULL || *hs == '\0' ||
160 		   (histsize = atoi(hs)) < 0)
161 			histsize = 100;
162 		history(hist, &he, H_EVENT, histsize);
163 	}
164 }
165 
166 /*
167  *  This command is provided since POSIX decided to standardize
168  *  the Korn shell fc command.  Oh well...
169  */
170 int
171 histcmd(argc, argv)
172 	int argc;
173 	char **argv;
174 {
175 	int ch;
176 	char *editor = NULL;
177 	HistEvent he;
178 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
179 	int i, retval;
180 	char *firststr, *laststr;
181 	int first, last, direction;
182 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
183 	static int active = 0;
184 	struct jmploc jmploc;
185 	struct jmploc *volatile savehandler;
186 	char editfile[PATH_MAX];
187 	FILE *efp;
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 = shoptarg;
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 					history(hist, &he, H_ENTER, s);
367 				}
368 			} else
369 				fputs(s, efp);
370 		}
371 		/*
372 		 * At end?  (if we were to loose last, we'd sure be
373 		 * messed up).
374 		 */
375 		if (he.num == last)
376 			break;
377 	}
378 	if (editor) {
379 		char *editcmd;
380 
381 		fclose(efp);
382 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
383 		sprintf(editcmd, "%s %s", editor, editfile);
384 		evalstring(editcmd);	/* XXX - should use no JC command */
385 		INTON;
386 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
387 		unlink(editfile);
388 	}
389 
390 	if (lflg == 0 && active > 0)
391 		--active;
392 	if (displayhist)
393 		displayhist = 0;
394 	return 0;
395 }
396 
397 STATIC char *
398 fc_replace(s, p, r)
399 	const char *s;
400 	char *p, *r;
401 {
402 	char *dest;
403 	int plen = strlen(p);
404 
405 	STARTSTACKSTR(dest);
406 	while (*s) {
407 		if (*s == *p && strncmp(s, p, plen) == 0) {
408 			while (*r)
409 				STPUTC(*r++, dest);
410 			s += plen;
411 			*p = '\0';	/* so no more matches */
412 		} else
413 			STPUTC(*s++, dest);
414 	}
415 	STACKSTRNUL(dest);
416 	dest = grabstackstr(dest);
417 
418 	return (dest);
419 }
420 
421 int
422 not_fcnumber(s)
423 	char *s;
424 {
425 	if (s == NULL)
426 		return (0);
427 	if (*s == '-')
428 		s++;
429 	return (!is_number(s));
430 }
431 
432 int
433 str_to_event(str, last)
434 	char *str;
435 	int last;
436 {
437 	HistEvent he;
438 	char *s = str;
439 	int relative = 0;
440 	int i, retval;
441 
442 	retval = history(hist, &he, H_FIRST);
443 	switch (*s) {
444 	case '-':
445 		relative = 1;
446 		/*FALLTHROUGH*/
447 	case '+':
448 		s++;
449 	}
450 	if (is_number(s)) {
451 		i = atoi(s);
452 		if (relative) {
453 			while (retval != -1 && i--) {
454 				retval = history(hist, &he, H_NEXT);
455 			}
456 			if (retval == -1)
457 				retval = history(hist, &he, H_LAST);
458 		} else {
459 			retval = history(hist, &he, H_NEXT_EVENT, i);
460 			if (retval == -1) {
461 				/*
462 				 * the notion of first and last is
463 				 * backwards to that of the history package
464 				 */
465 				retval = history(hist, &he, last ? H_FIRST : H_LAST);
466 			}
467 		}
468 		if (retval == -1)
469 			error("history number %s not found (internal error)",
470 			       str);
471 	} else {
472 		/*
473 		 * pattern
474 		 */
475 		retval = history(hist, &he, H_PREV_STR, str);
476 		if (retval == -1)
477 			error("history pattern not found: %s", str);
478 	}
479 	return (he.num);
480 }
481 #else
482 #include "error.h"
483 
484 int
485 histcmd(argc, argv)
486 	int argc;
487 	char **argv;
488 {
489 
490 	error("not compiled with history support");
491 	/*NOTREACHED*/
492 	return (0);
493 }
494 #endif
495