histedit.c revision 208755
1339631Sphilip/*-
2339631Sphilip * Copyright (c) 1993
3192886Sedwin *	The Regents of the University of California.  All rights reserved.
4192886Sedwin *
52744Swollman * This code is derived from software contributed to Berkeley by
620091Swollman * Kenneth Almquist.
720091Swollman *
8339631Sphilip * Redistribution and use in source and binary forms, with or without
9149511Swollman * modification, are permitted provided that the following conditions
10149511Swollman * are met:
11149511Swollman * 1. Redistributions of source code must retain the above copyright
122744Swollman *    notice, this list of conditions and the following disclaimer.
13307362Sbapt * 2. Redistributions in binary form must reproduce the above copyright
14307362Sbapt *    notice, this list of conditions and the following disclaimer in the
15307362Sbapt *    documentation and/or other materials provided with the distribution.
16307362Sbapt * 4. Neither the name of the University nor the names of its contributors
17307362Sbapt *    may be used to endorse or promote products derived from this software
18307362Sbapt *    without specific prior written permission.
19307362Sbapt *
202744Swollman * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2120091Swollman * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2220091Swollman * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2343009Swollman * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24270817Spluknet * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25199405Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2643009Swollman * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27199405Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2843009Swollman * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2920091Swollman * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3020091Swollman * SUCH DAMAGE.
3120091Swollman */
322744Swollman
332744Swollman#ifndef lint
342744Swollman#if 0
352744Swollmanstatic char sccsid[] = "@(#)histedit.c	8.2 (Berkeley) 5/4/95";
362744Swollman#endif
37307362Sbapt#endif /* not lint */
3875264Swollman#include <sys/cdefs.h>
3975264Swollman__FBSDID("$FreeBSD: head/bin/sh/histedit.c 208755 2010-06-02 19:16:58Z jilles $");
4075264Swollman
41307362Sbapt#include <sys/param.h>
4275264Swollman#include <limits.h>
43257697Sedwin#include <paths.h>
442744Swollman#include <stdio.h>
452744Swollman#include <stdlib.h>
462744Swollman#include <unistd.h>
472744Swollman/*
482744Swollman * Editline and history functions (and glue).
492744Swollman */
502744Swollman#include "shell.h"
512744Swollman#include "parser.h"
52307362Sbapt#include "var.h"
532744Swollman#include "options.h"
54307362Sbapt#include "main.h"
55307362Sbapt#include "output.h"
56307362Sbapt#include "mystring.h"
57307362Sbapt#ifndef NO_HISTORY
58307362Sbapt#include "myhistedit.h"
59307362Sbapt#include "error.h"
60307362Sbapt#include "eval.h"
61307362Sbapt#include "memalloc.h"
62307362Sbapt
63307362Sbapt#define MAXHISTLOOPS	4	/* max recursions through fc */
64307362Sbapt#define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
65307362Sbapt
66307362SbaptHistory *hist;	/* history cookie */
67307362SbaptEditLine *el;	/* editline cookie */
68307362Sbaptint displayhist;
69307362Sbaptstatic FILE *el_in, *el_out, *el_err;
70307362Sbapt
71307362SbaptSTATIC char *fc_replace(const char *, char *, char *);
72307362Sbapt
73307362Sbapt/*
74307362Sbapt * Set history and editing status.  Called whenever the status may
75307362Sbapt * have changed (figures out what to do).
76307362Sbapt */
77307362Sbaptvoid
78307362Sbapthistedit(void)
79307362Sbapt{
80
81#define editing (Eflag || Vflag)
82
83	if (iflag) {
84		if (!hist) {
85			/*
86			 * turn history on
87			 */
88			INTOFF;
89			hist = history_init();
90			INTON;
91
92			if (hist != NULL)
93				sethistsize(histsizeval());
94			else
95				out2fmt_flush("sh: can't initialize history\n");
96		}
97		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
98			/*
99			 * turn editing on
100			 */
101			char *term;
102
103			INTOFF;
104			if (el_in == NULL)
105				el_in = fdopen(0, "r");
106			if (el_err == NULL)
107				el_err = fdopen(1, "w");
108			if (el_out == NULL)
109				el_out = fdopen(2, "w");
110			if (el_in == NULL || el_err == NULL || el_out == NULL)
111				goto bad;
112			term = lookupvar("TERM");
113			if (term)
114				setenv("TERM", term, 1);
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			} else {
123bad:
124				out2fmt_flush("sh: can't initialize editing\n");
125			}
126			INTON;
127		} else if (!editing && el) {
128			INTOFF;
129			el_end(el);
130			el = NULL;
131			INTON;
132		}
133		if (el) {
134			if (Vflag)
135				el_set(el, EL_EDITOR, "vi");
136			else if (Eflag)
137				el_set(el, EL_EDITOR, "emacs");
138			el_source(el, NULL);
139		}
140	} else {
141		INTOFF;
142		if (el) {	/* no editing if not interactive */
143			el_end(el);
144			el = NULL;
145		}
146		if (hist) {
147			history_end(hist);
148			hist = NULL;
149		}
150		INTON;
151	}
152}
153
154
155void
156sethistsize(hs)
157	const char *hs;
158{
159	int histsize;
160	HistEvent he;
161
162	if (hist != NULL) {
163		if (hs == NULL || *hs == '\0' ||
164		   (histsize = atoi(hs)) < 0)
165			histsize = 100;
166		history(hist, &he, H_SETSIZE, histsize);
167	}
168}
169
170void
171setterm(const char *term)
172{
173	if (rootshell && el != NULL && term != NULL)
174		el_set(el, EL_TERMINAL, term);
175}
176
177int
178histcmd(int argc, char **argv)
179{
180	int ch;
181	const char *editor = NULL;
182	HistEvent he;
183	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
184	int i, retval;
185	const char *firststr, *laststr;
186	int first, last, direction;
187	char *pat = NULL, *repl = NULL;
188	static int active = 0;
189	struct jmploc jmploc;
190	struct jmploc *savehandler;
191	char editfilestr[PATH_MAX];
192	char *volatile editfile;
193	FILE *efp = NULL;
194	int oldhistnum;
195
196	if (hist == NULL)
197		error("history not active");
198
199	if (argc == 1)
200		error("missing history argument");
201
202	optreset = 1; optind = 1; /* initialize getopt */
203	opterr = 0;
204	while (not_fcnumber(argv[optind]) &&
205	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
206		switch ((char)ch) {
207		case 'e':
208			editor = optarg;
209			break;
210		case 'l':
211			lflg = 1;
212			break;
213		case 'n':
214			nflg = 1;
215			break;
216		case 'r':
217			rflg = 1;
218			break;
219		case 's':
220			sflg = 1;
221			break;
222		case ':':
223			error("option -%c expects argument", optopt);
224		case '?':
225		default:
226			error("unknown option: -%c", optopt);
227		}
228	argc -= optind, argv += optind;
229
230	/*
231	 * If executing...
232	 */
233	if (lflg == 0 || editor || sflg) {
234		lflg = 0;	/* ignore */
235		editfile = NULL;
236		/*
237		 * Catch interrupts to reset active counter and
238		 * cleanup temp files.
239		 */
240		savehandler = handler;
241		if (setjmp(jmploc.loc)) {
242			active = 0;
243			if (editfile)
244				unlink(editfile);
245			handler = savehandler;
246			longjmp(handler->loc, 1);
247		}
248		handler = &jmploc;
249		if (++active > MAXHISTLOOPS) {
250			active = 0;
251			displayhist = 0;
252			error("called recursively too many times");
253		}
254		/*
255		 * Set editor.
256		 */
257		if (sflg == 0) {
258			if (editor == NULL &&
259			    (editor = bltinlookup("FCEDIT", 1)) == NULL &&
260			    (editor = bltinlookup("EDITOR", 1)) == NULL)
261				editor = DEFEDITOR;
262			if (editor[0] == '-' && editor[1] == '\0') {
263				sflg = 1;	/* no edit */
264				editor = NULL;
265			}
266		}
267	}
268
269	/*
270	 * If executing, parse [old=new] now
271	 */
272	if (lflg == 0 && argc > 0 &&
273	     ((repl = strchr(argv[0], '=')) != NULL)) {
274		pat = argv[0];
275		*repl++ = '\0';
276		argc--, argv++;
277	}
278	/*
279	 * determine [first] and [last]
280	 */
281	switch (argc) {
282	case 0:
283		firststr = lflg ? "-16" : "-1";
284		laststr = "-1";
285		break;
286	case 1:
287		firststr = argv[0];
288		laststr = lflg ? "-1" : argv[0];
289		break;
290	case 2:
291		firststr = argv[0];
292		laststr = argv[1];
293		break;
294	default:
295		error("too many args");
296	}
297	/*
298	 * Turn into event numbers.
299	 */
300	first = str_to_event(firststr, 0);
301	last = str_to_event(laststr, 1);
302
303	if (rflg) {
304		i = last;
305		last = first;
306		first = i;
307	}
308	/*
309	 * XXX - this should not depend on the event numbers
310	 * always increasing.  Add sequence numbers or offset
311	 * to the history element in next (diskbased) release.
312	 */
313	direction = first < last ? H_PREV : H_NEXT;
314
315	/*
316	 * If editing, grab a temp file.
317	 */
318	if (editor) {
319		int fd;
320		INTOFF;		/* easier */
321		sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
322		if ((fd = mkstemp(editfilestr)) < 0)
323			error("can't create temporary file %s", editfile);
324		editfile = editfilestr;
325		if ((efp = fdopen(fd, "w")) == NULL) {
326			close(fd);
327			error("can't allocate stdio buffer for temp");
328		}
329	}
330
331	/*
332	 * Loop through selected history events.  If listing or executing,
333	 * do it now.  Otherwise, put into temp file and call the editor
334	 * after.
335	 *
336	 * The history interface needs rethinking, as the following
337	 * convolutions will demonstrate.
338	 */
339	history(hist, &he, H_FIRST);
340	retval = history(hist, &he, H_NEXT_EVENT, first);
341	for (;retval != -1; retval = history(hist, &he, direction)) {
342		if (lflg) {
343			if (!nflg)
344				out1fmt("%5d ", he.num);
345			out1str(he.str);
346		} else {
347			char *s = pat ?
348			   fc_replace(he.str, pat, repl) : (char *)he.str;
349
350			if (sflg) {
351				if (displayhist) {
352					out2str(s);
353					flushout(out2);
354				}
355				evalstring(s, 0);
356				if (displayhist && hist) {
357					/*
358					 *  XXX what about recursive and
359					 *  relative histnums.
360					 */
361					oldhistnum = he.num;
362					history(hist, &he, H_ENTER, s);
363					/*
364					 * XXX H_ENTER moves the internal
365					 * cursor, set it back to the current
366					 * entry.
367					 */
368					retval = history(hist, &he,
369					    H_NEXT_EVENT, oldhistnum);
370				}
371			} else
372				fputs(s, efp);
373		}
374		/*
375		 * At end?  (if we were to lose last, we'd sure be
376		 * messed up).
377		 */
378		if (he.num == last)
379			break;
380	}
381	if (editor) {
382		char *editcmd;
383
384		fclose(efp);
385		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
386		sprintf(editcmd, "%s %s", editor, editfile);
387		evalstring(editcmd, 0);	/* XXX - should use no JC command */
388		INTON;
389		readcmdfile(editfile);	/* XXX - should read back - quick tst */
390		unlink(editfile);
391	}
392
393	if (lflg == 0 && active > 0)
394		--active;
395	if (displayhist)
396		displayhist = 0;
397	return 0;
398}
399
400STATIC char *
401fc_replace(const char *s, char *p, char *r)
402{
403	char *dest;
404	int plen = strlen(p);
405
406	STARTSTACKSTR(dest);
407	while (*s) {
408		if (*s == *p && strncmp(s, p, plen) == 0) {
409			while (*r)
410				STPUTC(*r++, dest);
411			s += plen;
412			*p = '\0';	/* so no more matches */
413		} else
414			STPUTC(*s++, dest);
415	}
416	STACKSTRNUL(dest);
417	dest = grabstackstr(dest);
418
419	return (dest);
420}
421
422int
423not_fcnumber(const char *s)
424{
425	if (s == NULL)
426		return (0);
427	if (*s == '-')
428		s++;
429	return (!is_number(s));
430}
431
432int
433str_to_event(const char *str, int last)
434{
435	HistEvent he;
436	const char *s = str;
437	int relative = 0;
438	int i, retval;
439
440	retval = history(hist, &he, H_FIRST);
441	switch (*s) {
442	case '-':
443		relative = 1;
444		/*FALLTHROUGH*/
445	case '+':
446		s++;
447	}
448	if (is_number(s)) {
449		i = atoi(s);
450		if (relative) {
451			while (retval != -1 && i--) {
452				retval = history(hist, &he, H_NEXT);
453			}
454			if (retval == -1)
455				retval = history(hist, &he, H_LAST);
456		} else {
457			retval = history(hist, &he, H_NEXT_EVENT, i);
458			if (retval == -1) {
459				/*
460				 * the notion of first and last is
461				 * backwards to that of the history package
462				 */
463				retval = history(hist, &he, last ? H_FIRST : H_LAST);
464			}
465		}
466		if (retval == -1)
467			error("history number %s not found (internal error)",
468			       str);
469	} else {
470		/*
471		 * pattern
472		 */
473		retval = history(hist, &he, H_PREV_STR, str);
474		if (retval == -1)
475			error("history pattern not found: %s", str);
476	}
477	return (he.num);
478}
479
480int
481bindcmd(int argc, char **argv)
482{
483
484	if (el == NULL)
485		error("line editing is disabled");
486	return (el_parse(el, argc, (const char **)argv));
487}
488
489#else
490#include "error.h"
491
492int
493histcmd(int argc, char **argv)
494{
495
496	error("not compiled with history support");
497	/*NOTREACHED*/
498	return (0);
499}
500
501int
502bindcmd(int argc, char **argv)
503{
504
505	error("not compiled with line editing support");
506	return (0);
507}
508#endif
509