xref: /freebsd/bin/sh/histedit.c (revision e627b39baccd1ec9129690167cf5e6d860509655)
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  *	$Id: histedit.c,v 1.5 1996/09/01 10:20:12 peter Exp $
37  */
38 
39 #ifndef lint
40 static char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
41 #endif /* not lint */
42 
43 #include <sys/param.h>
44 #include <paths.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <unistd.h>
48 /*
49  * Editline and history functions (and glue).
50  */
51 #include "shell.h"
52 #include "parser.h"
53 #include "var.h"
54 #include "options.h"
55 #include "main.h"
56 #include "output.h"
57 #include "mystring.h"
58 #ifndef NO_HISTORY
59 #include "myhistedit.h"
60 #endif
61 #include "error.h"
62 #include "eval.h"
63 #include "memalloc.h"
64 
65 #define MAXHISTLOOPS	4	/* max recursions through fc */
66 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
67 
68 History *hist;	/* history cookie */
69 EditLine *el;	/* editline cookie */
70 int displayhist;
71 static FILE *el_in, *el_out;
72 
73 STATIC char *fc_replace __P((const char *, char *, char *));
74 
75 /*
76  * Set history and editing status.  Called whenever the status may
77  * have changed (figures out what to do).
78  */
79 void
80 histedit()
81 {
82 
83 #define editing (Eflag || Vflag)
84 
85 	if (iflag) {
86 		if (!hist) {
87 			/*
88 			 * turn history on
89 			 */
90 			INTOFF;
91 			hist = history_init();
92 			INTON;
93 
94 			if (hist != NULL)
95 				sethistsize();
96 			else
97 				out2str("sh: can't initialize history\n");
98 		}
99 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
100 			/*
101 			 * turn editing on
102 			 */
103 			INTOFF;
104 			if (el_in == NULL)
105 				el_in = fdopen(0, "r");
106 			if (el_out == NULL)
107 				el_out = fdopen(2, "w");
108 			if (el_in == NULL || el_out == NULL)
109 				goto bad;
110 			el = el_init(arg0, el_in, el_out);
111 			if (el != NULL) {
112 				if (hist)
113 					el_set(el, EL_HIST, history, hist);
114 				el_set(el, EL_PROMPT, getprompt);
115 			} else {
116 bad:
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 		}
132 	} else {
133 		INTOFF;
134 		if (el) {	/* no editing if not interactive */
135 			el_end(el);
136 			el = NULL;
137 		}
138 		if (hist) {
139 			history_end(hist);
140 			hist = NULL;
141 		}
142 		INTON;
143 	}
144 }
145 
146 
147 void
148 sethistsize()
149 {
150 	char *cp;
151 	int histsize;
152 
153 	if (hist != NULL) {
154 		cp = lookupvar("HISTSIZE");
155 		if (cp == NULL || *cp == '\0' ||
156 		   (histsize = atoi(cp)) < 0)
157 			histsize = 100;
158 		history(hist, H_EVENT, histsize);
159 	}
160 }
161 
162 /*
163  *  This command is provided since POSIX decided to standardize
164  *  the Korn shell fc command.  Oh well...
165  */
166 int
167 histcmd(argc, argv)
168 	int argc;
169 	char **argv;
170 {
171 	extern char *optarg;
172 	extern int optind, optopt, optreset;
173 	int ch;
174 	char *editor = NULL;
175 	const HistEvent *he;
176 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
177 	int i;
178 	char *firststr, *laststr;
179 	int first, last, direction;
180 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
181 	static int active = 0;
182 	struct jmploc jmploc;
183 	struct jmploc *volatile savehandler;
184 	char editfile[MAXPATHLEN + 1];
185 	FILE *efp;
186 #ifdef __GNUC__
187 	/* Avoid longjmp clobbering */
188 	(void) &editor;
189 	(void) &lflg;
190 	(void) &nflg;
191 	(void) &rflg;
192 	(void) &sflg;
193 	(void) &firststr;
194 	(void) &laststr;
195 	(void) &pat;
196 	(void) &repl;
197 	(void) &efp;
198 	(void) &argc;
199 	(void) &argv;
200 #endif
201 
202 	if (hist == NULL)
203 		error("history not active");
204 
205 	if (argc == 1)
206 		error("missing history argument");
207 
208 	optreset = 1; optind = 1; /* initialize getopt */
209 	while (not_fcnumber(argv[optind]) &&
210 	      (ch = getopt(argc, argv, ":e:lnrs")) != EOF)
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[0] = '\0';
241 		/*
242 		 * Catch interrupts to reset active counter and
243 		 * cleanup temp files.
244 		 */
245 		if (setjmp(jmploc.loc)) {
246 			active = 0;
247 			if (*editfile)
248 				unlink(editfile);
249 			handler = savehandler;
250 			longjmp(handler->loc, 1);
251 		}
252 		savehandler = handler;
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(editfile, "%s/_shXXXXXX", _PATH_TMP);
327 		if ((fd = mkstemp(editfile)) < 0)
328 			error("can't create temporary file %s", editfile);
329 		if ((efp = fdopen(fd, "w")) == NULL) {
330 			close(fd);
331 			error("can't allocate stdio buffer for temp");
332 		}
333 	}
334 
335 	/*
336 	 * Loop through selected history events.  If listing or executing,
337 	 * do it now.  Otherwise, put into temp file and call the editor
338 	 * after.
339 	 *
340 	 * The history interface needs rethinking, as the following
341 	 * convolutions will demonstrate.
342 	 */
343 	history(hist, H_FIRST);
344 	he = history(hist, H_NEXT_EVENT, first);
345 	for (;he != NULL; he = history(hist, direction)) {
346 		if (lflg) {
347 			if (!nflg)
348 				out1fmt("%5d ", he->num);
349 			out1str(he->str);
350 		} else {
351 			char *s = pat ?
352 			   fc_replace(he->str, pat, repl) : (char *)he->str;
353 
354 			if (sflg) {
355 				if (displayhist) {
356 					out2str(s);
357 				}
358 				evalstring(s);
359 				if (displayhist && hist) {
360 					/*
361 					 *  XXX what about recursive and
362 					 *  relative histnums.
363 					 */
364 					history(hist, H_ENTER, s);
365 				}
366 			} else
367 				fputs(s, efp);
368 		}
369 		/*
370 		 * At end?  (if we were to loose last, we'd sure be
371 		 * messed up).
372 		 */
373 		if (he->num == last)
374 			break;
375 	}
376 	if (editor) {
377 		char *editcmd;
378 
379 		fclose(efp);
380 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
381 		sprintf(editcmd, "%s %s", editor, editfile);
382 		evalstring(editcmd);	/* XXX - should use no JC command */
383 		INTON;
384 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
385 		unlink(editfile);
386 	}
387 
388 	if (lflg == 0 && active > 0)
389 		--active;
390 	if (displayhist)
391 		displayhist = 0;
392 	return 0;
393 }
394 
395 STATIC char *
396 fc_replace(s, p, r)
397 	const char *s;
398 	char *p, *r;
399 {
400 	char *dest;
401 	int plen = strlen(p);
402 
403 	STARTSTACKSTR(dest);
404 	while (*s) {
405 		if (*s == *p && strncmp(s, p, plen) == 0) {
406 			while (*r)
407 				STPUTC(*r++, dest);
408 			s += plen;
409 			*p = '\0';	/* so no more matches */
410 		} else
411 			STPUTC(*s++, dest);
412 	}
413 	STACKSTRNUL(dest);
414 	dest = grabstackstr(dest);
415 
416 	return (dest);
417 }
418 
419 int
420 not_fcnumber(s)
421         char *s;
422 {
423 	if (s == NULL) {
424 		/* NULL is not a fc_number */
425 		return (1);
426 	}
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 	const HistEvent *he;
438 	char *s = str;
439 	int relative = 0;
440 	int i;
441 
442 	he = history(hist, 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 (he != NULL && i--) {
454 				he = history(hist, H_NEXT);
455 			}
456 			if (he == NULL)
457 				he = history(hist, H_LAST);
458 		} else {
459 			he = history(hist, H_NEXT_EVENT, i);
460 			if (he == NULL) {
461 				/*
462 				 * the notion of first and last is
463 				 * backwards to that of the history package
464 				 */
465 				he = history(hist, last ? H_FIRST : H_LAST);
466 			}
467 		}
468 		if (he == NULL)
469 			error("history number %s not found (internal error)",
470 			       str);
471 	} else {
472 		/*
473 		 * pattern
474 		 */
475 		he = history(hist, H_PREV_STR, str);
476 		if (he == NULL)
477 			error("history pattern not found: %s", str);
478 	}
479 	return (he->num);
480 }
481