xref: /dragonfly/bin/sh/histedit.c (revision cf89a63b)
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  * @(#)histedit.c	8.2 (Berkeley) 5/4/95
33  * $FreeBSD: head/bin/sh/histedit.c 240541 2012-09-15 21:56:30Z jilles $
34  */
35 
36 #include <sys/param.h>
37 #include <limits.h>
38 #include <paths.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <unistd.h>
42 /*
43  * Editline and history functions (and glue).
44  */
45 #include "shell.h"
46 #include "parser.h"
47 #include "var.h"
48 #include "options.h"
49 #include "main.h"
50 #include "output.h"
51 #include "mystring.h"
52 #include "myhistedit.h"
53 #ifndef NO_HISTORY
54 #include "error.h"
55 #include "eval.h"
56 #include "memalloc.h"
57 #include "builtins.h"
58 
59 #define MAXHISTLOOPS	4	/* max recursions through fc */
60 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
61 
62 History *hist;	/* history cookie */
63 EditLine *el;	/* editline cookie */
64 int displayhist;
65 static FILE *el_in, *el_out, *el_err;
66 
67 static char *fc_replace(const char *, char *, char *);
68 static int not_fcnumber(const char *);
69 static int str_to_event(const char *, int);
70 
71 /*
72  * Set history and editing status.  Called whenever the status may
73  * have changed (figures out what to do).
74  */
75 void
76 histedit(void)
77 {
78 
79 #define editing (Eflag || Vflag)
80 
81 	if (iflag) {
82 		if (!hist) {
83 			/*
84 			 * turn history on
85 			 */
86 			INTOFF;
87 			hist = history_init();
88 			INTON;
89 
90 			if (hist != NULL)
91 				sethistsize(histsizeval());
92 			else
93 				out2fmt_flush("sh: can't initialize history\n");
94 		}
95 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
96 			/*
97 			 * turn editing on
98 			 */
99 			char *term;
100 
101 			INTOFF;
102 			if (el_in == NULL)
103 				el_in = fdopen(0, "r");
104 			if (el_err == NULL)
105 				el_err = fdopen(1, "w");
106 			if (el_out == NULL)
107 				el_out = fdopen(2, "w");
108 			if (el_in == NULL || el_err == NULL || el_out == NULL)
109 				goto bad;
110 			term = lookupvar("TERM");
111 			if (term) {
112 				if (setenv("TERM", term, 1) == -1)
113 					error("setenv: cannot set TERM=1");
114 			}
115 			else
116 				unsetenv("TERM");
117 			el = el_init(arg0, el_in, el_out, el_err);
118 			if (el != NULL) {
119 				if (hist)
120 					el_set(el, EL_HIST, history, hist);
121 				el_set(el, EL_PROMPT, getprompt);
122 				el_set(el, EL_ADDFN, "rl-complete",
123 				    "ReadLine compatible completion function",
124 				    _el_fn_complete);
125 			} else {
126 bad:
127 				out2fmt_flush("sh: can't initialize editing\n");
128 			}
129 			INTON;
130 		} else if (!editing && el) {
131 			INTOFF;
132 			el_end(el);
133 			el = NULL;
134 			INTON;
135 		}
136 		if (el) {
137 			if (Vflag)
138 				el_set(el, EL_EDITOR, "vi");
139 			else if (Eflag)
140 				el_set(el, EL_EDITOR, "emacs");
141 			el_set(el, EL_BIND, "^I",
142 			    tabcomplete ? "rl-complete" : "ed-insert", NULL);
143 			el_source(el, NULL);
144 		}
145 	} else {
146 		INTOFF;
147 		if (el) {	/* no editing if not interactive */
148 			el_end(el);
149 			el = NULL;
150 		}
151 		if (hist) {
152 			history_end(hist);
153 			hist = NULL;
154 		}
155 		INTON;
156 	}
157 }
158 
159 
160 void
161 sethistsize(const char *hs)
162 {
163 	int histsize;
164 	HistEvent he;
165 
166 	if (hist != NULL) {
167 		if (hs == NULL || *hs == '\0' ||
168 		   (histsize = atoi(hs)) < 0)
169 			histsize = 100;
170 		history(hist, &he, H_SETSIZE, histsize);
171 		history(hist, &he, H_SETUNIQUE, 1);
172 	}
173 }
174 
175 void
176 setterm(const char *term)
177 {
178 	if (rootshell && el != NULL && term != NULL)
179 		el_set(el, EL_TERMINAL, term);
180 }
181 
182 int
183 histcmd(int argc, char **argv __unused)
184 {
185 	int ch;
186 	const char *volatile editor = NULL;
187 	HistEvent he;
188 	volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
189 	int i, retval;
190 	const char *firststr = NULL, *laststr = NULL;
191 	int first, last, direction;
192 	char *pat = NULL, *repl = NULL;
193 	static int active = 0;
194 	struct jmploc jmploc;
195 	struct jmploc *savehandler;
196 	char editfilestr[PATH_MAX];
197 	char *volatile editfile;
198 	FILE *efp = NULL;
199 	int oldhistnum;
200 
201 	if (hist == NULL)
202 		error("history not active");
203 
204 	if (argc == 1)
205 		error("missing history argument");
206 
207 	while (not_fcnumber(*argptr) && (ch = nextopt("e:lnrs")) != '\0')
208 		switch ((char)ch) {
209 		case 'e':
210 			editor = shoptarg;
211 			break;
212 		case 'l':
213 			lflg = 1;
214 			break;
215 		case 'n':
216 			nflg = 1;
217 			break;
218 		case 'r':
219 			rflg = 1;
220 			break;
221 		case 's':
222 			sflg = 1;
223 			break;
224 		}
225 
226 	savehandler = handler;
227 	/*
228 	 * If executing...
229 	 */
230 	if (lflg == 0 || editor || sflg) {
231 		lflg = 0;	/* ignore */
232 		editfile = NULL;
233 		/*
234 		 * Catch interrupts to reset active counter and
235 		 * cleanup temp files.
236 		 */
237 		if (setjmp(jmploc.loc)) {
238 			active = 0;
239 			if (editfile)
240 				unlink(editfile);
241 			handler = savehandler;
242 			longjmp(handler->loc, 1);
243 		}
244 		handler = &jmploc;
245 		if (++active > MAXHISTLOOPS) {
246 			active = 0;
247 			displayhist = 0;
248 			error("called recursively too many times");
249 		}
250 		/*
251 		 * Set editor.
252 		 */
253 		if (sflg == 0) {
254 			if (editor == NULL &&
255 			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
256 			    (editor = bltinlookup("EDITOR", 1)) == NULL)
257 				editor = DEFEDITOR;
258 			if (editor[0] == '-' && editor[1] == '\0') {
259 				sflg = 1;	/* no edit */
260 				editor = NULL;
261 			}
262 		}
263 	}
264 
265 	/*
266 	 * If executing, parse [old=new] now
267 	 */
268 	if (lflg == 0 && *argptr != NULL &&
269 	     ((repl = strchr(*argptr, '=')) != NULL)) {
270 		pat = *argptr;
271 		*repl++ = '\0';
272 		argptr++;
273 	}
274 	/*
275 	 * determine [first] and [last]
276 	 */
277 	if (*argptr == NULL) {
278 		firststr = lflg ? "-16" : "-1";
279 		laststr = "-1";
280 	} else if (argptr[1] == NULL) {
281 		firststr = argptr[0];
282 		laststr = lflg ? "-1" : argptr[0];
283 	} else if (argptr[2] == NULL) {
284 		firststr = argptr[0];
285 		laststr = argptr[1];
286 	} else
287 		error("too many arguments");
288 	/*
289 	 * Turn into event numbers.
290 	 */
291 	first = str_to_event(firststr, 0);
292 	last = str_to_event(laststr, 1);
293 
294 	if (rflg) {
295 		i = last;
296 		last = first;
297 		first = i;
298 	}
299 	/*
300 	 * XXX - this should not depend on the event numbers
301 	 * always increasing.  Add sequence numbers or offset
302 	 * to the history element in next (diskbased) release.
303 	 */
304 	direction = first < last ? H_PREV : H_NEXT;
305 
306 	/*
307 	 * If editing, grab a temp file.
308 	 */
309 	if (editor) {
310 		int fd;
311 		INTOFF;		/* easier */
312 		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
313 		if ((fd = mkstemp(editfilestr)) < 0)
314 			error("can't create temporary file %s", editfile);
315 		editfile = editfilestr;
316 		if ((efp = fdopen(fd, "w")) == NULL) {
317 			close(fd);
318 			error("Out of space");
319 		}
320 	}
321 
322 	/*
323 	 * Loop through selected history events.  If listing or executing,
324 	 * do it now.  Otherwise, put into temp file and call the editor
325 	 * after.
326 	 *
327 	 * The history interface needs rethinking, as the following
328 	 * convolutions will demonstrate.
329 	 */
330 	history(hist, &he, H_FIRST);
331 	retval = history(hist, &he, H_NEXT_EVENT, first);
332 	for (;retval != -1; retval = history(hist, &he, direction)) {
333 		if (lflg) {
334 			if (!nflg)
335 				out1fmt("%5d ", he.num);
336 			out1str(he.str);
337 		} else {
338 			char *s = pat ?
339 			   fc_replace(he.str, pat, repl) :
340 			   __DECONST(char *, he.str);
341 
342 			if (sflg) {
343 				if (displayhist) {
344 					out2str(s);
345 					flushout(out2);
346 				}
347 				evalstring(s, 0);
348 				if (displayhist && hist) {
349 					/*
350 					 *  XXX what about recursive and
351 					 *  relative histnums.
352 					 */
353 					oldhistnum = he.num;
354 					history(hist, &he, H_ENTER, s);
355 					/*
356 					 * XXX H_ENTER moves the internal
357 					 * cursor, set it back to the current
358 					 * entry.
359 					 */
360 					retval = history(hist, &he,
361 					    H_NEXT_EVENT, oldhistnum);
362 				}
363 			} else
364 				fputs(s, efp);
365 		}
366 		/*
367 		 * At end?  (if we were to lose last, we'd sure be
368 		 * messed up).
369 		 */
370 		if (he.num == last)
371 			break;
372 	}
373 	if (editor) {
374 		char *editcmd;
375 
376 		fclose(efp);
377 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
378 		sprintf(editcmd, "%s %s", editor, editfile);
379 		evalstring(editcmd, 0);	/* XXX - should use no JC command */
380 		INTON;
381 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
382 		unlink(editfile);
383 	}
384 
385 	if (lflg == 0 && active > 0)
386 		--active;
387 	if (displayhist)
388 		displayhist = 0;
389 	handler = savehandler;
390 	return 0;
391 }
392 
393 static char *
394 fc_replace(const char *s, char *p, char *r)
395 {
396 	char *dest;
397 	int plen = strlen(p);
398 
399 	STARTSTACKSTR(dest);
400 	while (*s) {
401 		if (*s == *p && strncmp(s, p, plen) == 0) {
402 			STPUTS(r, dest);
403 			s += plen;
404 			*p = '\0';	/* so no more matches */
405 		} else
406 			STPUTC(*s++, dest);
407 	}
408 	STPUTC('\0', dest);
409 	dest = grabstackstr(dest);
410 
411 	return (dest);
412 }
413 
414 static int
415 not_fcnumber(const char *s)
416 {
417 	if (s == NULL)
418 		return (0);
419 	if (*s == '-')
420 		s++;
421 	return (!is_number(s));
422 }
423 
424 static int
425 str_to_event(const char *str, int last)
426 {
427 	HistEvent he;
428 	const char *s = str;
429 	int relative = 0;
430 	int i, retval;
431 
432 	retval = history(hist, &he, H_FIRST);
433 	switch (*s) {
434 	case '-':
435 		relative = 1;
436 		/*FALLTHROUGH*/
437 	case '+':
438 		s++;
439 	}
440 	if (is_number(s)) {
441 		i = atoi(s);
442 		if (relative) {
443 			while (retval != -1 && i--) {
444 				retval = history(hist, &he, H_NEXT);
445 			}
446 			if (retval == -1)
447 				retval = history(hist, &he, H_LAST);
448 		} else {
449 			retval = history(hist, &he, H_NEXT_EVENT, i);
450 			if (retval == -1) {
451 				/*
452 				 * the notion of first and last is
453 				 * backwards to that of the history package
454 				 */
455 				retval = history(hist, &he, last ? H_FIRST : H_LAST);
456 			}
457 		}
458 		if (retval == -1)
459 			error("history number %s not found (internal error)",
460 			       str);
461 	} else {
462 		/*
463 		 * pattern
464 		 */
465 		retval = history(hist, &he, H_PREV_STR, str);
466 		if (retval == -1)
467 			error("history pattern not found: %s", str);
468 	}
469 	return (he.num);
470 }
471 
472 int
473 bindcmd(int argc, char **argv)
474 {
475 
476 	if (el == NULL)
477 		error("line editing is disabled");
478 	return (el_parse(el, argc, (const char **)argv));
479 }
480 
481 #else
482 #include "error.h"
483 
484 int
485 histcmd(int argc __unused, char **argv __unused)
486 {
487 
488 	error("not compiled with history support");
489 	/*NOTREACHED*/
490 	return (0);
491 }
492 
493 int
494 bindcmd(int argc __unused, char **argv __unused)
495 {
496 
497 	error("not compiled with line editing support");
498 	return (0);
499 }
500 #endif
501