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