xref: /dragonfly/bin/sh/histedit.c (revision 0ca59c34)
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 #include "error.h"
60 #include "eval.h"
61 #include "memalloc.h"
62 #include "builtins.h"
63 
64 #define MAXHISTLOOPS	4	/* max recursions through fc */
65 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
66 
67 History *hist;	/* history cookie */
68 EditLine *el;	/* editline cookie */
69 int displayhist;
70 static FILE *el_in, *el_out, *el_err;
71 
72 static char *fc_replace(const char *, char *, char *);
73 static int not_fcnumber(const char *);
74 static int str_to_event(const char *, int);
75 
76 /*
77  * Set history and editing status.  Called whenever the status may
78  * have changed (figures out what to do).
79  */
80 void
81 histedit(void)
82 {
83 
84 #define editing (Eflag || Vflag)
85 
86 	if (iflag) {
87 		if (!hist) {
88 			/*
89 			 * turn history on
90 			 */
91 			INTOFF;
92 			hist = history_init();
93 			INTON;
94 
95 			if (hist != NULL)
96 				sethistsize(histsizeval());
97 			else
98 				out2fmt_flush("sh: can't initialize history\n");
99 		}
100 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
101 			/*
102 			 * turn editing on
103 			 */
104 			char *term;
105 
106 			INTOFF;
107 			if (el_in == NULL)
108 				el_in = fdopen(0, "r");
109 			if (el_err == NULL)
110 				el_err = fdopen(1, "w");
111 			if (el_out == NULL)
112 				el_out = fdopen(2, "w");
113 			if (el_in == NULL || el_err == NULL || el_out == NULL)
114 				goto bad;
115 			term = lookupvar("TERM");
116 			if (term)
117 				setenv("TERM", term, 1);
118 			else
119 				unsetenv("TERM");
120 			el = el_init(arg0, el_in, el_out, el_err);
121 			if (el != NULL) {
122 				if (hist)
123 					el_set(el, EL_HIST, history, hist);
124 				el_set(el, EL_PROMPT, getprompt);
125 				el_set(el, EL_ADDFN, "sh-complete",
126 				    "Filename completion",
127 				    _el_fn_complete);
128 			} else {
129 bad:
130 				out2fmt_flush("sh: can't initialize editing\n");
131 			}
132 			INTON;
133 		} else if (!editing && el) {
134 			INTOFF;
135 			el_end(el);
136 			el = NULL;
137 			INTON;
138 		}
139 		if (el) {
140 			if (Vflag)
141 				el_set(el, EL_EDITOR, "vi");
142 			else if (Eflag)
143 				el_set(el, EL_EDITOR, "emacs");
144 			el_set(el, EL_BIND, "^I", "sh-complete", NULL);
145 			el_source(el, NULL);
146 		}
147 	} else {
148 		INTOFF;
149 		if (el) {	/* no editing if not interactive */
150 			el_end(el);
151 			el = NULL;
152 		}
153 		if (hist) {
154 			history_end(hist);
155 			hist = NULL;
156 		}
157 		INTON;
158 	}
159 }
160 
161 
162 void
163 sethistsize(const char *hs)
164 {
165 	int histsize;
166 	HistEvent he;
167 
168 	if (hist != NULL) {
169 		if (hs == NULL || !is_number(hs))
170 			histsize = 100;
171 		else
172 			histsize = atoi(hs);
173 		history(hist, &he, H_SETSIZE, histsize);
174 		history(hist, &he, H_SETUNIQUE, 1);
175 	}
176 }
177 
178 void
179 setterm(const char *term)
180 {
181 	if (rootshell && el != NULL && term != NULL)
182 		el_set(el, EL_TERMINAL, term);
183 }
184 
185 int
186 histcmd(int argc, char **argv __unused)
187 {
188 	int ch;
189 	const char *editor = NULL;
190 	HistEvent he;
191 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
192 	int i, retval;
193 	const char *firststr, *laststr;
194 	int first, last, direction;
195 	char *pat = NULL, *repl = NULL;
196 	static int active = 0;
197 	struct jmploc jmploc;
198 	struct jmploc *savehandler;
199 	char editfilestr[PATH_MAX];
200 	char *volatile editfile;
201 	FILE *efp = NULL;
202 	int oldhistnum;
203 
204 	if (hist == NULL)
205 		error("history not active");
206 
207 	if (argc == 1)
208 		error("missing history argument");
209 
210 	while (not_fcnumber(*argptr) && (ch = nextopt("e:lnrs")) != '\0')
211 		switch ((char)ch) {
212 		case 'e':
213 			editor = shoptarg;
214 			break;
215 		case 'l':
216 			lflg = 1;
217 			break;
218 		case 'n':
219 			nflg = 1;
220 			break;
221 		case 'r':
222 			rflg = 1;
223 			break;
224 		case 's':
225 			sflg = 1;
226 			break;
227 		}
228 
229 	savehandler = handler;
230 	/*
231 	 * If executing...
232 	 */
233 	if (lflg == 0 || editor || sflg) {
234 		lflg = 0;	/* ignore */
235 		editfile = NULL;
236 		/*
237 		 * Catch interrupts to reset active counter and
238 		 * cleanup temp files.
239 		 */
240 		if (setjmp(jmploc.loc)) {
241 			active = 0;
242 			if (editfile)
243 				unlink(editfile);
244 			handler = savehandler;
245 			longjmp(handler->loc, 1);
246 		}
247 		handler = &jmploc;
248 		if (++active > MAXHISTLOOPS) {
249 			active = 0;
250 			displayhist = 0;
251 			error("called recursively too many times");
252 		}
253 		/*
254 		 * Set editor.
255 		 */
256 		if (sflg == 0) {
257 			if (editor == NULL &&
258 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
259 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
260 				editor = DEFEDITOR;
261 			if (editor[0] == '-' && editor[1] == '\0') {
262 				sflg = 1;	/* no edit */
263 				editor = NULL;
264 			}
265 		}
266 	}
267 
268 	/*
269 	 * If executing, parse [old=new] now
270 	 */
271 	if (lflg == 0 && *argptr != NULL &&
272 	     ((repl = strchr(*argptr, '=')) != NULL)) {
273 		pat = *argptr;
274 		*repl++ = '\0';
275 		argptr++;
276 	}
277 	/*
278 	 * determine [first] and [last]
279 	 */
280 	if (*argptr == NULL) {
281 		firststr = lflg ? "-16" : "-1";
282 		laststr = "-1";
283 	} else if (argptr[1] == NULL) {
284 		firststr = argptr[0];
285 		laststr = lflg ? "-1" : argptr[0];
286 	} else if (argptr[2] == NULL) {
287 		firststr = argptr[0];
288 		laststr = argptr[1];
289 	} else
290 		error("too many arguments");
291 	/*
292 	 * Turn into event numbers.
293 	 */
294 	first = str_to_event(firststr, 0);
295 	last = str_to_event(laststr, 1);
296 
297 	if (rflg) {
298 		i = last;
299 		last = first;
300 		first = i;
301 	}
302 	/*
303 	 * XXX - this should not depend on the event numbers
304 	 * always increasing.  Add sequence numbers or offset
305 	 * to the history element in next (diskbased) release.
306 	 */
307 	direction = first < last ? H_PREV : H_NEXT;
308 
309 	/*
310 	 * If editing, grab a temp file.
311 	 */
312 	if (editor) {
313 		int fd;
314 		INTOFF;		/* easier */
315 		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
316 		if ((fd = mkstemp(editfilestr)) < 0)
317 			error("can't create temporary file %s", editfile);
318 		editfile = editfilestr;
319 		if ((efp = fdopen(fd, "w")) == NULL) {
320 			close(fd);
321 			error("Out of space");
322 		}
323 	}
324 
325 	/*
326 	 * Loop through selected history events.  If listing or executing,
327 	 * do it now.  Otherwise, put into temp file and call the editor
328 	 * after.
329 	 *
330 	 * The history interface needs rethinking, as the following
331 	 * convolutions will demonstrate.
332 	 */
333 	history(hist, &he, H_FIRST);
334 	retval = history(hist, &he, H_NEXT_EVENT, first);
335 	for (;retval != -1; retval = history(hist, &he, direction)) {
336 		if (lflg) {
337 			if (!nflg)
338 				out1fmt("%5d ", he.num);
339 			out1str(he.str);
340 		} else {
341 			const char *s = pat ?
342 			   fc_replace(he.str, pat, repl) : he.str;
343 
344 			if (sflg) {
345 				if (displayhist) {
346 					out2str(s);
347 					flushout(out2);
348 				}
349 				evalstring(s, 0);
350 				if (displayhist && hist) {
351 					/*
352 					 *  XXX what about recursive and
353 					 *  relative histnums.
354 					 */
355 					oldhistnum = he.num;
356 					history(hist, &he, H_ENTER, s);
357 					/*
358 					 * XXX H_ENTER moves the internal
359 					 * cursor, set it back to the current
360 					 * entry.
361 					 */
362 					retval = history(hist, &he,
363 					    H_NEXT_EVENT, oldhistnum);
364 				}
365 			} else
366 				fputs(s, efp);
367 		}
368 		/*
369 		 * At end?  (if we were to lose 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, 0);	/* 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 	handler = savehandler;
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 			STPUTS(r, dest);
405 			s += plen;
406 			*p = '\0';	/* so no more matches */
407 		} else
408 			STPUTC(*s++, dest);
409 	}
410 	STPUTC('\0', dest);
411 	dest = grabstackstr(dest);
412 
413 	return (dest);
414 }
415 
416 static int
417 not_fcnumber(const char *s)
418 {
419 	if (s == NULL)
420 		return (0);
421 	if (*s == '-')
422 		s++;
423 	return (!is_number(s));
424 }
425 
426 static int
427 str_to_event(const char *str, int last)
428 {
429 	HistEvent he;
430 	const char *s = str;
431 	int relative = 0;
432 	int i, retval;
433 
434 	retval = history(hist, &he, H_FIRST);
435 	switch (*s) {
436 	case '-':
437 		relative = 1;
438 		/*FALLTHROUGH*/
439 	case '+':
440 		s++;
441 	}
442 	if (is_number(s)) {
443 		i = atoi(s);
444 		if (relative) {
445 			while (retval != -1 && i--) {
446 				retval = history(hist, &he, H_NEXT);
447 			}
448 			if (retval == -1)
449 				retval = history(hist, &he, H_LAST);
450 		} else {
451 			retval = history(hist, &he, H_NEXT_EVENT, i);
452 			if (retval == -1) {
453 				/*
454 				 * the notion of first and last is
455 				 * backwards to that of the history package
456 				 */
457 				retval = history(hist, &he, last ? H_FIRST : H_LAST);
458 			}
459 		}
460 		if (retval == -1)
461 			error("history number %s not found (internal error)",
462 			       str);
463 	} else {
464 		/*
465 		 * pattern
466 		 */
467 		retval = history(hist, &he, H_PREV_STR, str);
468 		if (retval == -1)
469 			error("history pattern not found: %s", str);
470 	}
471 	return (he.num);
472 }
473 
474 int
475 bindcmd(int argc, char **argv)
476 {
477 
478 	if (el == NULL)
479 		error("line editing is disabled");
480 	return (el_parse(el, argc, __DECONST(const char **, argv)));
481 }
482 
483 #else
484 #include "error.h"
485 
486 int
487 histcmd(int argc, char **argv)
488 {
489 
490 	error("not compiled with history support");
491 	/*NOTREACHED*/
492 	return (0);
493 }
494 
495 int
496 bindcmd(int argc, char **argv)
497 {
498 
499 	error("not compiled with line editing support");
500 	return (0);
501 }
502 #endif
503