Merge from vendor branch OPENPAM:
[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.4 2004/03/19 18:39:41 cpressey 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         const char *editor = NULL;
169         const HistEvent *he;
170         int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
171         int i;
172         const 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 #ifdef __GNUC__
181         /* Avoid longjmp clobbering */
182         (void) &editor;
183         (void) &lflg;
184         (void) &nflg;
185         (void) &rflg;
186         (void) &sflg;
187         (void) &firststr;
188         (void) &laststr;
189         (void) &pat;
190         (void) &repl;
191         (void) &efp;
192         (void) &argc;
193         (void) &argv;
194 #endif
195
196         if (hist == NULL)
197                 error("history not active");
198
199         if (argc == 1)
200                 error("missing history argument");
201
202         optreset = 1; optind = 1; /* initialize getopt */
203         opterr = 0;
204         while (not_fcnumber(argv[optind]) &&
205               (ch = getopt(argc, argv, ":e:lnrs")) != -1)
206                 switch ((char)ch) {
207                 case 'e':
208                         editor = optarg;
209                         break;
210                 case 'l':
211                         lflg = 1;
212                         break;
213                 case 'n':
214                         nflg = 1;
215                         break;
216                 case 'r':
217                         rflg = 1;
218                         break;
219                 case 's':
220                         sflg = 1;
221                         break;
222                 case ':':
223                         error("option -%c expects argument", optopt);
224                 case '?':
225                 default:
226                         error("unknown option: -%c", optopt);
227                 }
228         argc -= optind, argv += optind;
229
230         /*
231          * If executing...
232          */
233         if (lflg == 0 || editor || sflg) {
234                 lflg = 0;       /* ignore */
235                 editfile[0] = '\0';
236                 /*
237                  * Catch interrupts to reset active counter and
238                  * cleanup temp files.
239                  */
240                 if (setjmp(jmploc.loc)) {
241                         active = 0;
242                         if (*editfile)
243                                 unlink(editfile);
244                         handler = savehandler;
245                         longjmp(handler->loc, 1);
246                 }
247                 savehandler = handler;
248                 handler = &jmploc;
249                 if (++active > MAXHISTLOOPS) {
250                         active = 0;
251                         displayhist = 0;
252                         error("called recursively too many times");
253                 }
254                 /*
255                  * Set editor.
256                  */
257                 if (sflg == 0) {
258                         if (editor == NULL &&
259                             (editor = bltinlookup("FCEDIT", 1)) == NULL &&
260                             (editor = bltinlookup("EDITOR", 1)) == NULL)
261                                 editor = DEFEDITOR;
262                         if (editor[0] == '-' && editor[1] == '\0') {
263                                 sflg = 1;       /* no edit */
264                                 editor = NULL;
265                         }
266                 }
267         }
268
269         /*
270          * If executing, parse [old=new] now
271          */
272         if (lflg == 0 && argc > 0 &&
273              ((repl = strchr(argv[0], '=')) != NULL)) {
274                 pat = argv[0];
275                 *repl++ = '\0';
276                 argc--, argv++;
277         }
278         /*
279          * determine [first] and [last]
280          */
281         switch (argc) {
282         case 0:
283                 firststr = lflg ? "-16" : "-1";
284                 laststr = "-1";
285                 break;
286         case 1:
287                 firststr = argv[0];
288                 laststr = lflg ? "-1" : argv[0];
289                 break;
290         case 2:
291                 firststr = argv[0];
292                 laststr = argv[1];
293                 break;
294         default:
295                 error("too many args");
296         }
297         /*
298          * Turn into event numbers.
299          */
300         first = str_to_event(firststr, 0);
301         last = str_to_event(laststr, 1);
302
303         if (rflg) {
304                 i = last;
305                 last = first;
306                 first = i;
307         }
308         /*
309          * XXX - this should not depend on the event numbers
310          * always increasing.  Add sequence numbers or offset
311          * to the history element in next (diskbased) release.
312          */
313         direction = first < last ? H_PREV : H_NEXT;
314
315         /*
316          * If editing, grab a temp file.
317          */
318         if (editor) {
319                 int fd;
320                 INTOFF;         /* easier */
321                 sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
322                 if ((fd = mkstemp(editfile)) < 0)
323                         error("can't create temporary file %s", editfile);
324                 if ((efp = fdopen(fd, "w")) == NULL) {
325                         close(fd);
326                         error("can't allocate stdio buffer for temp");
327                 }
328         }
329
330         /*
331          * Loop through selected history events.  If listing or executing,
332          * do it now.  Otherwise, put into temp file and call the editor
333          * after.
334          *
335          * The history interface needs rethinking, as the following
336          * convolutions will demonstrate.
337          */
338         history(hist, H_FIRST);
339         he = history(hist, H_NEXT_EVENT, first);
340         for (;he != NULL; he = history(hist, direction)) {
341                 if (lflg) {
342                         if (!nflg)
343                                 out1fmt("%5d ", he->num);
344                         out1str(he->str);
345                 } else {
346                         char *s = pat ?
347                            fc_replace(he->str, pat, repl) : (char *)he->str;
348
349                         if (sflg) {
350                                 if (displayhist) {
351                                         out2str(s);
352                                 }
353                                 evalstring(s);
354                                 if (displayhist && hist) {
355                                         /*
356                                          *  XXX what about recursive and
357                                          *  relative histnums.
358                                          */
359                                         history(hist, H_ENTER, s);
360                                 }
361                         } else
362                                 fputs(s, efp);
363                 }
364                 /*
365                  * At end?  (if we were to loose last, we'd sure be
366                  * messed up).
367                  */
368                 if (he->num == last)
369                         break;
370         }
371         if (editor) {
372                 char *editcmd;
373
374                 fclose(efp);
375                 editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
376                 sprintf(editcmd, "%s %s", editor, editfile);
377                 evalstring(editcmd);    /* XXX - should use no JC command */
378                 INTON;
379                 readcmdfile(editfile);  /* XXX - should read back - quick tst */
380                 unlink(editfile);
381         }
382
383         if (lflg == 0 && active > 0)
384                 --active;
385         if (displayhist)
386                 displayhist = 0;
387         return 0;
388 }
389
390 STATIC char *
391 fc_replace(const char *s, char *p, char *r)
392 {
393         char *dest;
394         int plen = strlen(p);
395
396         STARTSTACKSTR(dest);
397         while (*s) {
398                 if (*s == *p && strncmp(s, p, plen) == 0) {
399                         while (*r)
400                                 STPUTC(*r++, dest);
401                         s += plen;
402                         *p = '\0';      /* so no more matches */
403                 } else
404                         STPUTC(*s++, dest);
405         }
406         STACKSTRNUL(dest);
407         dest = grabstackstr(dest);
408
409         return (dest);
410 }
411
412 int
413 not_fcnumber(char *s)
414 {
415         if (s == NULL)
416                 return (0);
417         if (*s == '-')
418                 s++;
419         return (!is_number(s));
420 }
421
422 int
423 str_to_event(const char *str, int last)
424 {
425         const HistEvent *he;
426         const char *s = str;
427         int relative = 0;
428         int i;
429
430         he = history(hist, H_FIRST);
431         switch (*s) {
432         case '-':
433                 relative = 1;
434                 /*FALLTHROUGH*/
435         case '+':
436                 s++;
437         }
438         if (is_number(s)) {
439                 i = atoi(s);
440                 if (relative) {
441                         while (he != NULL && i--) {
442                                 he = history(hist, H_NEXT);
443                         }
444                         if (he == NULL)
445                                 he = history(hist, H_LAST);
446                 } else {
447                         he = history(hist, H_NEXT_EVENT, i);
448                         if (he == NULL) {
449                                 /*
450                                  * the notion of first and last is
451                                  * backwards to that of the history package
452                                  */
453                                 he = history(hist, last ? H_FIRST : H_LAST);
454                         }
455                 }
456                 if (he == NULL)
457                         error("history number %s not found (internal error)",
458                                str);
459         } else {
460                 /*
461                  * pattern
462                  */
463                 he = history(hist, H_PREV_STR, str);
464                 if (he == NULL)
465                         error("history pattern not found: %s", str);
466         }
467         return (he->num);
468 }
469
470 int
471 bindcmd(int argc, char **argv)
472 {
473
474         if (el == NULL)
475                 error("line editing is disabled");
476         return (el_parse(el, argc, argv));
477 }
478
479 #else
480 #include "error.h"
481
482 int
483 histcmd(int argc, char **argv)
484 {
485
486         error("not compiled with history support");
487         /*NOTREACHED*/
488         return (0);
489 }
490
491 int
492 bindcmd(int argc, char **argv)
493 {
494
495         error("not compiled with line editing support");
496         return (0);
497 }
498 #endif