xref: /minix/bin/sh/histedit.c (revision 0a6a1f1d)
1 /*	$NetBSD: histedit.c,v 1.47 2014/06/18 18:17:30 christos 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.47 2014/06/18 18:17:30 christos 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
histedit(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 				el_set(el, EL_PROMPT, getprompt);
138 				el_set(el, EL_SIGNAL, 1);
139 				el_set(el, EL_ALIAS_TEXT, alias_text, NULL);
140 				el_set(el, EL_ADDFN, "rl-complete",
141 				    "ReadLine compatible completion function",
142 				    _el_fn_complete);
143 			} else {
144 bad:
145 				out2str("sh: can't initialize editing\n");
146 			}
147 			INTON;
148 		} else if (!editing && el) {
149 			INTOFF;
150 			el_end(el);
151 			el = NULL;
152 			INTON;
153 		}
154 		if (el) {
155 			el_source(el, NULL);
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 		}
163 	} else {
164 		INTOFF;
165 		if (el) {	/* no editing if not interactive */
166 			el_end(el);
167 			el = NULL;
168 		}
169 		if (hist) {
170 			history_end(hist);
171 			hist = NULL;
172 		}
173 		INTON;
174 	}
175 }
176 
177 
178 void
sethistsize(const char * hs)179 sethistsize(const char *hs)
180 {
181 	int histsize;
182 	HistEvent he;
183 
184 	if (hist != NULL) {
185 		if (hs == NULL || *hs == '\0' ||
186 		   (histsize = atoi(hs)) < 0)
187 			histsize = 100;
188 		history(hist, &he, H_SETSIZE, histsize);
189 		history(hist, &he, H_SETUNIQUE, 1);
190 	}
191 }
192 
193 void
setterm(const char * term)194 setterm(const char *term)
195 {
196 	if (el != NULL && term != NULL)
197 		if (el_set(el, EL_TERMINAL, term) != 0) {
198 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
199 			outfmt(out2, "sh: Using dumb terminal settings.\n");
200 		}
201 }
202 
203 int
inputrc(int argc,char ** argv)204 inputrc(int argc, char **argv)
205 {
206 	if (argc != 2) {
207 		out2str("usage: inputrc file\n");
208 		return 1;
209 	}
210 	if (el != NULL) {
211 		if (el_source(el, argv[1])) {
212 			out2str("inputrc: failed\n");
213 			return 1;
214 		} else
215 			return 0;
216 	} else {
217 		out2str("sh: inputrc ignored, not editing\n");
218 		return 1;
219 	}
220 }
221 
222 /*
223  *  This command is provided since POSIX decided to standardize
224  *  the Korn shell fc command.  Oh well...
225  */
226 int
histcmd(int argc,char ** argv)227 histcmd(int argc, char **argv)
228 {
229 	int ch;
230 	const char * volatile editor = NULL;
231 	HistEvent he;
232 	int lflg = 0;
233 	volatile int nflg = 0, rflg = 0, sflg = 0;
234 	int i, retval;
235 	const char *firststr, *laststr;
236 	int first, last, direction;
237 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
238 	static int active = 0;
239 	struct jmploc jmploc;
240 	struct jmploc *volatile savehandler;
241 	char editfile[MAXPATHLEN + 1];
242 	FILE *efp;
243 #ifdef __GNUC__
244 	repl = NULL;	/* XXX gcc4 */
245 	efp = NULL;	/* XXX gcc4 */
246 #endif
247 
248 	if (hist == NULL)
249 		error("history not active");
250 
251 	if (argc == 1)
252 		error("missing history argument");
253 
254 	optreset = 1; optind = 1; /* initialize getopt */
255 	while (not_fcnumber(argv[optind]) &&
256 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
257 		switch ((char)ch) {
258 		case 'e':
259 			editor = optionarg;
260 			break;
261 		case 'l':
262 			lflg = 1;
263 			break;
264 		case 'n':
265 			nflg = 1;
266 			break;
267 		case 'r':
268 			rflg = 1;
269 			break;
270 		case 's':
271 			sflg = 1;
272 			break;
273 		case ':':
274 			error("option -%c expects argument", optopt);
275 			/* NOTREACHED */
276 		case '?':
277 		default:
278 			error("unknown option: -%c", optopt);
279 			/* NOTREACHED */
280 		}
281 	argc -= optind, argv += optind;
282 
283 	/*
284 	 * If executing...
285 	 */
286 	if (lflg == 0 || editor || sflg) {
287 		lflg = 0;	/* ignore */
288 		editfile[0] = '\0';
289 		/*
290 		 * Catch interrupts to reset active counter and
291 		 * cleanup temp files.
292 		 */
293 		savehandler = handler;
294 		if (setjmp(jmploc.loc)) {
295 			active = 0;
296 			if (*editfile)
297 				unlink(editfile);
298 			handler = savehandler;
299 			longjmp(handler->loc, 1);
300 		}
301 		handler = &jmploc;
302 		if (++active > MAXHISTLOOPS) {
303 			active = 0;
304 			displayhist = 0;
305 			error("called recursively too many times");
306 		}
307 		/*
308 		 * Set editor.
309 		 */
310 		if (sflg == 0) {
311 			if (editor == NULL &&
312 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
313 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
314 				editor = DEFEDITOR;
315 			if (editor[0] == '-' && editor[1] == '\0') {
316 				sflg = 1;	/* no edit */
317 				editor = NULL;
318 			}
319 		}
320 	}
321 
322 	/*
323 	 * If executing, parse [old=new] now
324 	 */
325 	if (lflg == 0 && argc > 0 &&
326 	     ((repl = strchr(argv[0], '=')) != NULL)) {
327 		pat = argv[0];
328 		*repl++ = '\0';
329 		argc--, argv++;
330 	}
331 
332 	/*
333 	 * If -s is specified, accept only one operand
334 	 */
335 	if (sflg && argc >= 2)
336 		error("too many args");
337 
338 	/*
339 	 * determine [first] and [last]
340 	 */
341 	switch (argc) {
342 	case 0:
343 		firststr = lflg ? "-16" : "-1";
344 		laststr = "-1";
345 		break;
346 	case 1:
347 		firststr = argv[0];
348 		laststr = lflg ? "-1" : argv[0];
349 		break;
350 	case 2:
351 		firststr = argv[0];
352 		laststr = argv[1];
353 		break;
354 	default:
355 		error("too many args");
356 		/* NOTREACHED */
357 	}
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 		snprintf(editfile, sizeof(editfile), "%s_shXXXXXX", _PATH_TMP);
383 		if ((fd = mkstemp(editfile)) < 0)
384 			error("can't create temporary file %s", editfile);
385 		if ((efp = fdopen(fd, "w")) == NULL) {
386 			close(fd);
387 			error("can't allocate stdio buffer for temp");
388 		}
389 	}
390 
391 	/*
392 	 * Loop through selected history events.  If listing or executing,
393 	 * do it now.  Otherwise, put into temp file and call the editor
394 	 * after.
395 	 *
396 	 * The history interface needs rethinking, as the following
397 	 * convolutions will demonstrate.
398 	 */
399 	history(hist, &he, H_FIRST);
400 	retval = history(hist, &he, H_NEXT_EVENT, first);
401 	for (;retval != -1; retval = history(hist, &he, direction)) {
402 		if (lflg) {
403 			if (!nflg)
404 				out1fmt("%5d ", he.num);
405 			out1str(he.str);
406 		} else {
407 			const char *s = pat ?
408 			   fc_replace(he.str, pat, repl) : he.str;
409 
410 			if (sflg) {
411 				if (displayhist) {
412 					out2str(s);
413 				}
414 
415 				evalstring(strcpy(stalloc(strlen(s) + 1), s), 0);
416 				if (displayhist && hist) {
417 					/*
418 					 *  XXX what about recursive and
419 					 *  relative histnums.
420 					 */
421 					history(hist, &he, H_ENTER, s);
422 				}
423 
424 				break;
425 			} else
426 				fputs(s, efp);
427 		}
428 		/*
429 		 * At end?  (if we were to lose last, we'd sure be
430 		 * messed up).
431 		 */
432 		if (he.num == last)
433 			break;
434 	}
435 	if (editor) {
436 		char *editcmd;
437 		size_t cmdlen;
438 
439 		fclose(efp);
440 		cmdlen = strlen(editor) + strlen(editfile) + 2;
441 		editcmd = stalloc(cmdlen);
442 		snprintf(editcmd, cmdlen, "%s %s", editor, editfile);
443 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
444 		INTON;
445 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
446 		unlink(editfile);
447 	}
448 
449 	if (lflg == 0 && active > 0)
450 		--active;
451 	if (displayhist)
452 		displayhist = 0;
453 	return 0;
454 }
455 
456 STATIC const char *
fc_replace(const char * s,char * p,char * r)457 fc_replace(const char *s, char *p, char *r)
458 {
459 	char *dest;
460 	int plen = strlen(p);
461 
462 	STARTSTACKSTR(dest);
463 	while (*s) {
464 		if (*s == *p && strncmp(s, p, plen) == 0) {
465 			while (*r)
466 				STPUTC(*r++, dest);
467 			s += plen;
468 			*p = '\0';	/* so no more matches */
469 		} else
470 			STPUTC(*s++, dest);
471 	}
472 	STACKSTRNUL(dest);
473 	dest = grabstackstr(dest);
474 
475 	return (dest);
476 }
477 
478 int
not_fcnumber(char * s)479 not_fcnumber(char *s)
480 {
481 	if (s == NULL)
482 		return 0;
483         if (*s == '-')
484                 s++;
485 	return (!is_number(s));
486 }
487 
488 int
str_to_event(const char * str,int last)489 str_to_event(const char *str, int last)
490 {
491 	HistEvent he;
492 	const char *s = str;
493 	int relative = 0;
494 	int i, retval;
495 
496 	retval = history(hist, &he, H_FIRST);
497 	switch (*s) {
498 	case '-':
499 		relative = 1;
500 		/*FALLTHROUGH*/
501 	case '+':
502 		s++;
503 	}
504 	if (is_number(s)) {
505 		i = atoi(s);
506 		if (relative) {
507 			while (retval != -1 && i--) {
508 				retval = history(hist, &he, H_NEXT);
509 			}
510 			if (retval == -1)
511 				retval = history(hist, &he, H_LAST);
512 		} else {
513 			retval = history(hist, &he, H_NEXT_EVENT, i);
514 			if (retval == -1) {
515 				/*
516 				 * the notion of first and last is
517 				 * backwards to that of the history package
518 				 */
519 				retval = history(hist, &he,
520 						last ? H_FIRST : H_LAST);
521 			}
522 		}
523 		if (retval == -1)
524 			error("history number %s not found (internal error)",
525 			       str);
526 	} else {
527 		/*
528 		 * pattern
529 		 */
530 		retval = history(hist, &he, H_PREV_STR, str);
531 		if (retval == -1)
532 			error("history pattern not found: %s", str);
533 	}
534 	return (he.num);
535 }
536 #else
537 int
histcmd(int argc,char ** argv)538 histcmd(int argc, char **argv)
539 {
540 	error("not compiled with history support");
541 	/* NOTREACHED */
542 }
543 int
inputrc(int argc,char ** argv)544 inputrc(int argc, char **argv)
545 {
546 	error("not compiled with history support");
547 	/* NOTREACHED */
548 }
549 #endif
550