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