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