xref: /netbsd-src/bin/sh/histedit.c (revision 76dfffe33547c37f8bdd446e3e4ab0f3c16cea4b)
1 /*	$NetBSD: histedit.c,v 1.10 1996/10/16 14:40:32 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 #ifndef lint
40 #if 0
41 static char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
42 #else
43 static char rcsid[] = "$NetBSD: histedit.c,v 1.10 1996/10/16 14:40:32 christos Exp $";
44 #endif
45 #endif /* not lint */
46 
47 #include <sys/param.h>
48 #include <paths.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <unistd.h>
52 /*
53  * Editline and history functions (and glue).
54  */
55 #include "shell.h"
56 #include "parser.h"
57 #include "var.h"
58 #include "options.h"
59 #include "main.h"
60 #include "output.h"
61 #include "mystring.h"
62 #ifndef NO_HISTORY
63 #include "myhistedit.h"
64 #endif
65 #include "error.h"
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 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);
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 
157 	if (hist != NULL) {
158 		if (hs == NULL || *hs == '\0' ||
159 		   (histsize = atoi(hs)) < 0)
160 			histsize = 100;
161 		history(hist, H_EVENT, histsize);
162 	}
163 }
164 
165 /*
166  *  This command is provided since POSIX decided to standardize
167  *  the Korn shell fc command.  Oh well...
168  */
169 int
170 histcmd(argc, argv)
171 	int argc;
172 	char **argv;
173 {
174 	extern char *optarg;
175 	extern int optind, optopt, optreset;
176 	int ch;
177 	char *editor = NULL;
178 	const HistEvent *he;
179 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
180 	int i;
181 	char *firststr, *laststr;
182 	int first, last, direction;
183 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
184 	static int active = 0;
185 	struct jmploc jmploc;
186 	struct jmploc *volatile savehandler;
187 	char editfile[MAXPATHLEN + 1];
188 	FILE *efp;
189 #ifdef __GNUC__
190 	/* Avoid longjmp clobbering */
191 	(void) &editor;
192 	(void) &lflg;
193 	(void) &nflg;
194 	(void) &rflg;
195 	(void) &sflg;
196 	(void) &firststr;
197 	(void) &laststr;
198 	(void) &pat;
199 	(void) &repl;
200 	(void) &efp;
201 	(void) &argc;
202 	(void) &argv;
203 #endif
204 
205 	if (hist == NULL)
206 		error("history not active");
207 
208 	if (argc == 1)
209 		error("missing history argument");
210 
211 	optreset = 1; optind = 1; /* initialize getopt */
212 	while (not_fcnumber(argv[optind]) &&
213 	      (ch = getopt(argc, argv, ":e:lnrs")) != EOF)
214 		switch ((char)ch) {
215 		case 'e':
216 			editor = optarg;
217 			break;
218 		case 'l':
219 			lflg = 1;
220 			break;
221 		case 'n':
222 			nflg = 1;
223 			break;
224 		case 'r':
225 			rflg = 1;
226 			break;
227 		case 's':
228 			sflg = 1;
229 			break;
230 		case ':':
231 			error("option -%c expects argument", optopt);
232 		case '?':
233 		default:
234 			error("unknown option: -%c", optopt);
235 		}
236 	argc -= optind, argv += optind;
237 
238 	/*
239 	 * If executing...
240 	 */
241 	if (lflg == 0 || editor || sflg) {
242 		lflg = 0;	/* ignore */
243 		editfile[0] = '\0';
244 		/*
245 		 * Catch interrupts to reset active counter and
246 		 * cleanup temp files.
247 		 */
248 		if (setjmp(jmploc.loc)) {
249 			active = 0;
250 			if (*editfile)
251 				unlink(editfile);
252 			handler = savehandler;
253 			longjmp(handler->loc, 1);
254 		}
255 		savehandler = handler;
256 		handler = &jmploc;
257 		if (++active > MAXHISTLOOPS) {
258 			active = 0;
259 			displayhist = 0;
260 			error("called recursively too many times");
261 		}
262 		/*
263 		 * Set editor.
264 		 */
265 		if (sflg == 0) {
266 			if (editor == NULL &&
267 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
268 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
269 				editor = DEFEDITOR;
270 			if (editor[0] == '-' && editor[1] == '\0') {
271 				sflg = 1;	/* no edit */
272 				editor = NULL;
273 			}
274 		}
275 	}
276 
277 	/*
278 	 * If executing, parse [old=new] now
279 	 */
280 	if (lflg == 0 && argc > 0 &&
281 	     ((repl = strchr(argv[0], '=')) != NULL)) {
282 		pat = argv[0];
283 		*repl++ = '\0';
284 		argc--, argv++;
285 	}
286 	/*
287 	 * determine [first] and [last]
288 	 */
289 	switch (argc) {
290 	case 0:
291 		firststr = lflg ? "-16" : "-1";
292 		laststr = "-1";
293 		break;
294 	case 1:
295 		firststr = argv[0];
296 		laststr = lflg ? "-1" : argv[0];
297 		break;
298 	case 2:
299 		firststr = argv[0];
300 		laststr = argv[1];
301 		break;
302 	default:
303 		error("too many args");
304 	}
305 	/*
306 	 * Turn into event numbers.
307 	 */
308 	first = str_to_event(firststr, 0);
309 	last = str_to_event(laststr, 1);
310 
311 	if (rflg) {
312 		i = last;
313 		last = first;
314 		first = i;
315 	}
316 	/*
317 	 * XXX - this should not depend on the event numbers
318 	 * always increasing.  Add sequence numbers or offset
319 	 * to the history element in next (diskbased) release.
320 	 */
321 	direction = first < last ? H_PREV : H_NEXT;
322 
323 	/*
324 	 * If editing, grab a temp file.
325 	 */
326 	if (editor) {
327 		int fd;
328 		INTOFF;		/* easier */
329 		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
330 		if ((fd = mkstemp(editfile)) < 0)
331 			error("can't create temporary file %s", editfile);
332 		if ((efp = fdopen(fd, "w")) == NULL) {
333 			close(fd);
334 			error("can't allocate stdio buffer for temp");
335 		}
336 	}
337 
338 	/*
339 	 * Loop through selected history events.  If listing or executing,
340 	 * do it now.  Otherwise, put into temp file and call the editor
341 	 * after.
342 	 *
343 	 * The history interface needs rethinking, as the following
344 	 * convolutions will demonstrate.
345 	 */
346 	history(hist, H_FIRST);
347 	he = history(hist, H_NEXT_EVENT, first);
348 	for (;he != NULL; he = history(hist, direction)) {
349 		if (lflg) {
350 			if (!nflg)
351 				out1fmt("%5d ", he->num);
352 			out1str(he->str);
353 		} else {
354 			char *s = pat ?
355 			   fc_replace(he->str, pat, repl) : (char *)he->str;
356 
357 			if (sflg) {
358 				if (displayhist) {
359 					out2str(s);
360 				}
361 				evalstring(s);
362 				if (displayhist && hist) {
363 					/*
364 					 *  XXX what about recursive and
365 					 *  relative histnums.
366 					 */
367 					history(hist, H_ENTER, s);
368 				}
369 			} else
370 				fputs(s, efp);
371 		}
372 		/*
373 		 * At end?  (if we were to loose last, we'd sure be
374 		 * messed up).
375 		 */
376 		if (he->num == last)
377 			break;
378 	}
379 	if (editor) {
380 		char *editcmd;
381 
382 		fclose(efp);
383 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
384 		sprintf(editcmd, "%s %s", editor, editfile);
385 		evalstring(editcmd);	/* XXX - should use no JC command */
386 		INTON;
387 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
388 		unlink(editfile);
389 	}
390 
391 	if (lflg == 0 && active > 0)
392 		--active;
393 	if (displayhist)
394 		displayhist = 0;
395 	return 0;
396 }
397 
398 STATIC char *
399 fc_replace(s, p, r)
400 	const char *s;
401 	char *p, *r;
402 {
403 	char *dest;
404 	int plen = strlen(p);
405 
406 	STARTSTACKSTR(dest);
407 	while (*s) {
408 		if (*s == *p && strncmp(s, p, plen) == 0) {
409 			while (*r)
410 				STPUTC(*r++, dest);
411 			s += plen;
412 			*p = '\0';	/* so no more matches */
413 		} else
414 			STPUTC(*s++, dest);
415 	}
416 	STACKSTRNUL(dest);
417 	dest = grabstackstr(dest);
418 
419 	return (dest);
420 }
421 
422 int
423 not_fcnumber(s)
424         char *s;
425 {
426 	if (s == NULL)
427 		return 0;
428         if (*s == '-')
429                 s++;
430 	return (!is_number(s));
431 }
432 
433 int
434 str_to_event(str, last)
435 	char *str;
436 	int last;
437 {
438 	const HistEvent *he;
439 	char *s = str;
440 	int relative = 0;
441 	int i;
442 
443 	he = history(hist, H_FIRST);
444 	switch (*s) {
445 	case '-':
446 		relative = 1;
447 		/*FALLTHROUGH*/
448 	case '+':
449 		s++;
450 	}
451 	if (is_number(s)) {
452 		i = atoi(s);
453 		if (relative) {
454 			while (he != NULL && i--) {
455 				he = history(hist, H_NEXT);
456 			}
457 			if (he == NULL)
458 				he = history(hist, H_LAST);
459 		} else {
460 			he = history(hist, H_NEXT_EVENT, i);
461 			if (he == NULL) {
462 				/*
463 				 * the notion of first and last is
464 				 * backwards to that of the history package
465 				 */
466 				he = history(hist, last ? H_FIRST : H_LAST);
467 			}
468 		}
469 		if (he == NULL)
470 			error("history number %s not found (internal error)",
471 			       str);
472 	} else {
473 		/*
474 		 * pattern
475 		 */
476 		he = history(hist, H_PREV_STR, str);
477 		if (he == NULL)
478 			error("history pattern not found: %s", str);
479 	}
480 	return (he->num);
481 }
482