xref: /freebsd/bin/sh/histedit.c (revision eacee0ff7ec955b32e09515246bd97b6edcd2b0f)
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 <limits.h>
47 #include <paths.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 /*
52  * Editline and history functions (and glue).
53  */
54 #include "shell.h"
55 #include "parser.h"
56 #include "var.h"
57 #include "options.h"
58 #include "main.h"
59 #include "output.h"
60 #include "mystring.h"
61 #ifndef NO_HISTORY
62 #include "myhistedit.h"
63 #include "error.h"
64 #include "eval.h"
65 #include "memalloc.h"
66 
67 #define MAXHISTLOOPS	4	/* max recursions through fc */
68 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
69 
70 History *hist;	/* history cookie */
71 EditLine *el;	/* editline cookie */
72 int displayhist;
73 static FILE *el_in, *el_out, *el_err;
74 
75 STATIC char *fc_replace(const char *, char *, char *);
76 
77 /*
78  * Set history and editing status.  Called whenever the status may
79  * have changed (figures out what to do).
80  */
81 void
82 histedit(void)
83 {
84 
85 #define editing (Eflag || Vflag)
86 
87 	if (iflag) {
88 		if (!hist) {
89 			/*
90 			 * turn history on
91 			 */
92 			INTOFF;
93 			hist = history_init();
94 			INTON;
95 
96 			if (hist != NULL)
97 				sethistsize(histsizeval());
98 			else
99 				out2str("sh: can't initialize history\n");
100 		}
101 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
102 			/*
103 			 * turn editing on
104 			 */
105 			INTOFF;
106 			if (el_in == NULL)
107 				el_in = fdopen(0, "r");
108 			if (el_err == NULL)
109 				el_err = fdopen(1, "w");
110 			if (el_out == NULL)
111 				el_out = fdopen(2, "w");
112 			if (el_in == NULL || el_err == NULL || el_out == NULL)
113 				goto bad;
114 			el = el_init(arg0, el_in, el_out, el_err);
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_EVENT, histsize);
163 	}
164 }
165 
166 /*
167  *  This command is provided since POSIX decided to standardize
168  *  the Korn shell fc command.  Oh well...
169  */
170 int
171 histcmd(int argc, char **argv)
172 {
173 	int ch;
174 	char *editor = NULL;
175 	HistEvent he;
176 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
177 	int i, retval;
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[PATH_MAX];
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 = shoptarg;
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, &he, H_FIRST);
344 	retval = history(hist, &he, H_NEXT_EVENT, first);
345 	for (;retval != -1; retval = history(hist, &he, 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, &he, 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(const char *s, char *p, char *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(char *s)
419 {
420 	if (s == NULL)
421 		return (0);
422 	if (*s == '-')
423 		s++;
424 	return (!is_number(s));
425 }
426 
427 int
428 str_to_event(char *str, int last)
429 {
430 	HistEvent he;
431 	char *s = str;
432 	int relative = 0;
433 	int i, retval;
434 
435 	retval = history(hist, &he, H_FIRST);
436 	switch (*s) {
437 	case '-':
438 		relative = 1;
439 		/*FALLTHROUGH*/
440 	case '+':
441 		s++;
442 	}
443 	if (is_number(s)) {
444 		i = atoi(s);
445 		if (relative) {
446 			while (retval != -1 && i--) {
447 				retval = history(hist, &he, H_NEXT);
448 			}
449 			if (retval == -1)
450 				retval = history(hist, &he, H_LAST);
451 		} else {
452 			retval = history(hist, &he, H_NEXT_EVENT, i);
453 			if (retval == -1) {
454 				/*
455 				 * the notion of first and last is
456 				 * backwards to that of the history package
457 				 */
458 				retval = history(hist, &he, last ? H_FIRST : H_LAST);
459 			}
460 		}
461 		if (retval == -1)
462 			error("history number %s not found (internal error)",
463 			       str);
464 	} else {
465 		/*
466 		 * pattern
467 		 */
468 		retval = history(hist, &he, H_PREV_STR, str);
469 		if (retval == -1)
470 			error("history pattern not found: %s", str);
471 	}
472 	return (he.num);
473 }
474 #else
475 #include "error.h"
476 
477 int
478 histcmd(int argc, char **argv)
479 {
480 
481 	error("not compiled with history support");
482 	/*NOTREACHED*/
483 	return (0);
484 }
485 #endif
486