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