xref: /dragonfly/bin/sh/histedit.c (revision 8ef0e968)
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.13.2.4 2002/08/27 01:36:28 tjr Exp $
38  * $DragonFly: src/bin/sh/histedit.c,v 1.7 2006/01/17 15:06:26 corecode Exp $
39  */
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;
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 	FILE *el_err;
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 				out2str("sh: can't initialize history\n");
97 		}
98 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
99 			/*
100 			 * turn editing on
101 			 */
102 			char *term, *shname;
103 
104 			INTOFF;
105 			if (el_in == NULL)
106 				el_in = fdopen(0, "r");
107 			if (el_out == NULL)
108 				el_out = fdopen(2, "w");
109 			if (el_in == NULL || el_out == NULL)
110 				goto bad;
111 			el_err = el_out;
112 			term = lookupvar("TERM");
113 			if (term) {
114 				if (setenv("TERM", term, 1) == -1)
115 					error("setenv: cannot set TERM=1");
116 			}
117 			else
118 				unsetenv("TERM");
119 			shname = arg0;
120 			if (shname[0] == '-')
121 				shname++;
122 			el = el_init(arg0, el_in, el_out, el_err);
123 			if (el != NULL) {
124 				if (hist)
125 					el_set(el, EL_HIST, history, hist);
126 				el_set(el, EL_PROMPT, getprompt);
127 			} else {
128 bad:
129 				out2str("sh: can't initialize editing\n");
130 			}
131 			INTON;
132 		} else if (!editing && el) {
133 			INTOFF;
134 			el_end(el);
135 			el = NULL;
136 			INTON;
137 		}
138 		if (el) {
139 			if (Vflag)
140 				el_set(el, EL_EDITOR, "vi");
141 			else if (Eflag)
142 				el_set(el, EL_EDITOR, "emacs");
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(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 /*
175  *  This command is provided since POSIX decided to standardize
176  *  the Korn shell fc command.  Oh well...
177  */
178 int
179 histcmd(int argc, char **argv)
180 {
181 	int ch;
182 	const char *editor = NULL;
183 	HistEvent he;
184 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
185 	int i, retval;
186 	const char *firststr, *laststr;
187 	int first, last, direction;
188 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
189 	static int active = 0;
190 	struct jmploc jmploc;
191 	struct jmploc *volatile savehandler;
192 	char editfile[PATH_MAX];
193 	FILE *efp;
194 #ifdef __GNUC__
195 	/* Avoid longjmp clobbering */
196 	(void) &editor;
197 	(void) &lflg;
198 	(void) &nflg;
199 	(void) &rflg;
200 	(void) &sflg;
201 	(void) &firststr;
202 	(void) &laststr;
203 	(void) &pat;
204 	(void) &repl;
205 	(void) &efp;
206 	(void) &argc;
207 	(void) &argv;
208 #endif
209 
210 	if (hist == NULL)
211 		error("history not active");
212 
213 	if (argc == 1)
214 		error("missing history argument");
215 
216 	optreset = 1; optind = 1; /* initialize getopt */
217 	opterr = 0;
218 	while (not_fcnumber(argv[optind]) &&
219 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
220 		switch ((char)ch) {
221 		case 'e':
222 			editor = optarg;
223 			break;
224 		case 'l':
225 			lflg = 1;
226 			break;
227 		case 'n':
228 			nflg = 1;
229 			break;
230 		case 'r':
231 			rflg = 1;
232 			break;
233 		case 's':
234 			sflg = 1;
235 			break;
236 		case ':':
237 			error("option -%c expects argument", optopt);
238 		case '?':
239 		default:
240 			error("unknown option: -%c", optopt);
241 		}
242 	argc -= optind, argv += optind;
243 
244 	/*
245 	 * If executing...
246 	 */
247 	if (lflg == 0 || editor || sflg) {
248 		lflg = 0;	/* ignore */
249 		editfile[0] = '\0';
250 		/*
251 		 * Catch interrupts to reset active counter and
252 		 * cleanup temp files.
253 		 */
254 		if (setjmp(jmploc.loc)) {
255 			active = 0;
256 			if (*editfile)
257 				unlink(editfile);
258 			handler = savehandler;
259 			longjmp(handler->loc, 1);
260 		}
261 		savehandler = handler;
262 		handler = &jmploc;
263 		if (++active > MAXHISTLOOPS) {
264 			active = 0;
265 			displayhist = 0;
266 			error("called recursively too many times");
267 		}
268 		/*
269 		 * Set editor.
270 		 */
271 		if (sflg == 0) {
272 			if (editor == NULL &&
273 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
274 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
275 				editor = DEFEDITOR;
276 			if (editor[0] == '-' && editor[1] == '\0') {
277 				sflg = 1;	/* no edit */
278 				editor = NULL;
279 			}
280 		}
281 	}
282 
283 	/*
284 	 * If executing, parse [old=new] now
285 	 */
286 	if (lflg == 0 && argc > 0 &&
287 	     ((repl = strchr(argv[0], '=')) != NULL)) {
288 		pat = argv[0];
289 		*repl++ = '\0';
290 		argc--, argv++;
291 	}
292 	/*
293 	 * determine [first] and [last]
294 	 */
295 	switch (argc) {
296 	case 0:
297 		firststr = lflg ? "-16" : "-1";
298 		laststr = "-1";
299 		break;
300 	case 1:
301 		firststr = argv[0];
302 		laststr = lflg ? "-1" : argv[0];
303 		break;
304 	case 2:
305 		firststr = argv[0];
306 		laststr = argv[1];
307 		break;
308 	default:
309 		error("too many args");
310 	}
311 	/*
312 	 * Turn into event numbers.
313 	 */
314 	first = str_to_event(firststr, 0);
315 	last = str_to_event(laststr, 1);
316 
317 	if (rflg) {
318 		i = last;
319 		last = first;
320 		first = i;
321 	}
322 	/*
323 	 * XXX - this should not depend on the event numbers
324 	 * always increasing.  Add sequence numbers or offset
325 	 * to the history element in next (diskbased) release.
326 	 */
327 	direction = first < last ? H_PREV : H_NEXT;
328 
329 	/*
330 	 * If editing, grab a temp file.
331 	 */
332 	if (editor) {
333 		int fd;
334 		INTOFF;		/* easier */
335 		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
336 		if ((fd = mkstemp(editfile)) < 0)
337 			error("can't create temporary file %s", editfile);
338 		if ((efp = fdopen(fd, "w")) == NULL) {
339 			close(fd);
340 			error("can't allocate stdio buffer for temp");
341 		}
342 	}
343 
344 	/*
345 	 * Loop through selected history events.  If listing or executing,
346 	 * do it now.  Otherwise, put into temp file and call the editor
347 	 * after.
348 	 *
349 	 * The history interface needs rethinking, as the following
350 	 * convolutions will demonstrate.
351 	 */
352 	history(hist, &he, H_FIRST);
353 	retval = history(hist, &he, H_NEXT_EVENT, first);
354 	for (;retval != -1; retval = history(hist, &he, direction)) {
355 		if (lflg) {
356 			if (!nflg)
357 				out1fmt("%5d ", he.num);
358 			out1str(he.str);
359 		} else {
360 			char *s = pat ?
361 			   fc_replace(he.str, pat, repl) : (char *)he.str;
362 
363 			if (sflg) {
364 				if (displayhist) {
365 					out2str(s);
366 				}
367 				evalstring(s);
368 				if (displayhist && hist) {
369 					/*
370 					 *  XXX what about recursive and
371 					 *  relative histnums.
372 					 */
373 					history(hist, &he, H_ENTER, s);
374 				}
375 			} else
376 				fputs(s, efp);
377 		}
378 		/*
379 		 * At end?  (if we were to loose 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);	/* 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(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 	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