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