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