xref: /freebsd/bin/sh/histedit.c (revision 25ecdc7d52770caf1c9b44b5ec11f468f6b636f3)
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 <sys/stat.h>
43 #include <dirent.h>
44 #include <fcntl.h>
45 #include <limits.h>
46 #include <paths.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <unistd.h>
50 /*
51  * Editline and history functions (and glue).
52  */
53 #include "shell.h"
54 #include "parser.h"
55 #include "var.h"
56 #include "options.h"
57 #include "main.h"
58 #include "output.h"
59 #include "mystring.h"
60 #include "builtins.h"
61 #ifndef NO_HISTORY
62 #include "myhistedit.h"
63 #include "error.h"
64 #include "eval.h"
65 #include "memalloc.h"
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;
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 static int comparator(const void *, const void *, void *);
79 static char **sh_matches(const char *, int, int);
80 static unsigned char sh_complete(EditLine *, int);
81 
82 static const char *
83 get_histfile(void)
84 {
85 	const char *histfile;
86 
87 	/* don't try to save if the history size is 0 */
88 	if (hist == NULL || histsizeval() == 0)
89 		return (NULL);
90 	histfile = expandstr("${HISTFILE-${HOME-}/.sh_history}");
91 
92 	if (histfile[0] == '\0')
93 		return (NULL);
94 	return (histfile);
95 }
96 
97 void
98 histsave(void)
99 {
100 	HistEvent he;
101 	char *histtmpname = NULL;
102 	const char *histfile;
103 	int fd;
104 	FILE *f;
105 
106 	if ((histfile = get_histfile()) == NULL)
107 		return;
108 	INTOFF;
109 	asprintf(&histtmpname, "%s.XXXXXXXXXX", histfile);
110 	if (histtmpname == NULL) {
111 		INTON;
112 		return;
113 	}
114 	fd = mkstemp(histtmpname);
115 	if (fd == -1 || (f = fdopen(fd, "w")) == NULL) {
116 		free(histtmpname);
117 		INTON;
118 		return;
119 	}
120 	if (history(hist, &he, H_SAVE_FP, f) < 1 ||
121 	    rename(histtmpname, histfile) == -1)
122 		unlink(histtmpname);
123 	fclose(f);
124 	free(histtmpname);
125 	INTON;
126 
127 }
128 
129 void
130 histload(void)
131 {
132 	const char *histfile;
133 	HistEvent he;
134 
135 	if ((histfile = get_histfile()) == NULL)
136 		return;
137 	history(hist, &he, H_LOAD, histfile);
138 }
139 
140 /*
141  * Set history and editing status.  Called whenever the status may
142  * have changed (figures out what to do).
143  */
144 void
145 histedit(void)
146 {
147 
148 #define editing (Eflag || Vflag)
149 
150 	if (iflag) {
151 		if (!hist) {
152 			/*
153 			 * turn history on
154 			 */
155 			INTOFF;
156 			hist = history_init();
157 			INTON;
158 
159 			if (hist != NULL)
160 				sethistsize(histsizeval());
161 			else
162 				out2fmt_flush("sh: can't initialize history\n");
163 		}
164 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
165 			/*
166 			 * turn editing on
167 			 */
168 			char *term;
169 
170 			INTOFF;
171 			if (el_in == NULL)
172 				el_in = fdopen(0, "r");
173 			if (el_out == NULL)
174 				el_out = fdopen(2, "w");
175 			if (el_in == NULL || el_out == NULL)
176 				goto bad;
177 			term = lookupvar("TERM");
178 			if (term)
179 				setenv("TERM", term, 1);
180 			else
181 				unsetenv("TERM");
182 			el = el_init(arg0, el_in, el_out, el_out);
183 			if (el != NULL) {
184 				if (hist)
185 					el_set(el, EL_HIST, history, hist);
186 				el_set(el, EL_PROMPT, getprompt);
187 				el_set(el, EL_ADDFN, "sh-complete",
188 				    "Filename completion",
189 				    sh_complete);
190 			} else {
191 bad:
192 				out2fmt_flush("sh: can't initialize editing\n");
193 			}
194 			INTON;
195 		} else if (!editing && el) {
196 			INTOFF;
197 			el_end(el);
198 			el = NULL;
199 			INTON;
200 		}
201 		if (el) {
202 			if (Vflag)
203 				el_set(el, EL_EDITOR, "vi");
204 			else if (Eflag) {
205 				el_set(el, EL_EDITOR, "emacs");
206 				el_set(el, EL_BIND, "^R", "em-inc-search-prev", NULL);
207 			}
208 			el_set(el, EL_BIND, "^I", "sh-complete", NULL);
209 			el_source(el, NULL);
210 		}
211 	} else {
212 		INTOFF;
213 		if (el) {	/* no editing if not interactive */
214 			el_end(el);
215 			el = NULL;
216 		}
217 		if (hist) {
218 			history_end(hist);
219 			hist = NULL;
220 		}
221 		INTON;
222 	}
223 }
224 
225 
226 void
227 sethistsize(const char *hs)
228 {
229 	int histsize;
230 	HistEvent he;
231 
232 	if (hist != NULL) {
233 		if (hs == NULL || !is_number(hs))
234 			histsize = 100;
235 		else
236 			histsize = atoi(hs);
237 		history(hist, &he, H_SETSIZE, histsize);
238 		history(hist, &he, H_SETUNIQUE, 1);
239 	}
240 }
241 
242 void
243 setterm(const char *term)
244 {
245 	if (rootshell && el != NULL && term != NULL)
246 		el_set(el, EL_TERMINAL, term);
247 }
248 
249 int
250 histcmd(int argc, char **argv __unused)
251 {
252 	int ch;
253 	const char *editor = NULL;
254 	HistEvent he;
255 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
256 	int i, retval;
257 	const char *firststr, *laststr;
258 	int first, last, direction;
259 	char *pat = NULL, *repl = NULL;
260 	static int active = 0;
261 	struct jmploc jmploc;
262 	struct jmploc *savehandler;
263 	char editfilestr[PATH_MAX];
264 	char *volatile editfile;
265 	FILE *efp = NULL;
266 	int oldhistnum;
267 
268 	if (hist == NULL)
269 		error("history not active");
270 
271 	if (argc == 1)
272 		error("missing history argument");
273 
274 	while (not_fcnumber(*argptr) && (ch = nextopt("e:lnrs")) != '\0')
275 		switch ((char)ch) {
276 		case 'e':
277 			editor = shoptarg;
278 			break;
279 		case 'l':
280 			lflg = 1;
281 			break;
282 		case 'n':
283 			nflg = 1;
284 			break;
285 		case 'r':
286 			rflg = 1;
287 			break;
288 		case 's':
289 			sflg = 1;
290 			break;
291 		}
292 
293 	savehandler = handler;
294 	/*
295 	 * If executing...
296 	 */
297 	if (lflg == 0 || editor || sflg) {
298 		lflg = 0;	/* ignore */
299 		editfile = NULL;
300 		/*
301 		 * Catch interrupts to reset active counter and
302 		 * cleanup temp files.
303 		 */
304 		if (setjmp(jmploc.loc)) {
305 			active = 0;
306 			if (editfile)
307 				unlink(editfile);
308 			handler = savehandler;
309 			longjmp(handler->loc, 1);
310 		}
311 		handler = &jmploc;
312 		if (++active > MAXHISTLOOPS) {
313 			active = 0;
314 			displayhist = 0;
315 			error("called recursively too many times");
316 		}
317 		/*
318 		 * Set editor.
319 		 */
320 		if (sflg == 0) {
321 			if (editor == NULL &&
322 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
323 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
324 				editor = DEFEDITOR;
325 			if (editor[0] == '-' && editor[1] == '\0') {
326 				sflg = 1;	/* no edit */
327 				editor = NULL;
328 			}
329 		}
330 	}
331 
332 	/*
333 	 * If executing, parse [old=new] now
334 	 */
335 	if (lflg == 0 && *argptr != NULL &&
336 	     ((repl = strchr(*argptr, '=')) != NULL)) {
337 		pat = *argptr;
338 		*repl++ = '\0';
339 		argptr++;
340 	}
341 	/*
342 	 * determine [first] and [last]
343 	 */
344 	if (*argptr == NULL) {
345 		firststr = lflg ? "-16" : "-1";
346 		laststr = "-1";
347 	} else if (argptr[1] == NULL) {
348 		firststr = argptr[0];
349 		laststr = lflg ? "-1" : argptr[0];
350 	} else if (argptr[2] == NULL) {
351 		firststr = argptr[0];
352 		laststr = argptr[1];
353 	} else
354 		error("too many arguments");
355 	/*
356 	 * Turn into event numbers.
357 	 */
358 	first = str_to_event(firststr, 0);
359 	last = str_to_event(laststr, 1);
360 
361 	if (rflg) {
362 		i = last;
363 		last = first;
364 		first = i;
365 	}
366 	/*
367 	 * XXX - this should not depend on the event numbers
368 	 * always increasing.  Add sequence numbers or offset
369 	 * to the history element in next (diskbased) release.
370 	 */
371 	direction = first < last ? H_PREV : H_NEXT;
372 
373 	/*
374 	 * If editing, grab a temp file.
375 	 */
376 	if (editor) {
377 		int fd;
378 		INTOFF;		/* easier */
379 		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
380 		if ((fd = mkstemp(editfilestr)) < 0)
381 			error("can't create temporary file %s", editfile);
382 		editfile = editfilestr;
383 		if ((efp = fdopen(fd, "w")) == NULL) {
384 			close(fd);
385 			error("Out of space");
386 		}
387 	}
388 
389 	/*
390 	 * Loop through selected history events.  If listing or executing,
391 	 * do it now.  Otherwise, put into temp file and call the editor
392 	 * after.
393 	 *
394 	 * The history interface needs rethinking, as the following
395 	 * convolutions will demonstrate.
396 	 */
397 	history(hist, &he, H_FIRST);
398 	retval = history(hist, &he, H_NEXT_EVENT, first);
399 	for (;retval != -1; retval = history(hist, &he, direction)) {
400 		if (lflg) {
401 			if (!nflg)
402 				out1fmt("%5d ", he.num);
403 			out1str(he.str);
404 		} else {
405 			const char *s = pat ?
406 			   fc_replace(he.str, pat, repl) : he.str;
407 
408 			if (sflg) {
409 				if (displayhist) {
410 					out2str(s);
411 					flushout(out2);
412 				}
413 				evalstring(s, 0);
414 				if (displayhist && hist) {
415 					/*
416 					 *  XXX what about recursive and
417 					 *  relative histnums.
418 					 */
419 					oldhistnum = he.num;
420 					history(hist, &he, H_ENTER, s);
421 					/*
422 					 * XXX H_ENTER moves the internal
423 					 * cursor, set it back to the current
424 					 * entry.
425 					 */
426 					history(hist, &he,
427 					    H_NEXT_EVENT, oldhistnum);
428 				}
429 			} else
430 				fputs(s, efp);
431 		}
432 		/*
433 		 * At end?  (if we were to lose last, we'd sure be
434 		 * messed up).
435 		 */
436 		if (he.num == last)
437 			break;
438 	}
439 	if (editor) {
440 		char *editcmd;
441 
442 		fclose(efp);
443 		INTON;
444 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
445 		sprintf(editcmd, "%s %s", editor, editfile);
446 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
447 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
448 		unlink(editfile);
449 	}
450 
451 	if (lflg == 0 && active > 0)
452 		--active;
453 	if (displayhist)
454 		displayhist = 0;
455 	handler = savehandler;
456 	return 0;
457 }
458 
459 static char *
460 fc_replace(const char *s, char *p, char *r)
461 {
462 	char *dest;
463 	int plen = strlen(p);
464 
465 	STARTSTACKSTR(dest);
466 	while (*s) {
467 		if (*s == *p && strncmp(s, p, plen) == 0) {
468 			STPUTS(r, dest);
469 			s += plen;
470 			*p = '\0';	/* so no more matches */
471 		} else
472 			STPUTC(*s++, dest);
473 	}
474 	STPUTC('\0', dest);
475 	dest = grabstackstr(dest);
476 
477 	return (dest);
478 }
479 
480 static int
481 not_fcnumber(const char *s)
482 {
483 	if (s == NULL)
484 		return (0);
485 	if (*s == '-')
486 		s++;
487 	return (!is_number(s));
488 }
489 
490 static int
491 str_to_event(const char *str, int last)
492 {
493 	HistEvent he;
494 	const char *s = str;
495 	int relative = 0;
496 	int i, retval;
497 
498 	retval = history(hist, &he, H_FIRST);
499 	switch (*s) {
500 	case '-':
501 		relative = 1;
502 		/*FALLTHROUGH*/
503 	case '+':
504 		s++;
505 	}
506 	if (is_number(s)) {
507 		i = atoi(s);
508 		if (relative) {
509 			while (retval != -1 && i--) {
510 				retval = history(hist, &he, H_NEXT);
511 			}
512 			if (retval == -1)
513 				retval = history(hist, &he, H_LAST);
514 		} else {
515 			retval = history(hist, &he, H_NEXT_EVENT, i);
516 			if (retval == -1) {
517 				/*
518 				 * the notion of first and last is
519 				 * backwards to that of the history package
520 				 */
521 				retval = history(hist, &he, last ? H_FIRST : H_LAST);
522 			}
523 		}
524 		if (retval == -1)
525 			error("history number %s not found (internal error)",
526 			       str);
527 	} else {
528 		/*
529 		 * pattern
530 		 */
531 		retval = history(hist, &he, H_PREV_STR, str);
532 		if (retval == -1)
533 			error("history pattern not found: %s", str);
534 	}
535 	return (he.num);
536 }
537 
538 int
539 bindcmd(int argc, char **argv)
540 {
541 	int ret;
542 	FILE *old;
543 	FILE *out;
544 
545 	if (el == NULL)
546 		error("line editing is disabled");
547 
548 	INTOFF;
549 
550 	out = out1fp();
551 	if (out == NULL)
552 		error("Out of space");
553 
554 	el_get(el, EL_GETFP, 1, &old);
555 	el_set(el, EL_SETFP, 1, out);
556 
557 	ret = el_parse(el, argc, __DECONST(const char **, argv));
558 
559 	el_set(el, EL_SETFP, 1, old);
560 
561 	fclose(out);
562 
563 	INTON;
564 
565 	return ret;
566 }
567 
568 #else
569 #include "error.h"
570 
571 int
572 histcmd(int argc __unused, char **argv __unused)
573 {
574 
575 	error("not compiled with history support");
576 	/*NOTREACHED*/
577 	return (0);
578 }
579 
580 int
581 bindcmd(int argc __unused, char **argv __unused)
582 {
583 
584 	error("not compiled with line editing support");
585 	return (0);
586 }
587 #endif
588 
589 /*
590  * Comparator function for qsort(). The use of curpos here is to skip
591  * characters that we already know to compare equal (common prefix).
592  */
593 static int
594 comparator(const void *a, const void *b, void *thunk)
595 {
596 	size_t curpos = (intptr_t)thunk;
597 	return (strcmp(*(char *const *)a + curpos,
598 		*(char *const *)b + curpos));
599 }
600 
601 /*
602  * This function is passed to libedit's fn_complete2(). The library will
603  * use it instead of its standard function that finds matching files in
604  * current directory. If we're at the start of the line, we want to look
605  * for available commands from all paths in $PATH.
606  */
607 static char
608 **sh_matches(const char *text, int start, int end)
609 {
610 	char *free_path = NULL, *path;
611 	const char *dirname;
612 	char **matches = NULL;
613 	size_t i = 0, size = 16, j, k;
614 	size_t curpos = end - start;
615 
616 	if (start > 0 || memchr("/.~", text[0], 3) != NULL)
617 		return (NULL);
618 	if ((free_path = path = strdup(pathval())) == NULL)
619 		goto out;
620 	if ((matches = malloc(size * sizeof(matches[0]))) == NULL)
621 		goto out;
622 	while ((dirname = strsep(&path, ":")) != NULL) {
623 		struct dirent *entry;
624 		DIR *dir;
625 		int dfd;
626 
627 		dir = opendir(dirname[0] == '\0' ? "." : dirname);
628 		if (dir == NULL)
629 			continue;
630 		if ((dfd = dirfd(dir)) == -1) {
631 			closedir(dir);
632 			continue;
633 		}
634 		while ((entry = readdir(dir)) != NULL) {
635 			struct stat statb;
636 			char **rmatches;
637 
638 			if (strncmp(entry->d_name, text, curpos) != 0)
639 				continue;
640 			if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK) {
641 				if (fstatat(dfd, entry->d_name, &statb, 0) == -1)
642 					continue;
643 				if (!S_ISREG(statb.st_mode))
644 					continue;
645 			} else if (entry->d_type != DT_REG)
646 				continue;
647 			matches[++i] = strdup(entry->d_name);
648 			if (i < size - 1)
649 				continue;
650 			size *= 2;
651 			rmatches = reallocarray(matches, size, sizeof(matches[0]));
652 			if (rmatches == NULL) {
653 				closedir(dir);
654 				goto out;
655 			}
656 			matches = rmatches;
657 		}
658 		closedir(dir);
659 	}
660 out:
661 	free(free_path);
662 	/*
663 	 * matches[0] is special: it's not a real matching file name but a common
664 	 * prefix for all matching names. It can't be null, unlike any other
665 	 * element of the array. When strings matches[0] and matches[1] compare
666 	 * equal and matches[2] is null that means to libedit that there is only
667 	 * a single match. It will then replace user input with possibly escaped
668 	 * string in matches[0] which is the reason to copy the full name of the
669 	 * only match.
670 	 */
671 	if (i == 0) {
672 		free(matches);
673 		return (NULL);
674 	} else if (i == 1) {
675 		matches[0] = strdup(matches[1]);
676 		matches[2] = NULL;
677 		if (matches[0] != NULL)
678 			return (matches);
679 	} else
680 		matches[0] = strdup(text);
681 	if (matches[0] == NULL) {
682 		for (j = 1; j <= i; j++)
683 			free(matches[j]);
684 		free(matches);
685 		return (NULL);
686 	}
687 	qsort_s(matches + 1, i, sizeof(matches[0]), comparator,
688 		(void *)(intptr_t)curpos);
689 	for (j = 1, k = 2; k <= i; k++)
690 		if (strcmp(matches[j] + curpos, matches[k] + curpos) == 0)
691 			free(matches[k]);
692 		else
693 			matches[++j] = matches[k];
694 	matches[j + 1] = NULL;
695 	return (matches);
696 }
697 
698 /*
699  * This is passed to el_set(el, EL_ADDFN, ...) so that it's possible to
700  * bind a key (tab by default) to execute the function.
701  */
702 unsigned char
703 sh_complete(EditLine *sel, int ch __unused)
704 {
705 	return (unsigned char)fn_complete2(sel, NULL, sh_matches,
706 		L" \t\n\"\\'`@$><=;|&{(", NULL, NULL, (size_t)100,
707 		NULL, &((int) {0}), NULL, NULL, FN_QUOTE_MATCH);
708 }
709