xref: /freebsd/bin/sh/histedit.c (revision a8445737e740901f5f2c8d24c12ef7fc8b00134e)
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 	"$Id$";
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 	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")) != -1)
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 		return (0);
425 	if (*s == '-')
426 		s++;
427 	return (!is_number(s));
428 }
429 
430 int
431 str_to_event(str, last)
432 	char *str;
433 	int last;
434 {
435 	const HistEvent *he;
436 	char *s = str;
437 	int relative = 0;
438 	int i;
439 
440 	he = history(hist, H_FIRST);
441 	switch (*s) {
442 	case '-':
443 		relative = 1;
444 		/*FALLTHROUGH*/
445 	case '+':
446 		s++;
447 	}
448 	if (is_number(s)) {
449 		i = atoi(s);
450 		if (relative) {
451 			while (he != NULL && i--) {
452 				he = history(hist, H_NEXT);
453 			}
454 			if (he == NULL)
455 				he = history(hist, H_LAST);
456 		} else {
457 			he = history(hist, H_NEXT_EVENT, i);
458 			if (he == NULL) {
459 				/*
460 				 * the notion of first and last is
461 				 * backwards to that of the history package
462 				 */
463 				he = history(hist, last ? H_FIRST : H_LAST);
464 			}
465 		}
466 		if (he == NULL)
467 			error("history number %s not found (internal error)",
468 			       str);
469 	} else {
470 		/*
471 		 * pattern
472 		 */
473 		he = history(hist, H_PREV_STR, str);
474 		if (he == NULL)
475 			error("history pattern not found: %s", str);
476 	}
477 	return (he->num);
478 }
479 #else
480 #include "error.h"
481 
482 int
483 histcmd(argc, argv)
484 	int argc;
485 	char **argv;
486 {
487 
488 	error("not compiled with history support");
489 	/*NOTREACHED*/
490 	return (0);
491 }
492 #endif
493