xref: /dragonfly/bin/sh/histedit.c (revision 62f7f702)
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.29 2006/08/04 07:56:31 yar Exp $
38  * $DragonFly: src/bin/sh/histedit.c,v 1.12 2008/02/13 15:13:37 matthias 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, *el_err;
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 
81 #define editing (Eflag || Vflag)
82 
83 	if (iflag) {
84 		if (!hist) {
85 			/*
86 			 * turn history on
87 			 */
88 			INTOFF;
89 			hist = history_init();
90 			INTON;
91 
92 			if (hist != NULL)
93 				sethistsize(histsizeval());
94 			else
95 				out2str("sh: can't initialize history\n");
96 		}
97 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
98 			/*
99 			 * turn editing on
100 			 */
101 			char *term, *shname;
102 
103 			INTOFF;
104 			if (el_in == NULL)
105 				el_in = fdopen(0, "r");
106 			if (el_err == NULL)
107 				el_err = fdopen(1, "w");
108 			if (el_out == NULL)
109 				el_out = fdopen(2, "w");
110 			if (el_in == NULL || el_err == NULL || el_out == NULL)
111 				goto bad;
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 		history(hist, &he, H_SETUNIQUE, 1);
172 	}
173 }
174 
175 int
176 histcmd(int argc, char **argv)
177 {
178 	int ch;
179 	const char *volatile editor = NULL;
180 	HistEvent he;
181 	volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
182 	int i, retval;
183 	const char *firststr = NULL, *laststr = NULL;
184 	int first, last, direction;
185 	char *pat = NULL, *repl = NULL;
186 	static int active = 0;
187 	struct jmploc jmploc;
188 	struct jmploc *volatile savehandler;
189 	char editfile[PATH_MAX];
190 	FILE *efp = NULL;
191 	int oldhistnum;
192 
193 	if (hist == NULL)
194 		error("history not active");
195 
196 	if (argc == 1)
197 		error("missing history argument");
198 
199 	optreset = 1; optind = 1; /* initialize getopt */
200 	opterr = 0;
201 	while (not_fcnumber(argv[optind]) &&
202 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
203 		switch ((char)ch) {
204 		case 'e':
205 			editor = optarg;
206 			break;
207 		case 'l':
208 			lflg = 1;
209 			break;
210 		case 'n':
211 			nflg = 1;
212 			break;
213 		case 'r':
214 			rflg = 1;
215 			break;
216 		case 's':
217 			sflg = 1;
218 			break;
219 		case ':':
220 			error("option -%c expects argument", optopt);
221 		case '?':
222 		default:
223 			error("unknown option: -%c", optopt);
224 		}
225 	argc -= optind, argv += optind;
226 
227 	/*
228 	 * If executing...
229 	 */
230 	if (lflg == 0 || editor || sflg) {
231 		lflg = 0;	/* ignore */
232 		editfile[0] = '\0';
233 		/*
234 		 * Catch interrupts to reset active counter and
235 		 * cleanup temp files.
236 		 */
237 		if (setjmp(jmploc.loc)) {
238 			active = 0;
239 			if (*editfile)
240 				unlink(editfile);
241 			handler = savehandler;
242 			longjmp(handler->loc, 1);
243 		}
244 		savehandler = handler;
245 		handler = &jmploc;
246 		if (++active > MAXHISTLOOPS) {
247 			active = 0;
248 			displayhist = 0;
249 			error("called recursively too many times");
250 		}
251 		/*
252 		 * Set editor.
253 		 */
254 		if (sflg == 0) {
255 			if (editor == NULL &&
256 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
257 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
258 				editor = DEFEDITOR;
259 			if (editor[0] == '-' && editor[1] == '\0') {
260 				sflg = 1;	/* no edit */
261 				editor = NULL;
262 			}
263 		}
264 	}
265 
266 	/*
267 	 * If executing, parse [old=new] now
268 	 */
269 	if (lflg == 0 && argc > 0 &&
270 	     ((repl = strchr(argv[0], '=')) != NULL)) {
271 		pat = argv[0];
272 		*repl++ = '\0';
273 		argc--, argv++;
274 	}
275 	/*
276 	 * determine [first] and [last]
277 	 */
278 	switch (argc) {
279 	case 0:
280 		firststr = lflg ? "-16" : "-1";
281 		laststr = "-1";
282 		break;
283 	case 1:
284 		firststr = argv[0];
285 		laststr = lflg ? "-1" : argv[0];
286 		break;
287 	case 2:
288 		firststr = argv[0];
289 		laststr = argv[1];
290 		break;
291 	default:
292 		error("too many args");
293 	}
294 	/*
295 	 * Turn into event numbers.
296 	 */
297 	first = str_to_event(firststr, 0);
298 	last = str_to_event(laststr, 1);
299 
300 	if (rflg) {
301 		i = last;
302 		last = first;
303 		first = i;
304 	}
305 	/*
306 	 * XXX - this should not depend on the event numbers
307 	 * always increasing.  Add sequence numbers or offset
308 	 * to the history element in next (diskbased) release.
309 	 */
310 	direction = first < last ? H_PREV : H_NEXT;
311 
312 	/*
313 	 * If editing, grab a temp file.
314 	 */
315 	if (editor) {
316 		int fd;
317 		INTOFF;		/* easier */
318 		sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
319 		if ((fd = mkstemp(editfile)) < 0)
320 			error("can't create temporary file %s", editfile);
321 		if ((efp = fdopen(fd, "w")) == NULL) {
322 			close(fd);
323 			error("can't allocate stdio buffer for temp");
324 		}
325 	}
326 
327 	/*
328 	 * Loop through selected history events.  If listing or executing,
329 	 * do it now.  Otherwise, put into temp file and call the editor
330 	 * after.
331 	 *
332 	 * The history interface needs rethinking, as the following
333 	 * convolutions will demonstrate.
334 	 */
335 	history(hist, &he, H_FIRST);
336 	retval = history(hist, &he, H_NEXT_EVENT, first);
337 	for (;retval != -1; retval = history(hist, &he, direction)) {
338 		if (lflg) {
339 			if (!nflg)
340 				out1fmt("%5d ", he.num);
341 			out1str(he.str);
342 		} else {
343 			const char *s = pat ?
344 			   fc_replace(he.str, pat, repl) : he.str;
345 
346 			if (sflg) {
347 				if (displayhist) {
348 					out2str(s);
349 				}
350 				evalstring(strcpy(stalloc(strlen(s) + 1), s));
351 				if (displayhist && hist) {
352 					/*
353 					 *  XXX what about recursive and
354 					 *  relative histnums.
355 					 */
356 					oldhistnum = he.num;
357 					history(hist, &he, H_ENTER, s);
358 					/*
359 					 * XXX H_ENTER moves the internal
360 					 * cursor, set it back to the current
361 					 * entry.
362 					 */
363 					retval = history(hist, &he,
364 					    H_NEXT_EVENT, oldhistnum);
365 				}
366 			} else
367 				fputs(s, efp);
368 		}
369 		/*
370 		 * At end?  (if we were to lose last, we'd sure be
371 		 * messed up).
372 		 */
373 		if (he.num == last)
374 			break;
375 	}
376 	if (editor) {
377 		char *editcmd;
378 
379 		fclose(efp);
380 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
381 		sprintf(editcmd, "%s %s", editor, editfile);
382 		evalstring(editcmd);	/* XXX - should use no JC command */
383 		INTON;
384 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
385 		unlink(editfile);
386 	}
387 
388 	if (lflg == 0 && active > 0)
389 		--active;
390 	if (displayhist)
391 		displayhist = 0;
392 	return 0;
393 }
394 
395 STATIC char *
396 fc_replace(const char *s, char *p, char *r)
397 {
398 	char *dest;
399 	int plen = strlen(p);
400 
401 	STARTSTACKSTR(dest);
402 	while (*s) {
403 		if (*s == *p && strncmp(s, p, plen) == 0) {
404 			while (*r)
405 				STPUTC(*r++, dest);
406 			s += plen;
407 			*p = '\0';	/* so no more matches */
408 		} else
409 			STPUTC(*s++, dest);
410 	}
411 	STACKSTRNUL(dest);
412 	dest = grabstackstr(dest);
413 
414 	return (dest);
415 }
416 
417 int
418 not_fcnumber(char *s)
419 {
420 	if (s == NULL)
421 		return (0);
422 	if (*s == '-')
423 		s++;
424 	return (!is_number(s));
425 }
426 
427 int
428 str_to_event(const char *str, int last)
429 {
430 	HistEvent he;
431 	const char *s = str;
432 	int relative = 0;
433 	int i, retval;
434 
435 	retval = history(hist, &he, H_FIRST);
436 	switch (*s) {
437 	case '-':
438 		relative = 1;
439 		/*FALLTHROUGH*/
440 	case '+':
441 		s++;
442 	}
443 	if (is_number(s)) {
444 		i = atoi(s);
445 		if (relative) {
446 			while (retval != -1 && i--) {
447 				retval = history(hist, &he, H_NEXT);
448 			}
449 			if (retval == -1)
450 				retval = history(hist, &he, H_LAST);
451 		} else {
452 			retval = history(hist, &he, H_NEXT_EVENT, i);
453 			if (retval == -1) {
454 				/*
455 				 * the notion of first and last is
456 				 * backwards to that of the history package
457 				 */
458 				retval = history(hist, &he, last ? H_FIRST : H_LAST);
459 			}
460 		}
461 		if (retval == -1)
462 			error("history number %s not found (internal error)",
463 			       str);
464 	} else {
465 		/*
466 		 * pattern
467 		 */
468 		retval = history(hist, &he, H_PREV_STR, str);
469 		if (retval == -1)
470 			error("history pattern not found: %s", str);
471 	}
472 	return (he.num);
473 }
474 
475 int
476 bindcmd(int argc, char **argv)
477 {
478 
479 	if (el == NULL)
480 		error("line editing is disabled");
481 	return (el_parse(el, argc, (const char **)argv));
482 }
483 
484 #else
485 #include "error.h"
486 
487 int
488 histcmd(int argc, char **argv)
489 {
490 
491 	error("not compiled with history support");
492 	/*NOTREACHED*/
493 	return (0);
494 }
495 
496 int
497 bindcmd(int argc, char **argv)
498 {
499 
500 	error("not compiled with line editing support");
501 	return (0);
502 }
503 #endif
504