xref: /freebsd/bin/sh/histedit.c (revision 77a0943ded95b9e6438f7db70c4a28e4d93946d4)
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 <paths.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <unistd.h>
50 /*
51  * Editline and history functions (and glue).
52  */
53 #include "shell.h"
54 #include "parser.h"
55 #include "var.h"
56 #include "options.h"
57 #include "main.h"
58 #include "output.h"
59 #include "mystring.h"
60 #ifndef NO_HISTORY
61 #include "myhistedit.h"
62 #include "error.h"
63 #include "eval.h"
64 #include "memalloc.h"
65 
66 #define MAXHISTLOOPS	4	/* max recursions through fc */
67 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
68 
69 History *hist;	/* history cookie */
70 EditLine *el;	/* editline cookie */
71 int displayhist;
72 static FILE *el_in, *el_out;
73 
74 STATIC char *fc_replace __P((const char *, char *, char *));
75 
76 /*
77  * Set history and editing status.  Called whenever the status may
78  * have changed (figures out what to do).
79  */
80 void
81 histedit()
82 {
83 
84 #define editing (Eflag || Vflag)
85 
86 	if (iflag) {
87 		if (!hist) {
88 			/*
89 			 * turn history on
90 			 */
91 			INTOFF;
92 			hist = history_init();
93 			INTON;
94 
95 			if (hist != NULL)
96 				sethistsize(histsizeval());
97 			else
98 				out2str("sh: can't initialize history\n");
99 		}
100 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
101 			/*
102 			 * turn editing on
103 			 */
104 			INTOFF;
105 			if (el_in == NULL)
106 				el_in = fdopen(0, "r");
107 			if (el_out == NULL)
108 				el_out = fdopen(2, "w");
109 			if (el_in == NULL || el_out == NULL)
110 				goto bad;
111 			el = el_init(arg0, el_in, el_out);
112 			if (el != NULL) {
113 				if (hist)
114 					el_set(el, EL_HIST, history, hist);
115 				el_set(el, EL_PROMPT, getprompt);
116 			} else {
117 bad:
118 				out2str("sh: can't initialize editing\n");
119 			}
120 			INTON;
121 		} else if (!editing && el) {
122 			INTOFF;
123 			el_end(el);
124 			el = NULL;
125 			INTON;
126 		}
127 		if (el) {
128 			if (Vflag)
129 				el_set(el, EL_EDITOR, "vi");
130 			else if (Eflag)
131 				el_set(el, EL_EDITOR, "emacs");
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 
148 void
149 sethistsize(hs)
150 	const char *hs;
151 {
152 	int histsize;
153 
154 	if (hist != NULL) {
155 		if (hs == NULL || *hs == '\0' ||
156 		   (histsize = atoi(hs)) < 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 	int ch;
172 	char *editor = NULL;
173 	const HistEvent *he;
174 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
175 	int i;
176 	char *firststr, *laststr;
177 	int first, last, direction;
178 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
179 	static int active = 0;
180 	struct jmploc jmploc;
181 	struct jmploc *volatile savehandler;
182 	char editfile[MAXPATHLEN + 1];
183 	FILE *efp;
184 #ifdef __GNUC__
185 	/* Avoid longjmp clobbering */
186 	(void) &editor;
187 	(void) &lflg;
188 	(void) &nflg;
189 	(void) &rflg;
190 	(void) &sflg;
191 	(void) &firststr;
192 	(void) &laststr;
193 	(void) &pat;
194 	(void) &repl;
195 	(void) &efp;
196 	(void) &argc;
197 	(void) &argv;
198 #endif
199 
200 	if (hist == NULL)
201 		error("history not active");
202 
203 	if (argc == 1)
204 		error("missing history argument");
205 
206 	optreset = 1; optind = 1; /* initialize getopt */
207 	while (not_fcnumber(argv[optind]) &&
208 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
209 		switch ((char)ch) {
210 		case 'e':
211 			editor = shoptarg;
212 			break;
213 		case 'l':
214 			lflg = 1;
215 			break;
216 		case 'n':
217 			nflg = 1;
218 			break;
219 		case 'r':
220 			rflg = 1;
221 			break;
222 		case 's':
223 			sflg = 1;
224 			break;
225 		case ':':
226 			error("option -%c expects argument", optopt);
227 		case '?':
228 		default:
229 			error("unknown option: -%c", optopt);
230 		}
231 	argc -= optind, argv += optind;
232 
233 	/*
234 	 * If executing...
235 	 */
236 	if (lflg == 0 || editor || sflg) {
237 		lflg = 0;	/* ignore */
238 		editfile[0] = '\0';
239 		/*
240 		 * Catch interrupts to reset active counter and
241 		 * cleanup temp files.
242 		 */
243 		if (setjmp(jmploc.loc)) {
244 			active = 0;
245 			if (*editfile)
246 				unlink(editfile);
247 			handler = savehandler;
248 			longjmp(handler->loc, 1);
249 		}
250 		savehandler = handler;
251 		handler = &jmploc;
252 		if (++active > MAXHISTLOOPS) {
253 			active = 0;
254 			displayhist = 0;
255 			error("called recursively too many times");
256 		}
257 		/*
258 		 * Set editor.
259 		 */
260 		if (sflg == 0) {
261 			if (editor == NULL &&
262 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
263 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
264 				editor = DEFEDITOR;
265 			if (editor[0] == '-' && editor[1] == '\0') {
266 				sflg = 1;	/* no edit */
267 				editor = NULL;
268 			}
269 		}
270 	}
271 
272 	/*
273 	 * If executing, parse [old=new] now
274 	 */
275 	if (lflg == 0 && argc > 0 &&
276 	     ((repl = strchr(argv[0], '=')) != NULL)) {
277 		pat = argv[0];
278 		*repl++ = '\0';
279 		argc--, argv++;
280 	}
281 	/*
282 	 * determine [first] and [last]
283 	 */
284 	switch (argc) {
285 	case 0:
286 		firststr = lflg ? "-16" : "-1";
287 		laststr = "-1";
288 		break;
289 	case 1:
290 		firststr = argv[0];
291 		laststr = lflg ? "-1" : argv[0];
292 		break;
293 	case 2:
294 		firststr = argv[0];
295 		laststr = argv[1];
296 		break;
297 	default:
298 		error("too many args");
299 	}
300 	/*
301 	 * Turn into event numbers.
302 	 */
303 	first = str_to_event(firststr, 0);
304 	last = str_to_event(laststr, 1);
305 
306 	if (rflg) {
307 		i = last;
308 		last = first;
309 		first = i;
310 	}
311 	/*
312 	 * XXX - this should not depend on the event numbers
313 	 * always increasing.  Add sequence numbers or offset
314 	 * to the history element in next (diskbased) release.
315 	 */
316 	direction = first < last ? H_PREV : H_NEXT;
317 
318 	/*
319 	 * If editing, grab a temp file.
320 	 */
321 	if (editor) {
322 		int fd;
323 		INTOFF;		/* easier */
324 		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
325 		if ((fd = mkstemp(editfile)) < 0)
326 			error("can't create temporary file %s", editfile);
327 		if ((efp = fdopen(fd, "w")) == NULL) {
328 			close(fd);
329 			error("can't allocate stdio buffer for temp");
330 		}
331 	}
332 
333 	/*
334 	 * Loop through selected history events.  If listing or executing,
335 	 * do it now.  Otherwise, put into temp file and call the editor
336 	 * after.
337 	 *
338 	 * The history interface needs rethinking, as the following
339 	 * convolutions will demonstrate.
340 	 */
341 	history(hist, H_FIRST);
342 	he = history(hist, H_NEXT_EVENT, first);
343 	for (;he != NULL; he = history(hist, direction)) {
344 		if (lflg) {
345 			if (!nflg)
346 				out1fmt("%5d ", he->num);
347 			out1str(he->str);
348 		} else {
349 			char *s = pat ?
350 			   fc_replace(he->str, pat, repl) : (char *)he->str;
351 
352 			if (sflg) {
353 				if (displayhist) {
354 					out2str(s);
355 				}
356 				evalstring(s);
357 				if (displayhist && hist) {
358 					/*
359 					 *  XXX what about recursive and
360 					 *  relative histnums.
361 					 */
362 					history(hist, H_ENTER, s);
363 				}
364 			} else
365 				fputs(s, efp);
366 		}
367 		/*
368 		 * At end?  (if we were to loose last, we'd sure be
369 		 * messed up).
370 		 */
371 		if (he->num == last)
372 			break;
373 	}
374 	if (editor) {
375 		char *editcmd;
376 
377 		fclose(efp);
378 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
379 		sprintf(editcmd, "%s %s", editor, editfile);
380 		evalstring(editcmd);	/* XXX - should use no JC command */
381 		INTON;
382 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
383 		unlink(editfile);
384 	}
385 
386 	if (lflg == 0 && active > 0)
387 		--active;
388 	if (displayhist)
389 		displayhist = 0;
390 	return 0;
391 }
392 
393 STATIC char *
394 fc_replace(s, p, r)
395 	const char *s;
396 	char *p, *r;
397 {
398 	char *dest;
399 	int plen = strlen(p);
400 
401 	STARTSTACKSTR(dest);
402 	while (*s) {
403 		if (*s == *p && strncmp(s, p, plen) == 0) {
404 			while (*r)
405 				STPUTC(*r++, dest);
406 			s += plen;
407 			*p = '\0';	/* so no more matches */
408 		} else
409 			STPUTC(*s++, dest);
410 	}
411 	STACKSTRNUL(dest);
412 	dest = grabstackstr(dest);
413 
414 	return (dest);
415 }
416 
417 int
418 not_fcnumber(s)
419 	char *s;
420 {
421 	if (s == NULL)
422 		return (0);
423 	if (*s == '-')
424 		s++;
425 	return (!is_number(s));
426 }
427 
428 int
429 str_to_event(str, last)
430 	char *str;
431 	int last;
432 {
433 	const HistEvent *he;
434 	char *s = str;
435 	int relative = 0;
436 	int i;
437 
438 	he = history(hist, H_FIRST);
439 	switch (*s) {
440 	case '-':
441 		relative = 1;
442 		/*FALLTHROUGH*/
443 	case '+':
444 		s++;
445 	}
446 	if (is_number(s)) {
447 		i = atoi(s);
448 		if (relative) {
449 			while (he != NULL && i--) {
450 				he = history(hist, H_NEXT);
451 			}
452 			if (he == NULL)
453 				he = history(hist, H_LAST);
454 		} else {
455 			he = history(hist, H_NEXT_EVENT, i);
456 			if (he == NULL) {
457 				/*
458 				 * the notion of first and last is
459 				 * backwards to that of the history package
460 				 */
461 				he = history(hist, last ? H_FIRST : H_LAST);
462 			}
463 		}
464 		if (he == NULL)
465 			error("history number %s not found (internal error)",
466 			       str);
467 	} else {
468 		/*
469 		 * pattern
470 		 */
471 		he = history(hist, H_PREV_STR, str);
472 		if (he == NULL)
473 			error("history pattern not found: %s", str);
474 	}
475 	return (he->num);
476 }
477 #else
478 #include "error.h"
479 
480 int
481 histcmd(argc, argv)
482 	int argc;
483 	char **argv;
484 {
485 
486 	error("not compiled with history support");
487 	/*NOTREACHED*/
488 	return (0);
489 }
490 #endif
491