xref: /netbsd-src/bin/sh/histedit.c (revision 481fca6e59249d8ffcf24fef7cfbe7b131bfb080)
1 /*	$NetBSD: histedit.c,v 1.23 2000/04/14 05:52:58 simonb Exp $	*/
2 
3 /*-
4  * Copyright (c) 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
43 #else
44 __RCSID("$NetBSD: histedit.c,v 1.23 2000/04/14 05:52:58 simonb Exp $");
45 #endif
46 #endif /* not lint */
47 
48 #include <sys/param.h>
49 #include <paths.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <unistd.h>
53 /*
54  * Editline and history functions (and glue).
55  */
56 #include "shell.h"
57 #include "parser.h"
58 #include "var.h"
59 #include "options.h"
60 #include "main.h"
61 #include "output.h"
62 #include "mystring.h"
63 #include "myhistedit.h"
64 #include "error.h"
65 #ifndef SMALL
66 #include "eval.h"
67 #include "memalloc.h"
68 
69 #define MAXHISTLOOPS	4	/* max recursions through fc */
70 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
71 
72 History *hist;	/* history cookie */
73 EditLine *el;	/* editline cookie */
74 int displayhist;
75 static FILE *el_in, *el_out;
76 
77 STATIC const char *fc_replace __P((const char *, char *, char *));
78 
79 /*
80  * Set history and editing status.  Called whenever the status may
81  * have changed (figures out what to do).
82  */
83 void
84 histedit()
85 {
86 
87 #define editing (Eflag || Vflag)
88 
89 	if (iflag) {
90 		if (!hist) {
91 			/*
92 			 * turn history on
93 			 */
94 			INTOFF;
95 			hist = history_init();
96 			INTON;
97 
98 			if (hist != NULL)
99 				sethistsize(histsizeval());
100 			else
101 				out2str("sh: can't initialize history\n");
102 		}
103 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
104 			/*
105 			 * turn editing on
106 			 */
107 			INTOFF;
108 			if (el_in == NULL)
109 				el_in = fdopen(0, "r");
110 			if (el_out == NULL)
111 				el_out = fdopen(2, "w");
112 			if (el_in == NULL || el_out == NULL)
113 				goto bad;
114 			el = el_init(arg0, el_in, el_out, el_out);
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_SETSIZE, histsize);
163 	}
164 }
165 
166 void
167 setterm(term)
168 	const char *term;
169 {
170 	if (el != NULL && term != NULL)
171 		if (el_set(el, EL_TERMINAL, term) != 0) {
172 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
173 			outfmt(out2, "sh: Using dumb terminal settings.\n");
174 		}
175 }
176 
177 /*
178  *  This command is provided since POSIX decided to standardize
179  *  the Korn shell fc command.  Oh well...
180  */
181 int
182 histcmd(argc, argv)
183 	int argc;
184 	char **argv;
185 {
186 	int ch;
187 	const char *editor = NULL;
188 	HistEvent he;
189 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
190 	int i, retval;
191 	const char *firststr, *laststr;
192 	int first, last, direction;
193 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
194 	static int active = 0;
195 	struct jmploc jmploc;
196 	struct jmploc *volatile savehandler;
197 	char editfile[MAXPATHLEN + 1];
198 	FILE *efp;
199 #ifdef __GNUC__
200 	/* Avoid longjmp clobbering */
201 	(void) &editor;
202 	(void) &lflg;
203 	(void) &nflg;
204 	(void) &rflg;
205 	(void) &sflg;
206 	(void) &firststr;
207 	(void) &laststr;
208 	(void) &pat;
209 	(void) &repl;
210 	(void) &efp;
211 	(void) &argc;
212 	(void) &argv;
213 #endif
214 
215 	if (hist == NULL)
216 		error("history not active");
217 
218 	if (argc == 1)
219 		error("missing history argument");
220 
221 	optreset = 1; optind = 1; /* initialize getopt */
222 	while (not_fcnumber(argv[optind]) &&
223 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
224 		switch ((char)ch) {
225 		case 'e':
226 			editor = optarg;
227 			break;
228 		case 'l':
229 			lflg = 1;
230 			break;
231 		case 'n':
232 			nflg = 1;
233 			break;
234 		case 'r':
235 			rflg = 1;
236 			break;
237 		case 's':
238 			sflg = 1;
239 			break;
240 		case ':':
241 			error("option -%c expects argument", optopt);
242 			/* NOTREACHED */
243 		case '?':
244 		default:
245 			error("unknown option: -%c", optopt);
246 			/* NOTREACHED */
247 		}
248 	argc -= optind, argv += optind;
249 
250 	/*
251 	 * If executing...
252 	 */
253 	if (lflg == 0 || editor || sflg) {
254 		lflg = 0;	/* ignore */
255 		editfile[0] = '\0';
256 		/*
257 		 * Catch interrupts to reset active counter and
258 		 * cleanup temp files.
259 		 */
260 		if (setjmp(jmploc.loc)) {
261 			active = 0;
262 			if (*editfile)
263 				unlink(editfile);
264 			handler = savehandler;
265 			longjmp(handler->loc, 1);
266 		}
267 		savehandler = handler;
268 		handler = &jmploc;
269 		if (++active > MAXHISTLOOPS) {
270 			active = 0;
271 			displayhist = 0;
272 			error("called recursively too many times");
273 		}
274 		/*
275 		 * Set editor.
276 		 */
277 		if (sflg == 0) {
278 			if (editor == NULL &&
279 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
280 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
281 				editor = DEFEDITOR;
282 			if (editor[0] == '-' && editor[1] == '\0') {
283 				sflg = 1;	/* no edit */
284 				editor = NULL;
285 			}
286 		}
287 	}
288 
289 	/*
290 	 * If executing, parse [old=new] now
291 	 */
292 	if (lflg == 0 && argc > 0 &&
293 	     ((repl = strchr(argv[0], '=')) != NULL)) {
294 		pat = argv[0];
295 		*repl++ = '\0';
296 		argc--, argv++;
297 	}
298 	/*
299 	 * determine [first] and [last]
300 	 */
301 	switch (argc) {
302 	case 0:
303 		firststr = lflg ? "-16" : "-1";
304 		laststr = "-1";
305 		break;
306 	case 1:
307 		firststr = argv[0];
308 		laststr = lflg ? "-1" : argv[0];
309 		break;
310 	case 2:
311 		firststr = argv[0];
312 		laststr = argv[1];
313 		break;
314 	default:
315 		error("too many args");
316 		/* NOTREACHED */
317 	}
318 	/*
319 	 * Turn into event numbers.
320 	 */
321 	first = str_to_event(firststr, 0);
322 	last = str_to_event(laststr, 1);
323 
324 	if (rflg) {
325 		i = last;
326 		last = first;
327 		first = i;
328 	}
329 	/*
330 	 * XXX - this should not depend on the event numbers
331 	 * always increasing.  Add sequence numbers or offset
332 	 * to the history element in next (diskbased) release.
333 	 */
334 	direction = first < last ? H_PREV : H_NEXT;
335 
336 	/*
337 	 * If editing, grab a temp file.
338 	 */
339 	if (editor) {
340 		int fd;
341 		INTOFF;		/* easier */
342 		sprintf(editfile, "%s_shXXXXXX", _PATH_TMP);
343 		if ((fd = mkstemp(editfile)) < 0)
344 			error("can't create temporary file %s", editfile);
345 		if ((efp = fdopen(fd, "w")) == NULL) {
346 			close(fd);
347 			error("can't allocate stdio buffer for temp");
348 		}
349 	}
350 
351 	/*
352 	 * Loop through selected history events.  If listing or executing,
353 	 * do it now.  Otherwise, put into temp file and call the editor
354 	 * after.
355 	 *
356 	 * The history interface needs rethinking, as the following
357 	 * convolutions will demonstrate.
358 	 */
359 	history(hist, &he, H_FIRST);
360 	retval = history(hist, &he, H_NEXT_EVENT, first);
361 	for (;retval != -1; retval = history(hist, &he, direction)) {
362 		if (lflg) {
363 			if (!nflg)
364 				out1fmt("%5d ", he.num);
365 			out1str(he.str);
366 		} else {
367 			const char *s = pat ?
368 			   fc_replace(he.str, pat, repl) : he.str;
369 			char *sp;
370 
371 			if (sflg) {
372 				if (displayhist) {
373 					out2str(s);
374 				}
375 
376 				evalstring(strcpy(stalloc(strlen(s) + 1), s), 0);
377 				free(sp);
378 				if (displayhist && hist) {
379 					/*
380 					 *  XXX what about recursive and
381 					 *  relative histnums.
382 					 */
383 					history(hist, &he, H_ENTER, s);
384 				}
385 			} else
386 				fputs(s, efp);
387 		}
388 		/*
389 		 * At end?  (if we were to lose last, we'd sure be
390 		 * messed up).
391 		 */
392 		if (he.num == last)
393 			break;
394 	}
395 	if (editor) {
396 		char *editcmd;
397 
398 		fclose(efp);
399 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
400 		sprintf(editcmd, "%s %s", editor, editfile);
401 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
402 		INTON;
403 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
404 		unlink(editfile);
405 	}
406 
407 	if (lflg == 0 && active > 0)
408 		--active;
409 	if (displayhist)
410 		displayhist = 0;
411 	return 0;
412 }
413 
414 STATIC const char *
415 fc_replace(s, p, r)
416 	const char *s;
417 	char *p, *r;
418 {
419 	char *dest;
420 	int plen = strlen(p);
421 
422 	STARTSTACKSTR(dest);
423 	while (*s) {
424 		if (*s == *p && strncmp(s, p, plen) == 0) {
425 			while (*r)
426 				STPUTC(*r++, dest);
427 			s += plen;
428 			*p = '\0';	/* so no more matches */
429 		} else
430 			STPUTC(*s++, dest);
431 	}
432 	STACKSTRNUL(dest);
433 	dest = grabstackstr(dest);
434 
435 	return (dest);
436 }
437 
438 int
439 not_fcnumber(s)
440         char *s;
441 {
442 	if (s == NULL)
443 		return 0;
444         if (*s == '-')
445                 s++;
446 	return (!is_number(s));
447 }
448 
449 int
450 str_to_event(str, last)
451 	const char *str;
452 	int last;
453 {
454 	HistEvent he;
455 	const char *s = str;
456 	int relative = 0;
457 	int i, retval;
458 
459 	retval = history(hist, &he, H_FIRST);
460 	switch (*s) {
461 	case '-':
462 		relative = 1;
463 		/*FALLTHROUGH*/
464 	case '+':
465 		s++;
466 	}
467 	if (is_number(s)) {
468 		i = atoi(s);
469 		if (relative) {
470 			while (retval != -1 && i--) {
471 				retval = history(hist, &he, H_NEXT);
472 			}
473 			if (retval == -1)
474 				retval = history(hist, &he, H_LAST);
475 		} else {
476 			retval = history(hist, &he, H_NEXT_EVENT, i);
477 			if (retval == -1) {
478 				/*
479 				 * the notion of first and last is
480 				 * backwards to that of the history package
481 				 */
482 				retval = history(hist, &he,
483 						last ? H_FIRST : H_LAST);
484 			}
485 		}
486 		if (retval == -1)
487 			error("history number %s not found (internal error)",
488 			       str);
489 	} else {
490 		/*
491 		 * pattern
492 		 */
493 		retval = history(hist, &he, H_PREV_STR, str);
494 		if (retval == -1)
495 			error("history pattern not found: %s", str);
496 	}
497 	return (he.num);
498 }
499 #else
500 int
501 histcmd(argc, argv)
502 	int argc;
503 	char **argv;
504 {
505 	error("not compiled with history support");
506 	/* NOTREACHED */
507 }
508 #endif
509