Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / bin / sh / histedit.c
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  * @(#)histedit.c       8.2 (Berkeley) 5/4/95
37  * $FreeBSD: src/bin/sh/histedit.c,v 1.13.2.4 2002/08/27 01:36:28 tjr Exp $
38  * $DragonFly: src/bin/sh/histedit.c,v 1.2 2003/06/17 04:22:50 dillon Exp $
39  */
40
41 #include <sys/param.h>
42 #include <limits.h>
43 #include <paths.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <unistd.h>
47 /*
48  * Editline and history functions (and glue).
49  */
50 #include "shell.h"
51 #include "parser.h"
52 #include "var.h"
53 #include "options.h"
54 #include "main.h"
55 #include "output.h"
56 #include "mystring.h"
57 #ifndef NO_HISTORY
58 #include "myhistedit.h"
59 #include "error.h"
60 #include "eval.h"
61 #include "memalloc.h"
62
63 #define MAXHISTLOOPS    4       /* max recursions through fc */
64 #define DEFEDITOR       "ed"    /* default editor *should* be $EDITOR */
65
66 History *hist;  /* history cookie */
67 EditLine *el;   /* editline cookie */
68 int displayhist;
69 static FILE *el_in, *el_out;
70
71 STATIC char *fc_replace(const char *, char *, char *);
72
73 /*
74  * Set history and editing status.  Called whenever the status may
75  * have changed (figures out what to do).
76  */
77 void
78 histedit(void)
79 {
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                                 out2str("sh: can't initialize history\n");
96                 }
97                 if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
98                         /*
99                          * turn editing on
100                          */
101                         INTOFF;
102                         if (el_in == NULL)
103                                 el_in = fdopen(0, "r");
104                         if (el_out == NULL)
105                                 el_out = fdopen(2, "w");
106                         if (el_in == NULL || el_out == NULL)
107                                 goto bad;
108                         el = el_init(arg0, el_in, el_out);
109                         if (el != NULL) {
110                                 if (hist)
111                                         el_set(el, EL_HIST, history, hist);
112                                 el_set(el, EL_PROMPT, getprompt);
113                         } else {
114 bad:
115                                 out2str("sh: can't initialize editing\n");
116                         }
117                         INTON;
118                 } else if (!editing && el) {
119                         INTOFF;
120                         el_end(el);
121                         el = NULL;
122                         INTON;
123                 }
124                 if (el) {
125                         if (Vflag)
126                                 el_set(el, EL_EDITOR, "vi");
127                         else if (Eflag)
128                                 el_set(el, EL_EDITOR, "emacs");
129                         el_source(el, NULL);
130                 }
131         } else {
132                 INTOFF;
133                 if (el) {       /* no editing if not interactive */
134                         el_end(el);
135                         el = NULL;
136                 }
137                 if (hist) {
138                         history_end(hist);
139                         hist = NULL;
140                 }
141                 INTON;
142         }
143 }
144
145
146 void
147 sethistsize(hs)
148         const char *hs;
149 {
150         int histsize;
151
152         if (hist != NULL) {
153                 if (hs == NULL || *hs == '\0' ||
154                    (histsize = atoi(hs)) < 0)
155                         histsize = 100;
156                 history(hist, H_EVENT, histsize);
157         }
158 }
159
160 /*
161  *  This command is provided since POSIX decided to standardize
162  *  the Korn shell fc command.  Oh well...
163  */
164 int
165 histcmd(int argc, char **argv)
166 {
167         int ch;
168         char *editor = NULL;
169         const HistEvent *he;
170         int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
171         int i;
172         char *firststr, *laststr;
173         int first, last, direction;
174         char *pat = NULL, *repl;        /* ksh "fc old=new" crap */
175         static int active = 0;
176         struct jmploc jmploc;
177         struct jmploc *volatile savehandler;
178         char editfile[PATH_MAX];
179         FILE *efp;
180         int oldhistnum;
181 #ifdef __GNUC__
182         /* Avoid longjmp clobbering */
183         (void) &editor;
184         (void) &lflg;
185         (void) &nflg;
186         (void) &rflg;
187         (void) &sflg;
188         (void) &firststr;
189         (void) &laststr;
190         (void) &pat;
191         (void) &repl;
192         (void) &efp;
193         (void) &argc;
194         (void) &argv;
195 #endif
196
197         if (hist == NULL)
198                 error("history not active");
199
200         if (argc == 1)
201                 error("missing history argument");
202
203         optreset = 1; optind = 1; /* initialize getopt */
204         opterr = 0;
205         while (not_fcnumber(argv[optind]) &&
206               (ch = getopt(argc, argv, ":e:lnrs")) != -1)
207                 switch ((char)ch) {
208                 case 'e':
209                         editor = optarg;
210                         break;
211                 case 'l':
212                         lflg = 1;
213                         break;
214                 case 'n':
215                         nflg = 1;
216                         break;
217                 case 'r':
218                         rflg = 1;
219                         break;
220                 case 's':
221                         sflg = 1;
222                         break;
223                 case ':':
224                         error("option -%c expects argument", optopt);
225                 case '?':
226                 default:
227                         error("unknown option: -%c", optopt);
228                 }
229         argc -= optind, argv += optind;
230
231         /*
232          * If executing...
233          */
234         if (lflg == 0 || editor || sflg) {
235                 lflg = 0;       /* ignore */
236                 editfile[0] = '\0';
237                 /*
238                  * Catch interrupts to reset active counter and
239                  * cleanup temp files.
240                  */
241                 if (setjmp(jmploc.loc)) {
242                         active = 0;
243                         if (*editfile)
244                                 unlink(editfile);
245                         handler = savehandler;
246                         longjmp(handler->loc, 1);
247                 }
248                 savehandler = handler;
249                 handler = &jmploc;
250                 if (++active > MAXHISTLOOPS) {
251                         active = 0;
252                         displayhist = 0;
253                         error("called recursively too many times");
254                 }
255                 /*
256                  * Set editor.
257                  */
258                 if (sflg == 0) {
259                         if (editor == NULL &&
260                             (editor = bltinlookup("FCEDIT", 1)) == NULL &&
261                             (editor = bltinlookup("EDITOR", 1)) == NULL)
262                                 editor = DEFEDITOR;
263                         if (editor[0] == '-' && editor[1] == '\0') {
264                                 sflg = 1;       /* no edit */
265                                 editor = NULL;
266                         }
267                 }
268         }
269
270         /*
271          * If executing, parse [old=new] now
272          */
273         if (lflg == 0 && argc > 0 &&
274              ((repl = strchr(argv[0], '=')) != NULL)) {
275                 pat = argv[0];
276                 *repl++ = '\0';
277                 argc--, argv++;
278         }
279         /*
280          * determine [first] and [last]
281          */
282         switch (argc) {
283         case 0:
284                 firststr = lflg ? "-16" : "-1";
285                 laststr = "-1";
286                 break;
287         case 1:
288                 firststr = argv[0];
289                 laststr = lflg ? "-1" : argv[0];
290                 break;
291         case 2:
292                 firststr = argv[0];
293                 laststr = argv[1];
294                 break;
295         default:
296                 error("too many args");
297         }
298         /*
299          * Turn into event numbers.
300          */
301         first = str_to_event(firststr, 0);
302         last = str_to_event(laststr, 1);
303
304         if (rflg) {
305                 i = last;
306                 last = first;
307                 first = i;
308         }
309         /*
310          * XXX - this should not depend on the event numbers
311          * always increasing.  Add sequence numbers or offset
312          * to the history element in next (diskbased) release.
313          */
314         direction = first < last ? H_PREV : H_NEXT;
315
316         /*
317          * If editing, grab a temp file.
318          */
319         if (editor) {
320                 int fd;
321                 INTOFF;         /* easier */
322                 sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
323                 if ((fd = mkstemp(editfile)) < 0)
324                         error("can't create temporary file %s", editfile);
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, H_FIRST);
340         he = history(hist, H_NEXT_EVENT, first);
341         for (;he != NULL; he = history(hist, 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                                 }
354                                 evalstring(s);
355                                 if (displayhist && hist) {
356                                         /*
357                                          *  XXX what about recursive and
358                                          *  relative histnums.
359                                          */
360                                         history(hist, H_ENTER, s);
361                                 }
362                         } else
363                                 fputs(s, efp);
364                 }
365                 /*
366                  * At end?  (if we were to loose last, we'd sure be
367                  * messed up).
368                  */
369                 if (he->num == last)
370                         break;
371         }
372         if (editor) {
373                 char *editcmd;
374
375                 fclose(efp);
376                 editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
377                 sprintf(editcmd, "%s %s", editor, editfile);
378                 evalstring(editcmd);    /* XXX - should use no JC command */
379                 INTON;
380                 readcmdfile(editfile);  /* XXX - should read back - quick tst */
381                 unlink(editfile);
382         }
383
384         if (lflg == 0 && active > 0)
385                 --active;
386         if (displayhist)
387                 displayhist = 0;
388         return 0;
389 }
390
391 STATIC char *
392 fc_replace(const char *s, char *p, char *r)
393 {
394         char *dest;
395         int plen = strlen(p);
396
397         STARTSTACKSTR(dest);
398         while (*s) {
399                 if (*s == *p && strncmp(s, p, plen) == 0) {
400                         while (*r)
401                                 STPUTC(*r++, dest);
402                         s += plen;
403                         *p = '\0';      /* so no more matches */
404                 } else
405                         STPUTC(*s++, dest);
406         }
407         STACKSTRNUL(dest);
408         dest = grabstackstr(dest);
409
410         return (dest);
411 }
412
413 int
414 not_fcnumber(char *s)
415 {
416         if (s == NULL)
417                 return (0);
418         if (*s == '-')
419                 s++;
420         return (!is_number(s));
421 }
422
423 int
424 str_to_event(char *str, int last)
425 {
426         const HistEvent *he;
427         char *s = str;
428         int relative = 0;
429         int i;
430
431         he = history(hist, H_FIRST);
432         switch (*s) {
433         case '-':
434                 relative = 1;
435                 /*FALLTHROUGH*/
436         case '+':
437                 s++;
438         }
439         if (is_number(s)) {
440                 i = atoi(s);
441                 if (relative) {
442                         while (he != NULL && i--) {
443                                 he = history(hist, H_NEXT);
444                         }
445                         if (he == NULL)
446                                 he = history(hist, H_LAST);
447                 } else {
448                         he = history(hist, H_NEXT_EVENT, i);
449                         if (he == NULL) {
450                                 /*
451                                  * the notion of first and last is
452                                  * backwards to that of the history package
453                                  */
454                                 he = history(hist, last ? H_FIRST : H_LAST);
455                         }
456                 }
457                 if (he == NULL)
458                         error("history number %s not found (internal error)",
459                                str);
460         } else {
461                 /*
462                  * pattern
463                  */
464                 he = history(hist, H_PREV_STR, str);
465                 if (he == NULL)
466                         error("history pattern not found: %s", str);
467         }
468         return (he->num);
469 }
470
471 int
472 bindcmd(int argc, char **argv)
473 {
474
475         if (el == NULL)
476                 error("line editing is disabled");
477         return (el_parse(el, argc, argv));
478 }
479
480 #else
481 #include "error.h"
482
483 int
484 histcmd(int argc, char **argv)
485 {
486
487         error("not compiled with history support");
488         /*NOTREACHED*/
489         return (0);
490 }
491
492 int
493 bindcmd(int argc, char **argv)
494 {
495
496         error("not compiled with line editing support");
497         return (0);
498 }
499 #endif