xref: /dragonfly/bin/sh/histedit.c (revision 335b9e93)
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. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
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 #endif
60 #include "error.h"
61 #include "eval.h"
62 #include "memalloc.h"
63 #include "builtins.h"
64 
65 #ifndef NO_HISTORY
66 
67 #define MAXHISTLOOPS	4	/* max recursions through fc */
68 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
69 
70 History *hist;	/* history cookie */
71 EditLine *el;	/* editline cookie */
72 int displayhist;
73 static FILE *el_in, *el_out, *el_err;
74 
75 static char *fc_replace(const char *, char *, char *);
76 static int not_fcnumber(const char *);
77 static int str_to_event(const char *, int);
78 
79 /*
80  * Set history and editing status.  Called whenever the status may
81  * have changed (figures out what to do).
82  */
83 void
84 histedit(void)
85 {
86 
87 #define editing (Eflag || Vflag)
88 
89 	if (iflag) {
90 		if (!hist) {
91 			/*
92 			 * turn history on
93 			 */
94 			INTOFF;
95 			hist = history_init();
96 			INTON;
97 
98 			if (hist != NULL)
99 				sethistsize(histsizeval());
100 			else
101 				out2fmt_flush("sh: can't initialize history\n");
102 		}
103 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
104 			/*
105 			 * turn editing on
106 			 */
107 			char *term;
108 
109 			INTOFF;
110 			if (el_in == NULL)
111 				el_in = fdopen(0, "r");
112 			if (el_err == NULL)
113 				el_err = fdopen(1, "w");
114 			if (el_out == NULL)
115 				el_out = fdopen(2, "w");
116 			if (el_in == NULL || el_err == NULL || el_out == NULL)
117 				goto bad;
118 			term = lookupvar("TERM");
119 			if (term)
120 				setenv("TERM", term, 1);
121 			else
122 				unsetenv("TERM");
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, "sh-complete",
129 				    "Filename completion",
130 				    _el_fn_complete);
131 			} else {
132 bad:
133 				out2fmt_flush("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", "sh-complete", NULL);
148 			el_source(el, NULL);
149 		}
150 	} else {
151 		INTOFF;
152 		if (el) {	/* no editing if not interactive */
153 			el_end(el);
154 			el = NULL;
155 		}
156 		if (hist) {
157 			history_end(hist);
158 			hist = NULL;
159 		}
160 		INTON;
161 	}
162 }
163 
164 
165 void
166 sethistsize(const char *hs)
167 {
168 	int histsize;
169 	HistEvent he;
170 
171 	if (hist != NULL) {
172 		if (hs == NULL || !is_number(hs))
173 			histsize = 100;
174 		else
175 			histsize = atoi(hs);
176 		history(hist, &he, H_SETSIZE, histsize);
177 		history(hist, &he, H_SETUNIQUE, 1);
178 	}
179 }
180 
181 void
182 setterm(const char *term)
183 {
184 	if (rootshell && el != NULL && term != NULL)
185 		el_set(el, EL_TERMINAL, term);
186 }
187 
188 int
189 histcmd(int argc, char **argv __unused)
190 {
191 	int ch;
192 	const char *editor = NULL;
193 	HistEvent he;
194 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
195 	int i, retval;
196 	const char *firststr, *laststr;
197 	int first, last, direction;
198 	char *pat = NULL, *repl = NULL;
199 	static int active = 0;
200 	struct jmploc jmploc;
201 	struct jmploc *savehandler;
202 	char editfilestr[PATH_MAX];
203 	char *volatile editfile;
204 	FILE *efp = NULL;
205 	int oldhistnum;
206 
207 	if (hist == NULL)
208 		error("history not active");
209 
210 	if (argc == 1)
211 		error("missing history argument");
212 
213 	while (not_fcnumber(*argptr) && (ch = nextopt("e:lnrs")) != '\0')
214 		switch ((char)ch) {
215 		case 'e':
216 			editor = shoptarg;
217 			break;
218 		case 'l':
219 			lflg = 1;
220 			break;
221 		case 'n':
222 			nflg = 1;
223 			break;
224 		case 'r':
225 			rflg = 1;
226 			break;
227 		case 's':
228 			sflg = 1;
229 			break;
230 		}
231 
232 	savehandler = handler;
233 	/*
234 	 * If executing...
235 	 */
236 	if (lflg == 0 || editor || sflg) {
237 		lflg = 0;	/* ignore */
238 		editfile = NULL;
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 		handler = &jmploc;
251 		if (++active > MAXHISTLOOPS) {
252 			active = 0;
253 			displayhist = 0;
254 			error("called recursively too many times");
255 		}
256 		/*
257 		 * Set editor.
258 		 */
259 		if (sflg == 0) {
260 			if (editor == NULL &&
261 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
262 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
263 				editor = DEFEDITOR;
264 			if (editor[0] == '-' && editor[1] == '\0') {
265 				sflg = 1;	/* no edit */
266 				editor = NULL;
267 			}
268 		}
269 	}
270 
271 	/*
272 	 * If executing, parse [old=new] now
273 	 */
274 	if (lflg == 0 && *argptr != NULL &&
275 	     ((repl = strchr(*argptr, '=')) != NULL)) {
276 		pat = *argptr;
277 		*repl++ = '\0';
278 		argptr++;
279 	}
280 	/*
281 	 * determine [first] and [last]
282 	 */
283 	if (*argptr == NULL) {
284 		firststr = lflg ? "-16" : "-1";
285 		laststr = "-1";
286 	} else if (argptr[1] == NULL) {
287 		firststr = argptr[0];
288 		laststr = lflg ? "-1" : argptr[0];
289 	} else if (argptr[2] == NULL) {
290 		firststr = argptr[0];
291 		laststr = argptr[1];
292 	} else
293 		error("too many arguments");
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(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
319 		if ((fd = mkstemp(editfilestr)) < 0)
320 			error("can't create temporary file %s", editfile);
321 		editfile = editfilestr;
322 		if ((efp = fdopen(fd, "w")) == NULL) {
323 			close(fd);
324 			error("Out of space");
325 		}
326 	}
327 
328 	/*
329 	 * Loop through selected history events.  If listing or executing,
330 	 * do it now.  Otherwise, put into temp file and call the editor
331 	 * after.
332 	 *
333 	 * The history interface needs rethinking, as the following
334 	 * convolutions will demonstrate.
335 	 */
336 	history(hist, &he, H_FIRST);
337 	retval = history(hist, &he, H_NEXT_EVENT, first);
338 	for (;retval != -1; retval = history(hist, &he, direction)) {
339 		if (lflg) {
340 			if (!nflg)
341 				out1fmt("%5d ", he.num);
342 			out1str(he.str);
343 		} else {
344 			const char *s = pat ?
345 			   fc_replace(he.str, pat, repl) : he.str;
346 
347 			if (sflg) {
348 				if (displayhist) {
349 					out2str(s);
350 					flushout(out2);
351 				}
352 				evalstring(s, 0);
353 				if (displayhist && hist) {
354 					/*
355 					 *  XXX what about recursive and
356 					 *  relative histnums.
357 					 */
358 					oldhistnum = he.num;
359 					history(hist, &he, H_ENTER, s);
360 					/*
361 					 * XXX H_ENTER moves the internal
362 					 * cursor, set it back to the current
363 					 * entry.
364 					 */
365 					retval = history(hist, &he,
366 					    H_NEXT_EVENT, oldhistnum);
367 				}
368 			} else
369 				fputs(s, efp);
370 		}
371 		/*
372 		 * At end?  (if we were to lose last, we'd sure be
373 		 * messed up).
374 		 */
375 		if (he.num == last)
376 			break;
377 	}
378 	if (editor) {
379 		char *editcmd;
380 
381 		fclose(efp);
382 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
383 		sprintf(editcmd, "%s %s", editor, editfile);
384 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
385 		INTON;
386 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
387 		unlink(editfile);
388 	}
389 
390 	if (lflg == 0 && active > 0)
391 		--active;
392 	if (displayhist)
393 		displayhist = 0;
394 	handler = savehandler;
395 	return 0;
396 }
397 
398 static char *
399 fc_replace(const char *s, char *p, char *r)
400 {
401 	char *dest;
402 	int plen = strlen(p);
403 
404 	STARTSTACKSTR(dest);
405 	while (*s) {
406 		if (*s == *p && strncmp(s, p, plen) == 0) {
407 			STPUTS(r, dest);
408 			s += plen;
409 			*p = '\0';	/* so no more matches */
410 		} else
411 			STPUTC(*s++, dest);
412 	}
413 	STPUTC('\0', dest);
414 	dest = grabstackstr(dest);
415 
416 	return (dest);
417 }
418 
419 static int
420 not_fcnumber(const char *s)
421 {
422 	if (s == NULL)
423 		return (0);
424 	if (*s == '-')
425 		s++;
426 	return (!is_number(s));
427 }
428 
429 static int
430 str_to_event(const char *str, int last)
431 {
432 	HistEvent he;
433 	const char *s = str;
434 	int relative = 0;
435 	int i, retval;
436 
437 	retval = history(hist, &he, H_FIRST);
438 	switch (*s) {
439 	case '-':
440 		relative = 1;
441 		/*FALLTHROUGH*/
442 	case '+':
443 		s++;
444 	}
445 	if (is_number(s)) {
446 		i = atoi(s);
447 		if (relative) {
448 			while (retval != -1 && i--) {
449 				retval = history(hist, &he, H_NEXT);
450 			}
451 			if (retval == -1)
452 				retval = history(hist, &he, H_LAST);
453 		} else {
454 			retval = history(hist, &he, H_NEXT_EVENT, i);
455 			if (retval == -1) {
456 				/*
457 				 * the notion of first and last is
458 				 * backwards to that of the history package
459 				 */
460 				retval = history(hist, &he, last ? H_FIRST : H_LAST);
461 			}
462 		}
463 		if (retval == -1)
464 			error("history number %s not found (internal error)",
465 			       str);
466 	} else {
467 		/*
468 		 * pattern
469 		 */
470 		retval = history(hist, &he, H_PREV_STR, str);
471 		if (retval == -1)
472 			error("history pattern not found: %s", str);
473 	}
474 	return (he.num);
475 }
476 
477 int
478 bindcmd(int argc, char **argv)
479 {
480 
481 	if (el == NULL)
482 		error("line editing is disabled");
483 	return (el_parse(el, argc, __DECONST(const char **, argv)));
484 }
485 
486 #else
487 
488 int
489 histcmd(int argc __unused, char **argv __unused)
490 {
491 
492 	error("not compiled with history support");
493 	/*NOTREACHED*/
494 	return (0);
495 }
496 
497 int
498 bindcmd(int argc __unused, char **argv __unused)
499 {
500 
501 	error("not compiled with line editing support");
502 	return (0);
503 }
504 #endif
505