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