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