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