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