xref: /minix/bin/sh/histedit.c (revision 9f988b79)
1 /*	$NetBSD: histedit.c,v 1.45 2012/03/20 18:42:29 matt 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.45 2012/03/20 18:42:29 matt 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 #ifndef SMALL
63 #include "eval.h"
64 #include "memalloc.h"
65 
66 #define MAXHISTLOOPS	4	/* max recursions through fc */
67 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
68 
69 History *hist;	/* history cookie */
70 EditLine *el;	/* editline cookie */
71 int displayhist;
72 static FILE *el_in, *el_out;
73 unsigned char _el_fn_complete(EditLine *, int);
74 
75 STATIC const char *fc_replace(const char *, char *, char *);
76 
77 #ifdef DEBUG
78 extern FILE *tracefile;
79 #endif
80 
81 /*
82  * Set history and editing status.  Called whenever the status may
83  * have changed (figures out what to do).
84  */
85 void
86 histedit(void)
87 {
88 	FILE *el_err;
89 
90 #define editing (Eflag || Vflag)
91 
92 	if (iflag == 1) {
93 		if (!hist) {
94 			/*
95 			 * turn history on
96 			 */
97 			INTOFF;
98 			hist = history_init();
99 			INTON;
100 
101 			if (hist != NULL)
102 				sethistsize(histsizeval());
103 			else
104 				out2str("sh: can't initialize history\n");
105 		}
106 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
107 			/*
108 			 * turn editing on
109 			 */
110 			char *term, *shname;
111 
112 			INTOFF;
113 			if (el_in == NULL)
114 				el_in = fdopen(0, "r");
115 			if (el_out == NULL)
116 				el_out = fdopen(2, "w");
117 			if (el_in == NULL || el_out == NULL)
118 				goto bad;
119 			el_err = el_out;
120 #if DEBUG
121 			if (tracefile)
122 				el_err = tracefile;
123 #endif
124 			term = lookupvar("TERM");
125 			if (term)
126 				setenv("TERM", term, 1);
127 			else
128 				unsetenv("TERM");
129 			shname = arg0;
130 			if (shname[0] == '-')
131 				shname++;
132 			el = el_init(shname, el_in, el_out, el_err);
133 			if (el != NULL) {
134 				if (hist)
135 					el_set(el, EL_HIST, history, hist);
136 				el_set(el, EL_PROMPT, getprompt);
137 				el_set(el, EL_SIGNAL, 1);
138 				el_set(el, EL_ADDFN, "rl-complete",
139 				    "ReadLine compatible completion function",
140 				    _el_fn_complete);
141 			} else {
142 bad:
143 				out2str("sh: can't initialize editing\n");
144 			}
145 			INTON;
146 		} else if (!editing && el) {
147 			INTOFF;
148 			el_end(el);
149 			el = NULL;
150 			INTON;
151 		}
152 		if (el) {
153 			el_source(el, NULL);
154 			if (Vflag)
155 				el_set(el, EL_EDITOR, "vi");
156 			else if (Eflag)
157 				el_set(el, EL_EDITOR, "emacs");
158 			el_set(el, EL_BIND, "^I",
159 			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
160 		}
161 	} else {
162 		INTOFF;
163 		if (el) {	/* no editing if not interactive */
164 			el_end(el);
165 			el = NULL;
166 		}
167 		if (hist) {
168 			history_end(hist);
169 			hist = NULL;
170 		}
171 		INTON;
172 	}
173 }
174 
175 
176 void
177 sethistsize(const char *hs)
178 {
179 	int histsize;
180 	HistEvent he;
181 
182 	if (hist != NULL) {
183 		if (hs == NULL || *hs == '\0' ||
184 		   (histsize = atoi(hs)) < 0)
185 			histsize = 100;
186 		history(hist, &he, H_SETSIZE, histsize);
187 		history(hist, &he, H_SETUNIQUE, 1);
188 	}
189 }
190 
191 void
192 setterm(const char *term)
193 {
194 	if (el != NULL && term != NULL)
195 		if (el_set(el, EL_TERMINAL, term) != 0) {
196 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
197 			outfmt(out2, "sh: Using dumb terminal settings.\n");
198 		}
199 }
200 
201 int
202 inputrc(int argc, char **argv)
203 {
204 	if (argc != 2) {
205 		out2str("usage: inputrc file\n");
206 		return 1;
207 	}
208 	if (el != NULL) {
209 		if (el_source(el, argv[1])) {
210 			out2str("inputrc: failed\n");
211 			return 1;
212 		} else
213 			return 0;
214 	} else {
215 		out2str("sh: inputrc ignored, not editing\n");
216 		return 1;
217 	}
218 }
219 
220 /*
221  *  This command is provided since POSIX decided to standardize
222  *  the Korn shell fc command.  Oh well...
223  */
224 int
225 histcmd(int argc, char **argv)
226 {
227 	int ch;
228 	const char * volatile editor = NULL;
229 	HistEvent he;
230 	int lflg = 0;
231 	volatile int nflg = 0, rflg = 0, sflg = 0;
232 	int i, retval;
233 	const char *firststr, *laststr;
234 	int first, last, direction;
235 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
236 	static int active = 0;
237 	struct jmploc jmploc;
238 	struct jmploc *volatile savehandler;
239 	char editfile[MAXPATHLEN + 1];
240 	FILE *efp;
241 #ifdef __GNUC__
242 	repl = NULL;	/* XXX gcc4 */
243 	efp = NULL;	/* XXX gcc4 */
244 #endif
245 
246 	if (hist == NULL)
247 		error("history not active");
248 
249 	if (argc == 1)
250 		error("missing history argument");
251 
252 	optreset = 1; optind = 1; /* initialize getopt */
253 	while (not_fcnumber(argv[optind]) &&
254 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
255 		switch ((char)ch) {
256 		case 'e':
257 			editor = optionarg;
258 			break;
259 		case 'l':
260 			lflg = 1;
261 			break;
262 		case 'n':
263 			nflg = 1;
264 			break;
265 		case 'r':
266 			rflg = 1;
267 			break;
268 		case 's':
269 			sflg = 1;
270 			break;
271 		case ':':
272 			error("option -%c expects argument", optopt);
273 			/* NOTREACHED */
274 		case '?':
275 		default:
276 			error("unknown option: -%c", optopt);
277 			/* NOTREACHED */
278 		}
279 	argc -= optind, argv += optind;
280 
281 	/*
282 	 * If executing...
283 	 */
284 	if (lflg == 0 || editor || sflg) {
285 		lflg = 0;	/* ignore */
286 		editfile[0] = '\0';
287 		/*
288 		 * Catch interrupts to reset active counter and
289 		 * cleanup temp files.
290 		 */
291 		savehandler = handler;
292 		if (setjmp(jmploc.loc)) {
293 			active = 0;
294 			if (*editfile)
295 				unlink(editfile);
296 			handler = savehandler;
297 			longjmp(handler->loc, 1);
298 		}
299 		handler = &jmploc;
300 		if (++active > MAXHISTLOOPS) {
301 			active = 0;
302 			displayhist = 0;
303 			error("called recursively too many times");
304 		}
305 		/*
306 		 * Set editor.
307 		 */
308 		if (sflg == 0) {
309 			if (editor == NULL &&
310 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
311 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
312 				editor = DEFEDITOR;
313 			if (editor[0] == '-' && editor[1] == '\0') {
314 				sflg = 1;	/* no edit */
315 				editor = NULL;
316 			}
317 		}
318 	}
319 
320 	/*
321 	 * If executing, parse [old=new] now
322 	 */
323 	if (lflg == 0 && argc > 0 &&
324 	     ((repl = strchr(argv[0], '=')) != NULL)) {
325 		pat = argv[0];
326 		*repl++ = '\0';
327 		argc--, argv++;
328 	}
329 
330 	/*
331 	 * If -s is specified, accept only one operand
332 	 */
333 	if (sflg && argc >= 2)
334 		error("too many args");
335 
336 	/*
337 	 * determine [first] and [last]
338 	 */
339 	switch (argc) {
340 	case 0:
341 		firststr = lflg ? "-16" : "-1";
342 		laststr = "-1";
343 		break;
344 	case 1:
345 		firststr = argv[0];
346 		laststr = lflg ? "-1" : argv[0];
347 		break;
348 	case 2:
349 		firststr = argv[0];
350 		laststr = argv[1];
351 		break;
352 	default:
353 		error("too many args");
354 		/* NOTREACHED */
355 	}
356 	/*
357 	 * Turn into event numbers.
358 	 */
359 	first = str_to_event(firststr, 0);
360 	last = str_to_event(laststr, 1);
361 
362 	if (rflg) {
363 		i = last;
364 		last = first;
365 		first = i;
366 	}
367 	/*
368 	 * XXX - this should not depend on the event numbers
369 	 * always increasing.  Add sequence numbers or offset
370 	 * to the history element in next (diskbased) release.
371 	 */
372 	direction = first < last ? H_PREV : H_NEXT;
373 
374 	/*
375 	 * If editing, grab a temp file.
376 	 */
377 	if (editor) {
378 		int fd;
379 		INTOFF;		/* easier */
380 		snprintf(editfile, sizeof(editfile), "%s_shXXXXXX", _PATH_TMP);
381 		if ((fd = mkstemp(editfile)) < 0)
382 			error("can't create temporary file %s", editfile);
383 		if ((efp = fdopen(fd, "w")) == NULL) {
384 			close(fd);
385 			error("can't allocate stdio buffer for temp");
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 				}
412 
413 				evalstring(strcpy(stalloc(strlen(s) + 1), s), 0);
414 				if (displayhist && hist) {
415 					/*
416 					 *  XXX what about recursive and
417 					 *  relative histnums.
418 					 */
419 					history(hist, &he, H_ENTER, s);
420 				}
421 
422 				break;
423 			} else
424 				fputs(s, efp);
425 		}
426 		/*
427 		 * At end?  (if we were to lose last, we'd sure be
428 		 * messed up).
429 		 */
430 		if (he.num == last)
431 			break;
432 	}
433 	if (editor) {
434 		char *editcmd;
435 
436 		fclose(efp);
437 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
438 		sprintf(editcmd, "%s %s", editor, editfile);
439 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
440 		INTON;
441 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
442 		unlink(editfile);
443 	}
444 
445 	if (lflg == 0 && active > 0)
446 		--active;
447 	if (displayhist)
448 		displayhist = 0;
449 	return 0;
450 }
451 
452 STATIC const char *
453 fc_replace(const char *s, char *p, char *r)
454 {
455 	char *dest;
456 	int plen = strlen(p);
457 
458 	STARTSTACKSTR(dest);
459 	while (*s) {
460 		if (*s == *p && strncmp(s, p, plen) == 0) {
461 			while (*r)
462 				STPUTC(*r++, dest);
463 			s += plen;
464 			*p = '\0';	/* so no more matches */
465 		} else
466 			STPUTC(*s++, dest);
467 	}
468 	STACKSTRNUL(dest);
469 	dest = grabstackstr(dest);
470 
471 	return (dest);
472 }
473 
474 int
475 not_fcnumber(char *s)
476 {
477 	if (s == NULL)
478 		return 0;
479         if (*s == '-')
480                 s++;
481 	return (!is_number(s));
482 }
483 
484 int
485 str_to_event(const char *str, int last)
486 {
487 	HistEvent he;
488 	const char *s = str;
489 	int relative = 0;
490 	int i, retval;
491 
492 	retval = history(hist, &he, H_FIRST);
493 	switch (*s) {
494 	case '-':
495 		relative = 1;
496 		/*FALLTHROUGH*/
497 	case '+':
498 		s++;
499 	}
500 	if (is_number(s)) {
501 		i = atoi(s);
502 		if (relative) {
503 			while (retval != -1 && i--) {
504 				retval = history(hist, &he, H_NEXT);
505 			}
506 			if (retval == -1)
507 				retval = history(hist, &he, H_LAST);
508 		} else {
509 			retval = history(hist, &he, H_NEXT_EVENT, i);
510 			if (retval == -1) {
511 				/*
512 				 * the notion of first and last is
513 				 * backwards to that of the history package
514 				 */
515 				retval = history(hist, &he,
516 						last ? H_FIRST : H_LAST);
517 			}
518 		}
519 		if (retval == -1)
520 			error("history number %s not found (internal error)",
521 			       str);
522 	} else {
523 		/*
524 		 * pattern
525 		 */
526 		retval = history(hist, &he, H_PREV_STR, str);
527 		if (retval == -1)
528 			error("history pattern not found: %s", str);
529 	}
530 	return (he.num);
531 }
532 #else
533 int
534 histcmd(int argc, char **argv)
535 {
536 	error("not compiled with history support");
537 	/* NOTREACHED */
538 }
539 int
540 inputrc(int argc, char **argv)
541 {
542 	error("not compiled with history support");
543 	/* NOTREACHED */
544 }
545 #endif
546