xref: /netbsd-src/bin/sh/histedit.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: histedit.c,v 1.53 2018/07/13 22:43:44 kre Exp $	*/
2 
3 /*-
4  * Copyright (c) 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
39 #else
40 __RCSID("$NetBSD: histedit.c,v 1.53 2018/07/13 22:43:44 kre Exp $");
41 #endif
42 #endif /* not lint */
43 
44 #include <sys/param.h>
45 #include <paths.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <unistd.h>
49 /*
50  * Editline and history functions (and glue).
51  */
52 #include "shell.h"
53 #include "parser.h"
54 #include "var.h"
55 #include "options.h"
56 #include "builtins.h"
57 #include "main.h"
58 #include "output.h"
59 #include "mystring.h"
60 #include "myhistedit.h"
61 #include "error.h"
62 #include "alias.h"
63 #ifndef SMALL
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 unsigned char _el_fn_complete(EditLine *, int);
75 
76 STATIC const char *fc_replace(const char *, char *, char *);
77 
78 #ifdef DEBUG
79 extern FILE *tracefile;
80 #endif
81 
82 /*
83  * Set history and editing status.  Called whenever the status may
84  * have changed (figures out what to do).
85  */
86 void
87 histedit(void)
88 {
89 	FILE *el_err;
90 
91 #define editing (Eflag || Vflag)
92 
93 	if (iflag == 1) {
94 		if (!hist) {
95 			/*
96 			 * turn history on
97 			 */
98 			INTOFF;
99 			hist = history_init();
100 			INTON;
101 
102 			if (hist != NULL)
103 				sethistsize(histsizeval());
104 			else
105 				out2str("sh: can't initialize history\n");
106 		}
107 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
108 			/*
109 			 * turn editing on
110 			 */
111 			char *term, *shname;
112 
113 			INTOFF;
114 			if (el_in == NULL)
115 				el_in = fdopen(0, "r");
116 			if (el_out == NULL)
117 				el_out = fdopen(2, "w");
118 			if (el_in == NULL || el_out == NULL)
119 				goto bad;
120 			el_err = el_out;
121 #if DEBUG
122 			if (tracefile)
123 				el_err = tracefile;
124 #endif
125 			term = lookupvar("TERM");
126 			if (term)
127 				setenv("TERM", term, 1);
128 			else
129 				unsetenv("TERM");
130 			shname = arg0;
131 			if (shname[0] == '-')
132 				shname++;
133 			el = el_init(shname, el_in, el_out, el_err);
134 			if (el != NULL) {
135 				if (hist)
136 					el_set(el, EL_HIST, history, hist);
137 
138 				set_prompt_lit(lookupvar("PSlit"));
139 				el_set(el, EL_SIGNAL, 1);
140 				el_set(el, EL_ALIAS_TEXT, alias_text, NULL);
141 				el_set(el, EL_ADDFN, "rl-complete",
142 				    "ReadLine compatible completion function",
143 				    _el_fn_complete);
144 			} else {
145 bad:
146 				out2str("sh: can't initialize editing\n");
147 			}
148 			INTON;
149 		} else if (!editing && el) {
150 			INTOFF;
151 			el_end(el);
152 			el = NULL;
153 			INTON;
154 		}
155 		if (el) {
156 			if (Vflag)
157 				el_set(el, EL_EDITOR, "vi");
158 			else if (Eflag)
159 				el_set(el, EL_EDITOR, "emacs");
160 			el_set(el, EL_BIND, "^I",
161 			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
162 			el_source(el, lookupvar("EDITRC"));
163 		}
164 	} else {
165 		INTOFF;
166 		if (el) {	/* no editing if not interactive */
167 			el_end(el);
168 			el = NULL;
169 		}
170 		if (hist) {
171 			history_end(hist);
172 			hist = NULL;
173 		}
174 		INTON;
175 	}
176 }
177 
178 void
179 set_prompt_lit(const char *lit_ch)
180 {
181 	wchar_t wc;
182 
183 	if (!(iflag && editing && el))
184 		return;
185 
186 	if (lit_ch == NULL) {
187 		el_set(el, EL_PROMPT, getprompt);
188 		return;
189 	}
190 
191 	mbtowc(&wc, NULL, 1);		/* state init */
192 
193 	if (mbtowc(&wc, lit_ch, strlen(lit_ch)) <= 0)
194 		el_set(el, EL_PROMPT, getprompt);
195 	else
196 		el_set(el, EL_PROMPT_ESC, getprompt, (int)wc);
197 }
198 
199 void
200 set_editrc(const char *fname)
201 {
202 	if (iflag && editing && el)
203 		el_source(el, fname);
204 }
205 
206 void
207 sethistsize(const char *hs)
208 {
209 	int histsize;
210 	HistEvent he;
211 
212 	if (hist != NULL) {
213 		if (hs == NULL || *hs == '\0' || *hs == '-' ||
214 		   (histsize = number(hs)) < 0)
215 			histsize = 100;
216 		history(hist, &he, H_SETSIZE, histsize);
217 		history(hist, &he, H_SETUNIQUE, 1);
218 	}
219 }
220 
221 void
222 setterm(const char *term)
223 {
224 	if (el != NULL && term != NULL)
225 		if (el_set(el, EL_TERMINAL, term) != 0) {
226 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
227 			outfmt(out2, "sh: Using dumb terminal settings.\n");
228 		}
229 }
230 
231 int
232 inputrc(int argc, char **argv)
233 {
234 	if (argc != 2) {
235 		out2str("usage: inputrc file\n");
236 		return 1;
237 	}
238 	if (el != NULL) {
239 		if (el_source(el, argv[1])) {
240 			out2str("inputrc: failed\n");
241 			return 1;
242 		} else
243 			return 0;
244 	} else {
245 		out2str("sh: inputrc ignored, not editing\n");
246 		return 1;
247 	}
248 }
249 
250 /*
251  *  This command is provided since POSIX decided to standardize
252  *  the Korn shell fc command.  Oh well...
253  */
254 int
255 histcmd(volatile int argc, char ** volatile argv)
256 {
257 	int ch;
258 	const char * volatile editor = NULL;
259 	HistEvent he;
260 	volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
261 	int i, retval;
262 	const char *firststr, *laststr;
263 	int first, last, direction;
264 	char * volatile pat = NULL, * volatile repl;	/* ksh "fc old=new" crap */
265 	static int active = 0;
266 	struct jmploc jmploc;
267 	struct jmploc *volatile savehandler;
268 	char editfile[MAXPATHLEN + 1];
269 	FILE * volatile efp;
270 #ifdef __GNUC__
271 	repl = NULL;	/* XXX gcc4 */
272 	efp = NULL;	/* XXX gcc4 */
273 #endif
274 
275 	if (hist == NULL)
276 		error("history not active");
277 
278 	if (argc == 1)
279 		error("missing history argument");
280 
281 	optreset = 1; optind = 1; /* initialize getopt */
282 	while (not_fcnumber(argv[optind]) &&
283 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
284 		switch ((char)ch) {
285 		case 'e':
286 			editor = optionarg;
287 			break;
288 		case 'l':
289 			lflg = 1;
290 			break;
291 		case 'n':
292 			nflg = 1;
293 			break;
294 		case 'r':
295 			rflg = 1;
296 			break;
297 		case 's':
298 			sflg = 1;
299 			break;
300 		case ':':
301 			error("option -%c expects argument", optopt);
302 			/* NOTREACHED */
303 		case '?':
304 		default:
305 			error("unknown option: -%c", optopt);
306 			/* NOTREACHED */
307 		}
308 	argc -= optind, argv += optind;
309 
310 	/*
311 	 * If executing...
312 	 */
313 	if (lflg == 0 || editor || sflg) {
314 		lflg = 0;	/* ignore */
315 		editfile[0] = '\0';
316 		/*
317 		 * Catch interrupts to reset active counter and
318 		 * cleanup temp files.
319 		 */
320 		savehandler = handler;
321 		if (setjmp(jmploc.loc)) {
322 			active = 0;
323 			if (*editfile)
324 				unlink(editfile);
325 			handler = savehandler;
326 			longjmp(handler->loc, 1);
327 		}
328 		handler = &jmploc;
329 		if (++active > MAXHISTLOOPS) {
330 			active = 0;
331 			displayhist = 0;
332 			error("called recursively too many times");
333 		}
334 		/*
335 		 * Set editor.
336 		 */
337 		if (sflg == 0) {
338 			if (editor == NULL &&
339 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
340 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
341 				editor = DEFEDITOR;
342 			if (editor[0] == '-' && editor[1] == '\0') {
343 				sflg = 1;	/* no edit */
344 				editor = NULL;
345 			}
346 		}
347 	}
348 
349 	/*
350 	 * If executing, parse [old=new] now
351 	 */
352 	if (lflg == 0 && argc > 0 &&
353 	     ((repl = strchr(argv[0], '=')) != NULL)) {
354 		pat = argv[0];
355 		*repl++ = '\0';
356 		argc--, argv++;
357 	}
358 
359 	/*
360 	 * If -s is specified, accept only one operand
361 	 */
362 	if (sflg && argc >= 2)
363 		error("too many args");
364 
365 	/*
366 	 * determine [first] and [last]
367 	 */
368 	switch (argc) {
369 	case 0:
370 		firststr = lflg ? "-16" : "-1";
371 		laststr = "-1";
372 		break;
373 	case 1:
374 		firststr = argv[0];
375 		laststr = lflg ? "-1" : argv[0];
376 		break;
377 	case 2:
378 		firststr = argv[0];
379 		laststr = argv[1];
380 		break;
381 	default:
382 		error("too many args");
383 		/* NOTREACHED */
384 	}
385 	/*
386 	 * Turn into event numbers.
387 	 */
388 	first = str_to_event(firststr, 0);
389 	last = str_to_event(laststr, 1);
390 
391 	if (rflg) {
392 		i = last;
393 		last = first;
394 		first = i;
395 	}
396 	/*
397 	 * XXX - this should not depend on the event numbers
398 	 * always increasing.  Add sequence numbers or offset
399 	 * to the history element in next (diskbased) release.
400 	 */
401 	direction = first < last ? H_PREV : H_NEXT;
402 
403 	/*
404 	 * If editing, grab a temp file.
405 	 */
406 	if (editor) {
407 		int fd;
408 		INTOFF;		/* easier */
409 		snprintf(editfile, sizeof(editfile), "%s_shXXXXXX", _PATH_TMP);
410 		if ((fd = mkstemp(editfile)) < 0)
411 			error("can't create temporary file %s", editfile);
412 		if ((efp = fdopen(fd, "w")) == NULL) {
413 			close(fd);
414 			error("can't allocate stdio buffer for temp");
415 		}
416 	}
417 
418 	/*
419 	 * Loop through selected history events.  If listing or executing,
420 	 * do it now.  Otherwise, put into temp file and call the editor
421 	 * after.
422 	 *
423 	 * The history interface needs rethinking, as the following
424 	 * convolutions will demonstrate.
425 	 */
426 	history(hist, &he, H_FIRST);
427 	retval = history(hist, &he, H_NEXT_EVENT, first);
428 	for (;retval != -1; retval = history(hist, &he, direction)) {
429 		if (lflg) {
430 			if (!nflg)
431 				out1fmt("%5d ", he.num);
432 			out1str(he.str);
433 		} else {
434 			const char *s = pat ?
435 			   fc_replace(he.str, pat, repl) : he.str;
436 
437 			if (sflg) {
438 				if (displayhist) {
439 					out2str(s);
440 				}
441 
442 				evalstring(strcpy(stalloc(strlen(s) + 1), s), 0);
443 				if (displayhist && hist) {
444 					/*
445 					 *  XXX what about recursive and
446 					 *  relative histnums.
447 					 */
448 					history(hist, &he, H_ENTER, s);
449 				}
450 
451 				break;
452 			} else
453 				fputs(s, efp);
454 		}
455 		/*
456 		 * At end?  (if we were to lose last, we'd sure be
457 		 * messed up).
458 		 */
459 		if (he.num == last)
460 			break;
461 	}
462 	if (editor) {
463 		char *editcmd;
464 		size_t cmdlen;
465 
466 		fclose(efp);
467 		cmdlen = strlen(editor) + strlen(editfile) + 2;
468 		editcmd = stalloc(cmdlen);
469 		snprintf(editcmd, cmdlen, "%s %s", editor, editfile);
470 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
471 		INTON;
472 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
473 		unlink(editfile);
474 	}
475 
476 	if (lflg == 0 && active > 0)
477 		--active;
478 	if (displayhist)
479 		displayhist = 0;
480 	return 0;
481 }
482 
483 STATIC const char *
484 fc_replace(const char *s, char *p, char *r)
485 {
486 	char *dest;
487 	int plen = strlen(p);
488 
489 	STARTSTACKSTR(dest);
490 	while (*s) {
491 		if (*s == *p && strncmp(s, p, plen) == 0) {
492 			while (*r)
493 				STPUTC(*r++, dest);
494 			s += plen;
495 			*p = '\0';	/* so no more matches */
496 		} else
497 			STPUTC(*s++, dest);
498 	}
499 	STACKSTRNUL(dest);
500 	dest = grabstackstr(dest);
501 
502 	return (dest);
503 }
504 
505 int
506 not_fcnumber(char *s)
507 {
508 	if (s == NULL)
509 		return 0;
510         if (*s == '-')
511                 s++;
512 	return (!is_number(s));
513 }
514 
515 int
516 str_to_event(const char *str, int last)
517 {
518 	HistEvent he;
519 	const char *s = str;
520 	int relative = 0;
521 	int i, retval;
522 
523 	retval = history(hist, &he, H_FIRST);
524 	switch (*s) {
525 	case '-':
526 		relative = 1;
527 		/*FALLTHROUGH*/
528 	case '+':
529 		s++;
530 	}
531 	if (is_number(s)) {
532 		i = number(s);
533 		if (relative) {
534 			while (retval != -1 && i--) {
535 				retval = history(hist, &he, H_NEXT);
536 			}
537 			if (retval == -1)
538 				retval = history(hist, &he, H_LAST);
539 		} else {
540 			retval = history(hist, &he, H_NEXT_EVENT, i);
541 			if (retval == -1) {
542 				/*
543 				 * the notion of first and last is
544 				 * backwards to that of the history package
545 				 */
546 				retval = history(hist, &he,
547 						last ? H_FIRST : H_LAST);
548 			}
549 		}
550 		if (retval == -1)
551 			error("history number %s not found (internal error)",
552 			       str);
553 	} else {
554 		/*
555 		 * pattern
556 		 */
557 		retval = history(hist, &he, H_PREV_STR, str);
558 		if (retval == -1)
559 			error("history pattern not found: %s", str);
560 	}
561 	return (he.num);
562 }
563 #else
564 int
565 histcmd(int argc, char **argv)
566 {
567 	error("not compiled with history support");
568 	/* NOTREACHED */
569 }
570 int
571 inputrc(int argc, char **argv)
572 {
573 	error("not compiled with history support");
574 	/* NOTREACHED */
575 }
576 #endif
577