xref: /netbsd/bin/sh/histedit.c (revision c4a72b64)
1 /*	$NetBSD: histedit.c,v 1.27 2002/11/24 22:35:40 christos 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.27 2002/11/24 22:35:40 christos 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(const char *, char *, char *);
78 
79 #ifdef DEBUG
80 extern FILE *tracefile;
81 #endif
82 
83 /*
84  * Set history and editing status.  Called whenever the status may
85  * have changed (figures out what to do).
86  */
87 void
88 histedit(void)
89 {
90 	FILE *el_err;
91 
92 #define editing (Eflag || Vflag)
93 
94 	if (iflag) {
95 		if (!hist) {
96 			/*
97 			 * turn history on
98 			 */
99 			INTOFF;
100 			hist = history_init();
101 			INTON;
102 
103 			if (hist != NULL)
104 				sethistsize(histsizeval());
105 			else
106 				out2str("sh: can't initialize history\n");
107 		}
108 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
109 			/*
110 			 * turn editing on
111 			 */
112 			INTOFF;
113 			if (el_in == NULL)
114 				el_in = fdopen(0, "r");
115 			if (el_out == NULL)
116 				el_out = fdopen(2, "w");
117 			if (el_in == NULL || el_out == NULL)
118 				goto bad;
119 			el_err = el_out;
120 #if DEBUG
121 			if (tracefile)
122 				el_err = tracefile;
123 #endif
124 			el = el_init(arg0, el_in, el_out, el_err);
125 			if (el != NULL) {
126 				if (hist)
127 					el_set(el, EL_HIST, history, hist);
128 				el_set(el, EL_PROMPT, getprompt);
129 			} else {
130 bad:
131 				out2str("sh: can't initialize editing\n");
132 			}
133 			INTON;
134 		} else if (!editing && el) {
135 			INTOFF;
136 			el_end(el);
137 			el = NULL;
138 			INTON;
139 		}
140 		if (el) {
141 			if (Vflag)
142 				el_set(el, EL_EDITOR, "vi");
143 			else if (Eflag)
144 				el_set(el, EL_EDITOR, "emacs");
145 			el_source(el, NULL);
146 		}
147 	} else {
148 		INTOFF;
149 		if (el) {	/* no editing if not interactive */
150 			el_end(el);
151 			el = NULL;
152 		}
153 		if (hist) {
154 			history_end(hist);
155 			hist = NULL;
156 		}
157 		INTON;
158 	}
159 }
160 
161 
162 void
163 sethistsize(const char *hs)
164 {
165 	int histsize;
166 	HistEvent he;
167 
168 	if (hist != NULL) {
169 		if (hs == NULL || *hs == '\0' ||
170 		   (histsize = atoi(hs)) < 0)
171 			histsize = 100;
172 		history(hist, &he, H_SETSIZE, histsize);
173 	}
174 }
175 
176 void
177 setterm(const char *term)
178 {
179 	if (el != NULL && term != NULL)
180 		if (el_set(el, EL_TERMINAL, term) != 0) {
181 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
182 			outfmt(out2, "sh: Using dumb terminal settings.\n");
183 		}
184 }
185 
186 /*
187  *  This command is provided since POSIX decided to standardize
188  *  the Korn shell fc command.  Oh well...
189  */
190 int
191 histcmd(int argc, char **argv)
192 {
193 	int ch;
194 	const char *editor = NULL;
195 	HistEvent he;
196 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
197 	int i, retval;
198 	const char *firststr, *laststr;
199 	int first, last, direction;
200 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
201 	static int active = 0;
202 	struct jmploc jmploc;
203 	struct jmploc *volatile savehandler;
204 	char editfile[MAXPATHLEN + 1];
205 	FILE *efp;
206 #ifdef __GNUC__
207 	/* Avoid longjmp clobbering */
208 	(void) &editor;
209 	(void) &lflg;
210 	(void) &nflg;
211 	(void) &rflg;
212 	(void) &sflg;
213 	(void) &firststr;
214 	(void) &laststr;
215 	(void) &pat;
216 	(void) &repl;
217 	(void) &efp;
218 	(void) &argc;
219 	(void) &argv;
220 #endif
221 
222 	if (hist == NULL)
223 		error("history not active");
224 
225 	if (argc == 1)
226 		error("missing history argument");
227 
228 	optreset = 1; optind = 1; /* initialize getopt */
229 	while (not_fcnumber(argv[optind]) &&
230 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
231 		switch ((char)ch) {
232 		case 'e':
233 			editor = optionarg;
234 			break;
235 		case 'l':
236 			lflg = 1;
237 			break;
238 		case 'n':
239 			nflg = 1;
240 			break;
241 		case 'r':
242 			rflg = 1;
243 			break;
244 		case 's':
245 			sflg = 1;
246 			break;
247 		case ':':
248 			error("option -%c expects argument", optopt);
249 			/* NOTREACHED */
250 		case '?':
251 		default:
252 			error("unknown option: -%c", optopt);
253 			/* NOTREACHED */
254 		}
255 	argc -= optind, argv += optind;
256 
257 	/*
258 	 * If executing...
259 	 */
260 	if (lflg == 0 || editor || sflg) {
261 		lflg = 0;	/* ignore */
262 		editfile[0] = '\0';
263 		/*
264 		 * Catch interrupts to reset active counter and
265 		 * cleanup temp files.
266 		 */
267 		if (setjmp(jmploc.loc)) {
268 			active = 0;
269 			if (*editfile)
270 				unlink(editfile);
271 			handler = savehandler;
272 			longjmp(handler->loc, 1);
273 		}
274 		savehandler = handler;
275 		handler = &jmploc;
276 		if (++active > MAXHISTLOOPS) {
277 			active = 0;
278 			displayhist = 0;
279 			error("called recursively too many times");
280 		}
281 		/*
282 		 * Set editor.
283 		 */
284 		if (sflg == 0) {
285 			if (editor == NULL &&
286 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
287 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
288 				editor = DEFEDITOR;
289 			if (editor[0] == '-' && editor[1] == '\0') {
290 				sflg = 1;	/* no edit */
291 				editor = NULL;
292 			}
293 		}
294 	}
295 
296 	/*
297 	 * If executing, parse [old=new] now
298 	 */
299 	if (lflg == 0 && argc > 0 &&
300 	     ((repl = strchr(argv[0], '=')) != NULL)) {
301 		pat = argv[0];
302 		*repl++ = '\0';
303 		argc--, argv++;
304 	}
305 	/*
306 	 * determine [first] and [last]
307 	 */
308 	switch (argc) {
309 	case 0:
310 		firststr = lflg ? "-16" : "-1";
311 		laststr = "-1";
312 		break;
313 	case 1:
314 		firststr = argv[0];
315 		laststr = lflg ? "-1" : argv[0];
316 		break;
317 	case 2:
318 		firststr = argv[0];
319 		laststr = argv[1];
320 		break;
321 	default:
322 		error("too many args");
323 		/* NOTREACHED */
324 	}
325 	/*
326 	 * Turn into event numbers.
327 	 */
328 	first = str_to_event(firststr, 0);
329 	last = str_to_event(laststr, 1);
330 
331 	if (rflg) {
332 		i = last;
333 		last = first;
334 		first = i;
335 	}
336 	/*
337 	 * XXX - this should not depend on the event numbers
338 	 * always increasing.  Add sequence numbers or offset
339 	 * to the history element in next (diskbased) release.
340 	 */
341 	direction = first < last ? H_PREV : H_NEXT;
342 
343 	/*
344 	 * If editing, grab a temp file.
345 	 */
346 	if (editor) {
347 		int fd;
348 		INTOFF;		/* easier */
349 		sprintf(editfile, "%s_shXXXXXX", _PATH_TMP);
350 		if ((fd = mkstemp(editfile)) < 0)
351 			error("can't create temporary file %s", editfile);
352 		if ((efp = fdopen(fd, "w")) == NULL) {
353 			close(fd);
354 			error("can't allocate stdio buffer for temp");
355 		}
356 	}
357 
358 	/*
359 	 * Loop through selected history events.  If listing or executing,
360 	 * do it now.  Otherwise, put into temp file and call the editor
361 	 * after.
362 	 *
363 	 * The history interface needs rethinking, as the following
364 	 * convolutions will demonstrate.
365 	 */
366 	history(hist, &he, H_FIRST);
367 	retval = history(hist, &he, H_NEXT_EVENT, first);
368 	for (;retval != -1; retval = history(hist, &he, direction)) {
369 		if (lflg) {
370 			if (!nflg)
371 				out1fmt("%5d ", he.num);
372 			out1str(he.str);
373 		} else {
374 			const char *s = pat ?
375 			   fc_replace(he.str, pat, repl) : he.str;
376 
377 			if (sflg) {
378 				if (displayhist) {
379 					out2str(s);
380 				}
381 
382 				evalstring(strcpy(stalloc(strlen(s) + 1), s), 0);
383 				if (displayhist && hist) {
384 					/*
385 					 *  XXX what about recursive and
386 					 *  relative histnums.
387 					 */
388 					history(hist, &he, H_ENTER, s);
389 				}
390 			} else
391 				fputs(s, efp);
392 		}
393 		/*
394 		 * At end?  (if we were to lose last, we'd sure be
395 		 * messed up).
396 		 */
397 		if (he.num == last)
398 			break;
399 	}
400 	if (editor) {
401 		char *editcmd;
402 
403 		fclose(efp);
404 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
405 		sprintf(editcmd, "%s %s", editor, editfile);
406 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
407 		INTON;
408 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
409 		unlink(editfile);
410 	}
411 
412 	if (lflg == 0 && active > 0)
413 		--active;
414 	if (displayhist)
415 		displayhist = 0;
416 	return 0;
417 }
418 
419 STATIC const char *
420 fc_replace(const char *s, char *p, char *r)
421 {
422 	char *dest;
423 	int plen = strlen(p);
424 
425 	STARTSTACKSTR(dest);
426 	while (*s) {
427 		if (*s == *p && strncmp(s, p, plen) == 0) {
428 			while (*r)
429 				STPUTC(*r++, dest);
430 			s += plen;
431 			*p = '\0';	/* so no more matches */
432 		} else
433 			STPUTC(*s++, dest);
434 	}
435 	STACKSTRNUL(dest);
436 	dest = grabstackstr(dest);
437 
438 	return (dest);
439 }
440 
441 int
442 not_fcnumber(char *s)
443 {
444 	if (s == NULL)
445 		return 0;
446         if (*s == '-')
447                 s++;
448 	return (!is_number(s));
449 }
450 
451 int
452 str_to_event(const char *str, 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(int argc, char **argv)
502 {
503 	error("not compiled with history support");
504 	/* NOTREACHED */
505 }
506 #endif
507