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