xref: /freebsd/bin/sh/histedit.c (revision 36daf0495aa68d669ac6abf004940ec1b1e83e42)
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 #include "builtins.h"
63 
64 #define MAXHISTLOOPS	4	/* max recursions through fc */
65 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
66 
67 History *hist;	/* history cookie */
68 EditLine *el;	/* editline cookie */
69 int displayhist;
70 static FILE *el_in, *el_out, *el_err;
71 
72 static char *fc_replace(const char *, char *, char *);
73 
74 /*
75  * Set history and editing status.  Called whenever the status may
76  * have changed (figures out what to do).
77  */
78 void
79 histedit(void)
80 {
81 
82 #define editing (Eflag || Vflag)
83 
84 	if (iflag) {
85 		if (!hist) {
86 			/*
87 			 * turn history on
88 			 */
89 			INTOFF;
90 			hist = history_init();
91 			INTON;
92 
93 			if (hist != NULL)
94 				sethistsize(histsizeval());
95 			else
96 				out2fmt_flush("sh: can't initialize history\n");
97 		}
98 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
99 			/*
100 			 * turn editing on
101 			 */
102 			char *term;
103 
104 			INTOFF;
105 			if (el_in == NULL)
106 				el_in = fdopen(0, "r");
107 			if (el_err == NULL)
108 				el_err = fdopen(1, "w");
109 			if (el_out == NULL)
110 				el_out = fdopen(2, "w");
111 			if (el_in == NULL || el_err == NULL || el_out == NULL)
112 				goto bad;
113 			term = lookupvar("TERM");
114 			if (term)
115 				setenv("TERM", term, 1);
116 			else
117 				unsetenv("TERM");
118 			el = el_init(arg0, el_in, el_out, el_err);
119 			if (el != NULL) {
120 				if (hist)
121 					el_set(el, EL_HIST, history, hist);
122 				el_set(el, EL_PROMPT, getprompt);
123 				el_set(el, EL_ADDFN, "sh-complete",
124 				    "Filename completion",
125 				    _el_fn_sh_complete);
126 			} else {
127 bad:
128 				out2fmt_flush("sh: can't initialize editing\n");
129 			}
130 			INTON;
131 		} else if (!editing && el) {
132 			INTOFF;
133 			el_end(el);
134 			el = NULL;
135 			INTON;
136 		}
137 		if (el) {
138 			if (Vflag)
139 				el_set(el, EL_EDITOR, "vi");
140 			else if (Eflag)
141 				el_set(el, EL_EDITOR, "emacs");
142 			el_set(el, EL_BIND, "^I", "sh-complete", NULL);
143 			el_source(el, NULL);
144 		}
145 	} else {
146 		INTOFF;
147 		if (el) {	/* no editing if not interactive */
148 			el_end(el);
149 			el = NULL;
150 		}
151 		if (hist) {
152 			history_end(hist);
153 			hist = NULL;
154 		}
155 		INTON;
156 	}
157 }
158 
159 
160 void
161 sethistsize(hs)
162 	const char *hs;
163 {
164 	int histsize;
165 	HistEvent he;
166 
167 	if (hist != NULL) {
168 		if (hs == NULL || *hs == '\0' ||
169 		   (histsize = atoi(hs)) < 0)
170 			histsize = 100;
171 		history(hist, &he, H_SETSIZE, histsize);
172 		history(hist, &he, H_SETUNIQUE, 1);
173 	}
174 }
175 
176 void
177 setterm(const char *term)
178 {
179 	if (rootshell && el != NULL && term != NULL)
180 		el_set(el, EL_TERMINAL, term);
181 }
182 
183 int
184 histcmd(int argc, char **argv)
185 {
186 	int ch;
187 	const char *editor = NULL;
188 	HistEvent he;
189 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
190 	int i, retval;
191 	const char *firststr, *laststr;
192 	int first, last, direction;
193 	char *pat = NULL, *repl = NULL;
194 	static int active = 0;
195 	struct jmploc jmploc;
196 	struct jmploc *savehandler;
197 	char editfilestr[PATH_MAX];
198 	char *volatile editfile;
199 	FILE *efp = NULL;
200 	int oldhistnum;
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 	opterr = 0;
210 	while (not_fcnumber(argv[optind]) &&
211 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
212 		switch ((char)ch) {
213 		case 'e':
214 			editor = optarg;
215 			break;
216 		case 'l':
217 			lflg = 1;
218 			break;
219 		case 'n':
220 			nflg = 1;
221 			break;
222 		case 'r':
223 			rflg = 1;
224 			break;
225 		case 's':
226 			sflg = 1;
227 			break;
228 		case ':':
229 			error("option -%c expects argument", optopt);
230 		case '?':
231 		default:
232 			error("unknown option: -%c", optopt);
233 		}
234 	argc -= optind, argv += optind;
235 
236 	savehandler = handler;
237 	/*
238 	 * If executing...
239 	 */
240 	if (lflg == 0 || editor || sflg) {
241 		lflg = 0;	/* ignore */
242 		editfile = NULL;
243 		/*
244 		 * Catch interrupts to reset active counter and
245 		 * cleanup temp files.
246 		 */
247 		if (setjmp(jmploc.loc)) {
248 			active = 0;
249 			if (editfile)
250 				unlink(editfile);
251 			handler = savehandler;
252 			longjmp(handler->loc, 1);
253 		}
254 		handler = &jmploc;
255 		if (++active > MAXHISTLOOPS) {
256 			active = 0;
257 			displayhist = 0;
258 			error("called recursively too many times");
259 		}
260 		/*
261 		 * Set editor.
262 		 */
263 		if (sflg == 0) {
264 			if (editor == NULL &&
265 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
266 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
267 				editor = DEFEDITOR;
268 			if (editor[0] == '-' && editor[1] == '\0') {
269 				sflg = 1;	/* no edit */
270 				editor = NULL;
271 			}
272 		}
273 	}
274 
275 	/*
276 	 * If executing, parse [old=new] now
277 	 */
278 	if (lflg == 0 && argc > 0 &&
279 	     ((repl = strchr(argv[0], '=')) != NULL)) {
280 		pat = argv[0];
281 		*repl++ = '\0';
282 		argc--, argv++;
283 	}
284 	/*
285 	 * determine [first] and [last]
286 	 */
287 	switch (argc) {
288 	case 0:
289 		firststr = lflg ? "-16" : "-1";
290 		laststr = "-1";
291 		break;
292 	case 1:
293 		firststr = argv[0];
294 		laststr = lflg ? "-1" : argv[0];
295 		break;
296 	case 2:
297 		firststr = argv[0];
298 		laststr = argv[1];
299 		break;
300 	default:
301 		error("too many arguments");
302 	}
303 	/*
304 	 * Turn into event numbers.
305 	 */
306 	first = str_to_event(firststr, 0);
307 	last = str_to_event(laststr, 1);
308 
309 	if (rflg) {
310 		i = last;
311 		last = first;
312 		first = i;
313 	}
314 	/*
315 	 * XXX - this should not depend on the event numbers
316 	 * always increasing.  Add sequence numbers or offset
317 	 * to the history element in next (diskbased) release.
318 	 */
319 	direction = first < last ? H_PREV : H_NEXT;
320 
321 	/*
322 	 * If editing, grab a temp file.
323 	 */
324 	if (editor) {
325 		int fd;
326 		INTOFF;		/* easier */
327 		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
328 		if ((fd = mkstemp(editfilestr)) < 0)
329 			error("can't create temporary file %s", editfile);
330 		editfile = editfilestr;
331 		if ((efp = fdopen(fd, "w")) == NULL) {
332 			close(fd);
333 			error("Out of space");
334 		}
335 	}
336 
337 	/*
338 	 * Loop through selected history events.  If listing or executing,
339 	 * do it now.  Otherwise, put into temp file and call the editor
340 	 * after.
341 	 *
342 	 * The history interface needs rethinking, as the following
343 	 * convolutions will demonstrate.
344 	 */
345 	history(hist, &he, H_FIRST);
346 	retval = history(hist, &he, H_NEXT_EVENT, first);
347 	for (;retval != -1; retval = history(hist, &he, direction)) {
348 		if (lflg) {
349 			if (!nflg)
350 				out1fmt("%5d ", he.num);
351 			out1str(he.str);
352 		} else {
353 			char *s = pat ?
354 			   fc_replace(he.str, pat, repl) : (char *)he.str;
355 
356 			if (sflg) {
357 				if (displayhist) {
358 					out2str(s);
359 					flushout(out2);
360 				}
361 				evalstring(s, 0);
362 				if (displayhist && hist) {
363 					/*
364 					 *  XXX what about recursive and
365 					 *  relative histnums.
366 					 */
367 					oldhistnum = he.num;
368 					history(hist, &he, H_ENTER, s);
369 					/*
370 					 * XXX H_ENTER moves the internal
371 					 * cursor, set it back to the current
372 					 * entry.
373 					 */
374 					retval = history(hist, &he,
375 					    H_NEXT_EVENT, oldhistnum);
376 				}
377 			} else
378 				fputs(s, efp);
379 		}
380 		/*
381 		 * At end?  (if we were to lose last, we'd sure be
382 		 * messed up).
383 		 */
384 		if (he.num == last)
385 			break;
386 	}
387 	if (editor) {
388 		char *editcmd;
389 
390 		fclose(efp);
391 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
392 		sprintf(editcmd, "%s %s", editor, editfile);
393 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
394 		INTON;
395 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
396 		unlink(editfile);
397 	}
398 
399 	if (lflg == 0 && active > 0)
400 		--active;
401 	if (displayhist)
402 		displayhist = 0;
403 	handler = savehandler;
404 	return 0;
405 }
406 
407 static char *
408 fc_replace(const char *s, char *p, char *r)
409 {
410 	char *dest;
411 	int plen = strlen(p);
412 
413 	STARTSTACKSTR(dest);
414 	while (*s) {
415 		if (*s == *p && strncmp(s, p, plen) == 0) {
416 			STPUTS(r, dest);
417 			s += plen;
418 			*p = '\0';	/* so no more matches */
419 		} else
420 			STPUTC(*s++, dest);
421 	}
422 	STPUTC('\0', dest);
423 	dest = grabstackstr(dest);
424 
425 	return (dest);
426 }
427 
428 int
429 not_fcnumber(const char *s)
430 {
431 	if (s == NULL)
432 		return (0);
433 	if (*s == '-')
434 		s++;
435 	return (!is_number(s));
436 }
437 
438 int
439 str_to_event(const char *str, int last)
440 {
441 	HistEvent he;
442 	const char *s = str;
443 	int relative = 0;
444 	int i, retval;
445 
446 	retval = history(hist, &he, H_FIRST);
447 	switch (*s) {
448 	case '-':
449 		relative = 1;
450 		/*FALLTHROUGH*/
451 	case '+':
452 		s++;
453 	}
454 	if (is_number(s)) {
455 		i = atoi(s);
456 		if (relative) {
457 			while (retval != -1 && i--) {
458 				retval = history(hist, &he, H_NEXT);
459 			}
460 			if (retval == -1)
461 				retval = history(hist, &he, H_LAST);
462 		} else {
463 			retval = history(hist, &he, H_NEXT_EVENT, i);
464 			if (retval == -1) {
465 				/*
466 				 * the notion of first and last is
467 				 * backwards to that of the history package
468 				 */
469 				retval = history(hist, &he, last ? H_FIRST : H_LAST);
470 			}
471 		}
472 		if (retval == -1)
473 			error("history number %s not found (internal error)",
474 			       str);
475 	} else {
476 		/*
477 		 * pattern
478 		 */
479 		retval = history(hist, &he, H_PREV_STR, str);
480 		if (retval == -1)
481 			error("history pattern not found: %s", str);
482 	}
483 	return (he.num);
484 }
485 
486 int
487 bindcmd(int argc, char **argv)
488 {
489 
490 	if (el == NULL)
491 		error("line editing is disabled");
492 	return (el_parse(el, argc, (const char **)argv));
493 }
494 
495 #else
496 #include "error.h"
497 
498 int
499 histcmd(int argc, char **argv)
500 {
501 
502 	error("not compiled with history support");
503 	/*NOTREACHED*/
504 	return (0);
505 }
506 
507 int
508 bindcmd(int argc, char **argv)
509 {
510 
511 	error("not compiled with line editing support");
512 	return (0);
513 }
514 #endif
515