Initial import from FreeBSD RELENG_4:
[dragonfly.git] / bin / sh / histedit.c
CommitLineData
984263bc
MD
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. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38#if 0
39static char sccsid[] = "@(#)histedit.c 8.2 (Berkeley) 5/4/95";
40#endif
41#endif /* not lint */
42#include <sys/cdefs.h>
43__FBSDID("$FreeBSD: src/bin/sh/histedit.c,v 1.13.2.4 2002/08/27 01:36:28 tjr Exp $");
44
45#include <sys/param.h>
46#include <limits.h>
47#include <paths.h>
48#include <stdio.h>
49#include <stdlib.h>
50#include <unistd.h>
51/*
52 * Editline and history functions (and glue).
53 */
54#include "shell.h"
55#include "parser.h"
56#include "var.h"
57#include "options.h"
58#include "main.h"
59#include "output.h"
60#include "mystring.h"
61#ifndef NO_HISTORY
62#include "myhistedit.h"
63#include "error.h"
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
70History *hist; /* history cookie */
71EditLine *el; /* editline cookie */
72int displayhist;
73static FILE *el_in, *el_out;
74
75STATIC char *fc_replace(const char *, char *, char *);
76
77/*
78 * Set history and editing status. Called whenever the status may
79 * have changed (figures out what to do).
80 */
81void
82histedit(void)
83{
84
85#define editing (Eflag || Vflag)
86
87 if (iflag) {
88 if (!hist) {
89 /*
90 * turn history on
91 */
92 INTOFF;
93 hist = history_init();
94 INTON;
95
96 if (hist != NULL)
97 sethistsize(histsizeval());
98 else
99 out2str("sh: can't initialize history\n");
100 }
101 if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
102 /*
103 * turn editing on
104 */
105 INTOFF;
106 if (el_in == NULL)
107 el_in = fdopen(0, "r");
108 if (el_out == NULL)
109 el_out = fdopen(2, "w");
110 if (el_in == NULL || el_out == NULL)
111 goto bad;
112 el = el_init(arg0, el_in, el_out);
113 if (el != NULL) {
114 if (hist)
115 el_set(el, EL_HIST, history, hist);
116 el_set(el, EL_PROMPT, getprompt);
117 } else {
118bad:
119 out2str("sh: can't initialize editing\n");
120 }
121 INTON;
122 } else if (!editing && el) {
123 INTOFF;
124 el_end(el);
125 el = NULL;
126 INTON;
127 }
128 if (el) {
129 if (Vflag)
130 el_set(el, EL_EDITOR, "vi");
131 else if (Eflag)
132 el_set(el, EL_EDITOR, "emacs");
133 el_source(el, NULL);
134 }
135 } else {
136 INTOFF;
137 if (el) { /* no editing if not interactive */
138 el_end(el);
139 el = NULL;
140 }
141 if (hist) {
142 history_end(hist);
143 hist = NULL;
144 }
145 INTON;
146 }
147}
148
149
150void
151sethistsize(hs)
152 const char *hs;
153{
154 int histsize;
155
156 if (hist != NULL) {
157 if (hs == NULL || *hs == '\0' ||
158 (histsize = atoi(hs)) < 0)
159 histsize = 100;
160 history(hist, H_EVENT, histsize);
161 }
162}
163
164/*
165 * This command is provided since POSIX decided to standardize
166 * the Korn shell fc command. Oh well...
167 */
168int
169histcmd(int argc, char **argv)
170{
171 int ch;
172 char *editor = NULL;
173 const HistEvent *he;
174 int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
175 int i;
176 char *firststr, *laststr;
177 int first, last, direction;
178 char *pat = NULL, *repl; /* ksh "fc old=new" crap */
179 static int active = 0;
180 struct jmploc jmploc;
181 struct jmploc *volatile savehandler;
182 char editfile[PATH_MAX];
183 FILE *efp;
184 int oldhistnum;
185#ifdef __GNUC__
186 /* Avoid longjmp clobbering */
187 (void) &editor;
188 (void) &lflg;
189 (void) &nflg;
190 (void) &rflg;
191 (void) &sflg;
192 (void) &firststr;
193 (void) &laststr;
194 (void) &pat;
195 (void) &repl;
196 (void) &efp;
197 (void) &argc;
198 (void) &argv;
199#endif
200
201 if (hist == NULL)
202 error("history not active");
203
204 if (argc == 1)
205 error("missing history argument");
206
207 optreset = 1; optind = 1; /* initialize getopt */
208 opterr = 0;
209 while (not_fcnumber(argv[optind]) &&
210 (ch = getopt(argc, argv, ":e:lnrs")) != -1)
211 switch ((char)ch) {
212 case 'e':
213 editor = optarg;
214 break;
215 case 'l':
216 lflg = 1;
217 break;
218 case 'n':
219 nflg = 1;
220 break;
221 case 'r':
222 rflg = 1;
223 break;
224 case 's':
225 sflg = 1;
226 break;
227 case ':':
228 error("option -%c expects argument", optopt);
229 case '?':
230 default:
231 error("unknown option: -%c", optopt);
232 }
233 argc -= optind, argv += optind;
234
235 /*
236 * If executing...
237 */
238 if (lflg == 0 || editor || sflg) {
239 lflg = 0; /* ignore */
240 editfile[0] = '\0';
241 /*
242 * Catch interrupts to reset active counter and
243 * cleanup temp files.
244 */
245 if (setjmp(jmploc.loc)) {
246 active = 0;
247 if (*editfile)
248 unlink(editfile);
249 handler = savehandler;
250 longjmp(handler->loc, 1);
251 }
252 savehandler = handler;
253 handler = &jmploc;
254 if (++active > MAXHISTLOOPS) {
255 active = 0;
256 displayhist = 0;
257 error("called recursively too many times");
258 }
259 /*
260 * Set editor.
261 */
262 if (sflg == 0) {
263 if (editor == NULL &&
264 (editor = bltinlookup("FCEDIT", 1)) == NULL &&
265 (editor = bltinlookup("EDITOR", 1)) == NULL)
266 editor = DEFEDITOR;
267 if (editor[0] == '-' && editor[1] == '\0') {
268 sflg = 1; /* no edit */
269 editor = NULL;
270 }
271 }
272 }
273
274 /*
275 * If executing, parse [old=new] now
276 */
277 if (lflg == 0 && argc > 0 &&
278 ((repl = strchr(argv[0], '=')) != NULL)) {
279 pat = argv[0];
280 *repl++ = '\0';
281 argc--, argv++;
282 }
283 /*
284 * determine [first] and [last]
285 */
286 switch (argc) {
287 case 0:
288 firststr = lflg ? "-16" : "-1";
289 laststr = "-1";
290 break;
291 case 1:
292 firststr = argv[0];
293 laststr = lflg ? "-1" : argv[0];
294 break;
295 case 2:
296 firststr = argv[0];
297 laststr = argv[1];
298 break;
299 default:
300 error("too many args");
301 }
302 /*
303 * Turn into event numbers.
304 */
305 first = str_to_event(firststr, 0);
306 last = str_to_event(laststr, 1);
307
308 if (rflg) {
309 i = last;
310 last = first;
311 first = i;
312 }
313 /*
314 * XXX - this should not depend on the event numbers
315 * always increasing. Add sequence numbers or offset
316 * to the history element in next (diskbased) release.
317 */
318 direction = first < last ? H_PREV : H_NEXT;
319
320 /*
321 * If editing, grab a temp file.
322 */
323 if (editor) {
324 int fd;
325 INTOFF; /* easier */
326 sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
327 if ((fd = mkstemp(editfile)) < 0)
328 error("can't create temporary file %s", editfile);
329 if ((efp = fdopen(fd, "w")) == NULL) {
330 close(fd);
331 error("can't allocate stdio buffer for temp");
332 }
333 }
334
335 /*
336 * Loop through selected history events. If listing or executing,
337 * do it now. Otherwise, put into temp file and call the editor
338 * after.
339 *
340 * The history interface needs rethinking, as the following
341 * convolutions will demonstrate.
342 */
343 history(hist, H_FIRST);
344 he = history(hist, H_NEXT_EVENT, first);
345 for (;he != NULL; he = history(hist, direction)) {
346 if (lflg) {
347 if (!nflg)
348 out1fmt("%5d ", he->num);
349 out1str(he->str);
350 } else {
351 char *s = pat ?
352 fc_replace(he->str, pat, repl) : (char *)he->str;
353
354 if (sflg) {
355 if (displayhist) {
356 out2str(s);
357 }
358 evalstring(s);
359 if (displayhist && hist) {
360 /*
361 * XXX what about recursive and
362 * relative histnums.
363 */
364 history(hist, H_ENTER, s);
365 }
366 } else
367 fputs(s, efp);
368 }
369 /*
370 * At end? (if we were to loose last, we'd sure be
371 * messed up).
372 */
373 if (he->num == last)
374 break;
375 }
376 if (editor) {
377 char *editcmd;
378
379 fclose(efp);
380 editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
381 sprintf(editcmd, "%s %s", editor, editfile);
382 evalstring(editcmd); /* XXX - should use no JC command */
383 INTON;
384 readcmdfile(editfile); /* XXX - should read back - quick tst */
385 unlink(editfile);
386 }
387
388 if (lflg == 0 && active > 0)
389 --active;
390 if (displayhist)
391 displayhist = 0;
392 return 0;
393}
394
395STATIC char *
396fc_replace(const char *s, char *p, char *r)
397{
398 char *dest;
399 int plen = strlen(p);
400
401 STARTSTACKSTR(dest);
402 while (*s) {
403 if (*s == *p && strncmp(s, p, plen) == 0) {
404 while (*r)
405 STPUTC(*r++, dest);
406 s += plen;
407 *p = '\0'; /* so no more matches */
408 } else
409 STPUTC(*s++, dest);
410 }
411 STACKSTRNUL(dest);
412 dest = grabstackstr(dest);
413
414 return (dest);
415}
416
417int
418not_fcnumber(char *s)
419{
420 if (s == NULL)
421 return (0);
422 if (*s == '-')
423 s++;
424 return (!is_number(s));
425}
426
427int
428str_to_event(char *str, int last)
429{
430 const HistEvent *he;
431 char *s = str;
432 int relative = 0;
433 int i;
434
435 he = history(hist, H_FIRST);
436 switch (*s) {
437 case '-':
438 relative = 1;
439 /*FALLTHROUGH*/
440 case '+':
441 s++;
442 }
443 if (is_number(s)) {
444 i = atoi(s);
445 if (relative) {
446 while (he != NULL && i--) {
447 he = history(hist, H_NEXT);
448 }
449 if (he == NULL)
450 he = history(hist, H_LAST);
451 } else {
452 he = history(hist, H_NEXT_EVENT, i);
453 if (he == NULL) {
454 /*
455 * the notion of first and last is
456 * backwards to that of the history package
457 */
458 he = history(hist, last ? H_FIRST : H_LAST);
459 }
460 }
461 if (he == NULL)
462 error("history number %s not found (internal error)",
463 str);
464 } else {
465 /*
466 * pattern
467 */
468 he = history(hist, H_PREV_STR, str);
469 if (he == NULL)
470 error("history pattern not found: %s", str);
471 }
472 return (he->num);
473}
474
475int
476bindcmd(int argc, char **argv)
477{
478
479 if (el == NULL)
480 error("line editing is disabled");
481 return (el_parse(el, argc, argv));
482}
483
484#else
485#include "error.h"
486
487int
488histcmd(int argc, char **argv)
489{
490
491 error("not compiled with history support");
492 /*NOTREACHED*/
493 return (0);
494}
495
496int
497bindcmd(int argc, char **argv)
498{
499
500 error("not compiled with line editing support");
501 return (0);
502}
503#endif