xref: /dflybsd-src/bin/sh/histedit.c (revision 8469d7829843cc19cace403765eff3d234e987a1)
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  * @(#)histedit.c	8.2 (Berkeley) 5/4/95
37  * $FreeBSD: src/bin/sh/histedit.c,v 1.42 2010/12/29 19:39:51 jilles Exp $
38  */
39 
40 #include <sys/param.h>
41 #include <limits.h>
42 #include <paths.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 /*
47  * Editline and history functions (and glue).
48  */
49 #include "shell.h"
50 #include "parser.h"
51 #include "var.h"
52 #include "options.h"
53 #include "main.h"
54 #include "output.h"
55 #include "mystring.h"
56 #include "myhistedit.h"
57 #ifndef NO_HISTORY
58 #include "error.h"
59 #include "eval.h"
60 #include "memalloc.h"
61 
62 #define MAXHISTLOOPS	4	/* max recursions through fc */
63 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
64 
65 History *hist;	/* history cookie */
66 EditLine *el;	/* editline cookie */
67 int displayhist;
68 static FILE *el_in, *el_out, *el_err;
69 
70 static char *fc_replace(const char *, char *, char *);
71 
72 /*
73  * Set history and editing status.  Called whenever the status may
74  * have changed (figures out what to do).
75  */
76 void
77 histedit(void)
78 {
79 
80 #define editing (Eflag || Vflag)
81 
82 	if (iflag) {
83 		if (!hist) {
84 			/*
85 			 * turn history on
86 			 */
87 			INTOFF;
88 			hist = history_init();
89 			INTON;
90 
91 			if (hist != NULL)
92 				sethistsize(histsizeval());
93 			else
94 				out2fmt_flush("sh: can't initialize history\n");
95 		}
96 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
97 			/*
98 			 * turn editing on
99 			 */
100 			char *term;
101 
102 			INTOFF;
103 			if (el_in == NULL)
104 				el_in = fdopen(0, "r");
105 			if (el_err == NULL)
106 				el_err = fdopen(1, "w");
107 			if (el_out == NULL)
108 				el_out = fdopen(2, "w");
109 			if (el_in == NULL || el_err == NULL || el_out == NULL)
110 				goto bad;
111 			term = lookupvar("TERM");
112 			if (term) {
113 				if (setenv("TERM", term, 1) == -1)
114 					error("setenv: cannot set TERM=1");
115 			}
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, "rl-complete",
124 				    "ReadLine compatible completion function",
125 				    _el_fn_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",
143 			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
144 			el_source(el, NULL);
145 		}
146 	} else {
147 		INTOFF;
148 		if (el) {	/* no editing if not interactive */
149 			el_end(el);
150 			el = NULL;
151 		}
152 		if (hist) {
153 			history_end(hist);
154 			hist = NULL;
155 		}
156 		INTON;
157 	}
158 }
159 
160 
161 void
162 sethistsize(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 *volatile editor = NULL;
188 	HistEvent he;
189 	volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
190 	int i, retval;
191 	const char *firststr = NULL, *laststr = NULL;
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) :
355 			   __DECONST(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 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 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 __unused, char **argv __unused)
501 {
502 
503 	error("not compiled with history support");
504 	/*NOTREACHED*/
505 	return (0);
506 }
507 
508 int
509 bindcmd(int argc __unused, char **argv __unused)
510 {
511 
512 	error("not compiled with line editing support");
513 	return (0);
514 }
515 #endif
516