xref: /netbsd-src/bin/sh/histedit.c (revision ae9172d6cd9432a6a1a56760d86b32c57a66c39c)
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 
37 #ifndef lint
38 /*static char sccsid[] = "from: @(#)histedit.c	8.1 (Berkeley) 5/31/93";*/
39 static char *rcsid = "$Id: histedit.c,v 1.5 1994/12/05 19:07:42 cgd Exp $";
40 #endif /* not lint */
41 
42 /*
43  * Editline and history functions (and glue).
44  */
45 #include <sys/param.h>
46 #include <paths.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <unistd.h>
50 #include "shell.h"
51 #include "parser.h"
52 #include "var.h"
53 #include "options.h"
54 #include "output.h"
55 #include "mystring.h"
56 #include "error.h"
57 #include "eval.h"
58 #include "histedit.h"
59 #include "memalloc.h"
60 #include "extern.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;
69 
70 STATIC char *fc_replace __P((const char *, char *, char *));
71 int not_fcnumber __P((char *));
72 int str_to_event __P((char *, int));
73 
74 /*
75  * Set history and editing status.  Called whenever the status may
76  * have changed (figures out what to do).
77  */
78 void
79 histedit()
80 {
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();
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 			INTOFF;
103 			if (el_in == NULL)
104 				el_in = fdopen(0, "r");
105 			if (el_out == NULL)
106 				el_out = fdopen(2, "w");
107 			if (el_in == NULL || el_out == NULL)
108 				goto bad;
109 			el = el_init(arg0, el_in, el_out);
110 			if (el != NULL) {
111 				if (hist)
112 					el_set(el, EL_HIST, history, hist);
113 				el_set(el, EL_PROMPT, getprompt);
114 			} else {
115 bad:
116 				out2str("sh: can't initialize editing\n");
117 			}
118 			INTON;
119 		} else if (!editing && el) {
120 			INTOFF;
121 			el_end(el);
122 			el = NULL;
123 			INTON;
124 		}
125 		if (el) {
126 			if (Vflag)
127 				el_set(el, EL_EDITOR, "vi");
128 			else if (Eflag)
129 				el_set(el, EL_EDITOR, "emacs");
130 		}
131 	} else {
132 		INTOFF;
133 		if (el) {	/* no editing if not interactive */
134 			el_end(el);
135 			el = NULL;
136 		}
137 		if (hist) {
138 			history_end(hist);
139 			hist = NULL;
140 		}
141 		INTON;
142 	}
143 }
144 
145 
146 void
147 sethistsize() {
148 	char *cp;
149 	int histsize;
150 
151 	if (hist != NULL) {
152 		cp = lookupvar("HISTSIZE");
153 		if (cp == NULL || *cp == '\0' ||
154 		   (histsize = atoi(cp)) < 0)
155 			histsize = 100;
156 		history(hist, H_EVENT, histsize);
157 	}
158 }
159 
160 /*
161  *  This command is provided since POSIX decided to standardize
162  *  the Korn shell fc command.  Oh well...
163  */
164 int
165 histcmd(argc, argv)
166 	int argc;
167 	char *argv[];
168 {
169 	extern char *optarg;
170 	extern int optind, optopt, optreset;
171 	int ch;
172 	char *editor = NULL;
173 	const HistEvent *he;
174 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
175 	int i;
176 	char *firststr, *laststr;
177 	int first, last, direction;
178 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
179 	static int active = 0;
180 	struct jmploc jmploc;
181 	struct jmploc *volatile savehandler;
182 	char editfile[MAXPATHLEN + 1];
183 	FILE *efp;
184 
185 	if (hist == NULL)
186 		error("history not active");
187 
188 	if (argc == 1)
189 		error("missing history argument");
190 
191 	optreset = 1; optind = 1; /* initialize getopt */
192 	while (not_fcnumber(argv[optind]) &&
193 	      (ch = getopt(argc, argv, ":e:lnrs")) != EOF)
194 		switch ((char)ch) {
195 		case 'e':
196 			editor = optarg;
197 			break;
198 		case 'l':
199 			lflg = 1;
200 			break;
201 		case 'n':
202 			nflg = 1;
203 			break;
204 		case 'r':
205 			rflg = 1;
206 			break;
207 		case 's':
208 			sflg = 1;
209 			break;
210 		case ':':
211 			error("option -%c expects argument", optopt);
212 		case '?':
213 		default:
214 			error("unknown option: -%c", optopt);
215 		}
216 	argc -= optind, argv += optind;
217 
218 	/*
219 	 * If executing...
220 	 */
221 	if (lflg == 0 || editor || sflg) {
222 		lflg = 0;	/* ignore */
223 		editfile[0] = '\0';
224 		/*
225 		 * Catch interrupts to reset active counter and
226 		 * cleanup temp files.
227 		 */
228 		if (setjmp(jmploc.loc)) {
229 			active = 0;
230 			if (*editfile)
231 				unlink(editfile);
232 			handler = savehandler;
233 			longjmp(handler->loc, 1);
234 		}
235 		savehandler = handler;
236 		handler = &jmploc;
237 		if (++active > MAXHISTLOOPS) {
238 			active = 0;
239 			displayhist = 0;
240 			error("called recursively too many times");
241 		}
242 		/*
243 		 * Set editor.
244 		 */
245 		if (sflg == 0) {
246 			if (editor == NULL &&
247 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
248 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
249 				editor = DEFEDITOR;
250 			if (editor[0] == '-' && editor[1] == '\0') {
251 				sflg = 1;	/* no edit */
252 				editor = NULL;
253 			}
254 		}
255 	}
256 
257 	/*
258 	 * If executing, parse [old=new] now
259 	 */
260 	if (lflg == 0 && argc > 0 &&
261 	     ((repl = strchr(argv[0], '=')) != NULL)) {
262 		pat = argv[0];
263 		*repl++ = '\0';
264 		argc--, argv++;
265 	}
266 	/*
267 	 * determine [first] and [last]
268 	 */
269 	switch (argc) {
270 	case 0:
271 		firststr = lflg ? "-16" : "-1";
272 		laststr = "-1";
273 		break;
274 	case 1:
275 		firststr = argv[0];
276 		laststr = lflg ? "-1" : argv[0];
277 		break;
278 	case 2:
279 		firststr = argv[0];
280 		laststr = argv[1];
281 		break;
282 	default:
283 		error("too many args");
284 	}
285 	/*
286 	 * Turn into event numbers.
287 	 */
288 	first = str_to_event(firststr, 0);
289 	last = str_to_event(laststr, 1);
290 
291 	if (rflg) {
292 		i = last;
293 		last = first;
294 		first = i;
295 	}
296 	/*
297 	 * XXX - this should not depend on the event numbers
298 	 * always increasing.  Add sequence numbers or offset
299 	 * to the history element in next (diskbased) release.
300 	 */
301 	direction = first < last ? H_PREV : H_NEXT;
302 
303 	/*
304 	 * If editing, grab a temp file.
305 	 */
306 	if (editor) {
307 		int fd;
308 		INTOFF;		/* easier */
309 		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
310 		if ((fd = mkstemp(editfile)) < 0)
311 			error("can't create temporary file %s", editfile);
312 		if ((efp = fdopen(fd, "w")) == NULL) {
313 			close(fd);
314 			error("can't allocate stdio buffer for temp\n");
315 		}
316 	}
317 
318 	/*
319 	 * Loop through selected history events.  If listing or executing,
320 	 * do it now.  Otherwise, put into temp file and call the editor
321 	 * after.
322 	 *
323 	 * The history interface needs rethinking, as the following
324 	 * convolutions will demonstrate.
325 	 */
326 	history(hist, H_FIRST);
327 	he = history(hist, H_NEXT_EVENT, first);
328 	for (;he != NULL; he = history(hist, direction)) {
329 		if (lflg) {
330 			if (!nflg)
331 				out1fmt("%5d ", he->num);
332 			out1str(he->str);
333 		} else {
334 			char *s = pat ?
335 			   fc_replace(he->str, pat, repl) : (char *)he->str;
336 
337 			if (sflg) {
338 				if (displayhist) {
339 					out2str(s);
340 				}
341 				evalstring(s);
342 				if (displayhist && hist) {
343 					/*
344 					 *  XXX what about recursive and
345 					 *  relative histnums.
346 					 */
347 					history(hist, H_ENTER, s);
348 				}
349 			} else
350 				fputs(s, efp);
351 		}
352 		/*
353 		 * At end?  (if we were to loose last, we'd sure be
354 		 * messed up).
355 		 */
356 		if (he->num == last)
357 			break;
358 	}
359 	if (editor) {
360 		char *editcmd;
361 
362 		fclose(efp);
363 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
364 		sprintf(editcmd, "%s %s", editor, editfile);
365 		evalstring(editcmd);	/* XXX - should use no JC command */
366 		INTON;
367 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
368 		unlink(editfile);
369 	}
370 
371 	if (lflg == 0 && active > 0)
372 		--active;
373 	if (displayhist)
374 		displayhist = 0;
375 }
376 
377 STATIC char *
378 fc_replace(s, p, r)
379 	const char *s;
380 	char *p, *r;
381 {
382 	char *dest;
383 	int plen = strlen(p);
384 
385 	STARTSTACKSTR(dest);
386 	while (*s) {
387 		if (*s == *p && strncmp(s, p, plen) == 0) {
388 			while (*r)
389 				STPUTC(*r++, dest);
390 			s += plen;
391 			*p = '\0';	/* so no more matches */
392 		} else
393 			STPUTC(*s++, dest);
394 	}
395 	STACKSTRNUL(dest);
396 	dest = grabstackstr(dest);
397 
398 	return (dest);
399 }
400 
401 int
402 not_fcnumber(s)
403         char *s;
404 {
405         if (*s == '-')
406                 s++;
407 	return (!is_number(s));
408 }
409 
410 int
411 str_to_event(str, last)
412 	char *str;
413 	int last;
414 {
415 	const HistEvent *he;
416 	char *s = str;
417 	int relative = 0;
418 	int i;
419 
420 	he = history(hist, H_FIRST);
421 	switch (*s) {
422 	case '-':
423 		relative = 1;
424 		/*FALLTHROUGH*/
425 	case '+':
426 		s++;
427 	}
428 	if (is_number(s)) {
429 		i = atoi(s);
430 		if (relative) {
431 			while (he != NULL && i--) {
432 				he = history(hist, H_NEXT);
433 			}
434 			if (he == NULL)
435 				he = history(hist, H_LAST);
436 		} else {
437 			he = history(hist, H_NEXT_EVENT, i);
438 			if (he == NULL) {
439 				/*
440 				 * the notion of first and last is
441 				 * backwards to that of the history package
442 				 */
443 				he = history(hist, last ? H_FIRST : H_LAST);
444 			}
445 		}
446 		if (he == NULL)
447 			error("history number %s not found (internal error)",
448 			       str);
449 	} else {
450 		/*
451 		 * pattern
452 		 */
453 		he = history(hist, H_PREV_STR, str);
454 		if (he == NULL)
455 			error("history pattern not found: %s", str);
456 	}
457 	return (he->num);
458 }
459