xref: /freebsd/bin/sh/histedit.c (revision 952d112864d8008aa87278a30a539d888a8493cd)
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  *	$Id: histedit.c,v 1.9 1997/02/22 13:58:27 peter Exp $
37  */
38 
39 #ifndef lint
40 static char const sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
41 #endif /* not lint */
42 
43 #include <sys/param.h>
44 #include <paths.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <unistd.h>
48 /*
49  * Editline and history functions (and glue).
50  */
51 #include "shell.h"
52 #include "parser.h"
53 #include "var.h"
54 #include "options.h"
55 #include "main.h"
56 #include "output.h"
57 #include "mystring.h"
58 #ifndef NO_HISTORY
59 #include "myhistedit.h"
60 #endif
61 #include "error.h"
62 #include "eval.h"
63 #include "memalloc.h"
64 
65 #define MAXHISTLOOPS	4	/* max recursions through fc */
66 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
67 
68 History *hist;	/* history cookie */
69 EditLine *el;	/* editline cookie */
70 int displayhist;
71 static FILE *el_in, *el_out;
72 
73 STATIC char *fc_replace __P((const char *, char *, char *));
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()
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 				out2str("sh: can't initialize history\n");
98 		}
99 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
100 			/*
101 			 * turn editing on
102 			 */
103 			INTOFF;
104 			if (el_in == NULL)
105 				el_in = fdopen(0, "r");
106 			if (el_out == NULL)
107 				el_out = fdopen(2, "w");
108 			if (el_in == NULL || el_out == NULL)
109 				goto bad;
110 			el = el_init(arg0, el_in, el_out);
111 			if (el != NULL) {
112 				if (hist)
113 					el_set(el, EL_HIST, history, hist);
114 				el_set(el, EL_PROMPT, getprompt);
115 			} else {
116 bad:
117 				out2str("sh: can't initialize editing\n");
118 			}
119 			INTON;
120 		} else if (!editing && el) {
121 			INTOFF;
122 			el_end(el);
123 			el = NULL;
124 			INTON;
125 		}
126 		if (el) {
127 			if (Vflag)
128 				el_set(el, EL_EDITOR, "vi");
129 			else if (Eflag)
130 				el_set(el, EL_EDITOR, "emacs");
131 		}
132 	} else {
133 		INTOFF;
134 		if (el) {	/* no editing if not interactive */
135 			el_end(el);
136 			el = NULL;
137 		}
138 		if (hist) {
139 			history_end(hist);
140 			hist = NULL;
141 		}
142 		INTON;
143 	}
144 }
145 
146 
147 void
148 sethistsize(hs)
149 	const char *hs;
150 {
151 	int histsize;
152 
153 	if (hist != NULL) {
154 		if (hs == NULL || *hs == '\0' ||
155 		   (histsize = atoi(hs)) < 0)
156 			histsize = 100;
157 		history(hist, H_EVENT, histsize);
158 	}
159 }
160 
161 /*
162  *  This command is provided since POSIX decided to standardize
163  *  the Korn shell fc command.  Oh well...
164  */
165 int
166 histcmd(argc, argv)
167 	int argc;
168 	char **argv;
169 {
170 	extern char *optarg;
171 	extern int optind, optopt, optreset;
172 	int ch;
173 	char *editor = NULL;
174 	const HistEvent *he;
175 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
176 	int i;
177 	char *firststr, *laststr;
178 	int first, last, direction;
179 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
180 	static int active = 0;
181 	struct jmploc jmploc;
182 	struct jmploc *volatile savehandler;
183 	char editfile[MAXPATHLEN + 1];
184 	FILE *efp;
185 #ifdef __GNUC__
186 	/* Avoid longjmp clobbering */
187 	(void) &editor;
188 	(void) &lflg;
189 	(void) &nflg;
190 	(void) &rflg;
191 	(void) &sflg;
192 	(void) &firststr;
193 	(void) &laststr;
194 	(void) &pat;
195 	(void) &repl;
196 	(void) &efp;
197 	(void) &argc;
198 	(void) &argv;
199 #endif
200 
201 	if (hist == NULL)
202 		error("history not active");
203 
204 	if (argc == 1)
205 		error("missing history argument");
206 
207 	optreset = 1; optind = 1; /* initialize getopt */
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[0] = '\0';
240 		/*
241 		 * Catch interrupts to reset active counter and
242 		 * cleanup temp files.
243 		 */
244 		if (setjmp(jmploc.loc)) {
245 			active = 0;
246 			if (*editfile)
247 				unlink(editfile);
248 			handler = savehandler;
249 			longjmp(handler->loc, 1);
250 		}
251 		savehandler = handler;
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(editfile, "%s/_shXXXXXX", _PATH_TMP);
326 		if ((fd = mkstemp(editfile)) < 0)
327 			error("can't create temporary file %s", editfile);
328 		if ((efp = fdopen(fd, "w")) == NULL) {
329 			close(fd);
330 			error("can't allocate stdio buffer for temp");
331 		}
332 	}
333 
334 	/*
335 	 * Loop through selected history events.  If listing or executing,
336 	 * do it now.  Otherwise, put into temp file and call the editor
337 	 * after.
338 	 *
339 	 * The history interface needs rethinking, as the following
340 	 * convolutions will demonstrate.
341 	 */
342 	history(hist, H_FIRST);
343 	he = history(hist, H_NEXT_EVENT, first);
344 	for (;he != NULL; he = history(hist, direction)) {
345 		if (lflg) {
346 			if (!nflg)
347 				out1fmt("%5d ", he->num);
348 			out1str(he->str);
349 		} else {
350 			char *s = pat ?
351 			   fc_replace(he->str, pat, repl) : (char *)he->str;
352 
353 			if (sflg) {
354 				if (displayhist) {
355 					out2str(s);
356 				}
357 				evalstring(s);
358 				if (displayhist && hist) {
359 					/*
360 					 *  XXX what about recursive and
361 					 *  relative histnums.
362 					 */
363 					history(hist, H_ENTER, s);
364 				}
365 			} else
366 				fputs(s, efp);
367 		}
368 		/*
369 		 * At end?  (if we were to loose last, we'd sure be
370 		 * messed up).
371 		 */
372 		if (he->num == last)
373 			break;
374 	}
375 	if (editor) {
376 		char *editcmd;
377 
378 		fclose(efp);
379 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
380 		sprintf(editcmd, "%s %s", editor, editfile);
381 		evalstring(editcmd);	/* XXX - should use no JC command */
382 		INTON;
383 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
384 		unlink(editfile);
385 	}
386 
387 	if (lflg == 0 && active > 0)
388 		--active;
389 	if (displayhist)
390 		displayhist = 0;
391 	return 0;
392 }
393 
394 STATIC char *
395 fc_replace(s, p, r)
396 	const char *s;
397 	char *p, *r;
398 {
399 	char *dest;
400 	int plen = strlen(p);
401 
402 	STARTSTACKSTR(dest);
403 	while (*s) {
404 		if (*s == *p && strncmp(s, p, plen) == 0) {
405 			while (*r)
406 				STPUTC(*r++, dest);
407 			s += plen;
408 			*p = '\0';	/* so no more matches */
409 		} else
410 			STPUTC(*s++, dest);
411 	}
412 	STACKSTRNUL(dest);
413 	dest = grabstackstr(dest);
414 
415 	return (dest);
416 }
417 
418 int
419 not_fcnumber(s)
420 	char *s;
421 {
422 	if (s == NULL)
423 		return (1);
424 	if (*s == '-')
425 		s++;
426 	return (!is_number(s));
427 }
428 
429 int
430 str_to_event(str, last)
431 	char *str;
432 	int last;
433 {
434 	const HistEvent *he;
435 	char *s = str;
436 	int relative = 0;
437 	int i;
438 
439 	he = history(hist, H_FIRST);
440 	switch (*s) {
441 	case '-':
442 		relative = 1;
443 		/*FALLTHROUGH*/
444 	case '+':
445 		s++;
446 	}
447 	if (is_number(s)) {
448 		i = atoi(s);
449 		if (relative) {
450 			while (he != NULL && i--) {
451 				he = history(hist, H_NEXT);
452 			}
453 			if (he == NULL)
454 				he = history(hist, H_LAST);
455 		} else {
456 			he = history(hist, H_NEXT_EVENT, i);
457 			if (he == NULL) {
458 				/*
459 				 * the notion of first and last is
460 				 * backwards to that of the history package
461 				 */
462 				he = history(hist, last ? H_FIRST : H_LAST);
463 			}
464 		}
465 		if (he == NULL)
466 			error("history number %s not found (internal error)",
467 			       str);
468 	} else {
469 		/*
470 		 * pattern
471 		 */
472 		he = history(hist, H_PREV_STR, str);
473 		if (he == NULL)
474 			error("history pattern not found: %s", str);
475 	}
476 	return (he->num);
477 }
478