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