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