Merge branch 'vendor/TNFTP'
[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: head/bin/sh/histedit.c 240541 2012-09-15 21:56:30Z jilles $
38  */
39
40 #include <sys/param.h>
41 #include <limits.h>
42 #include <paths.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 /*
47  * Editline and history functions (and glue).
48  */
49 #include "shell.h"
50 #include "parser.h"
51 #include "var.h"
52 #include "options.h"
53 #include "main.h"
54 #include "output.h"
55 #include "mystring.h"
56 #include "myhistedit.h"
57 #ifndef NO_HISTORY
58 #include "error.h"
59 #include "eval.h"
60 #include "memalloc.h"
61 #include "builtins.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 static int not_fcnumber(const char *);
73 static int str_to_event(const char *, int);
74
75 /*
76  * Set history and editing status.  Called whenever the status may
77  * have changed (figures out what to do).
78  */
79 void
80 histedit(void)
81 {
82
83 #define editing (Eflag || Vflag)
84
85         if (iflag) {
86                 if (!hist) {
87                         /*
88                          * turn history on
89                          */
90                         INTOFF;
91                         hist = history_init();
92                         INTON;
93
94                         if (hist != NULL)
95                                 sethistsize(histsizeval());
96                         else
97                                 out2fmt_flush("sh: can't initialize history\n");
98                 }
99                 if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
100                         /*
101                          * turn editing on
102                          */
103                         char *term;
104
105                         INTOFF;
106                         if (el_in == NULL)
107                                 el_in = fdopen(0, "r");
108                         if (el_err == NULL)
109                                 el_err = fdopen(1, "w");
110                         if (el_out == NULL)
111                                 el_out = fdopen(2, "w");
112                         if (el_in == NULL || el_err == NULL || el_out == NULL)
113                                 goto bad;
114                         term = lookupvar("TERM");
115                         if (term) {
116                                 if (setenv("TERM", term, 1) == -1)
117                                         error("setenv: cannot set TERM=1");
118                         }
119                         else
120                                 unsetenv("TERM");
121                         el = el_init(arg0, el_in, el_out, el_err);
122                         if (el != NULL) {
123                                 if (hist)
124                                         el_set(el, EL_HIST, history, hist);
125                                 el_set(el, EL_PROMPT, getprompt);
126                                 el_set(el, EL_ADDFN, "rl-complete",
127                                     "ReadLine compatible completion function",
128                                     _el_fn_complete);
129                         } else {
130 bad:
131                                 out2fmt_flush("sh: can't initialize editing\n");
132                         }
133                         INTON;
134                 } else if (!editing && el) {
135                         INTOFF;
136                         el_end(el);
137                         el = NULL;
138                         INTON;
139                 }
140                 if (el) {
141                         if (Vflag)
142                                 el_set(el, EL_EDITOR, "vi");
143                         else if (Eflag)
144                                 el_set(el, EL_EDITOR, "emacs");
145                         el_set(el, EL_BIND, "^I",
146                             tabcomplete ? "rl-complete" : "ed-insert", NULL);
147                         el_source(el, NULL);
148                 }
149         } else {
150                 INTOFF;
151                 if (el) {       /* no editing if not interactive */
152                         el_end(el);
153                         el = NULL;
154                 }
155                 if (hist) {
156                         history_end(hist);
157                         hist = NULL;
158                 }
159                 INTON;
160         }
161 }
162
163
164 void
165 sethistsize(const char *hs)
166 {
167         int histsize;
168         HistEvent he;
169
170         if (hist != NULL) {
171                 if (hs == NULL || *hs == '\0' ||
172                    (histsize = atoi(hs)) < 0)
173                         histsize = 100;
174                 history(hist, &he, H_SETSIZE, histsize);
175                 history(hist, &he, H_SETUNIQUE, 1);
176         }
177 }
178
179 void
180 setterm(const char *term)
181 {
182         if (rootshell && el != NULL && term != NULL)
183                 el_set(el, EL_TERMINAL, term);
184 }
185
186 int
187 histcmd(int argc, char **argv __unused)
188 {
189         int ch;
190         const char *volatile editor = NULL;
191         HistEvent he;
192         volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
193         int i, retval;
194         const char *firststr = NULL, *laststr = NULL;
195         int first, last, direction;
196         char *pat = NULL, *repl = NULL;
197         static int active = 0;
198         struct jmploc jmploc;
199         struct jmploc *savehandler;
200         char editfilestr[PATH_MAX];
201         char *volatile editfile;
202         FILE *efp = NULL;
203         int oldhistnum;
204
205         if (hist == NULL)
206                 error("history not active");
207
208         if (argc == 1)
209                 error("missing history argument");
210
211         while (not_fcnumber(*argptr) && (ch = nextopt("e:lnrs")) != '\0')
212                 switch ((char)ch) {
213                 case 'e':
214                         editor = shoptarg;
215                         break;
216                 case 'l':
217                         lflg = 1;
218                         break;
219                 case 'n':
220                         nflg = 1;
221                         break;
222                 case 'r':
223                         rflg = 1;
224                         break;
225                 case 's':
226                         sflg = 1;
227                         break;
228                 }
229
230         savehandler = handler;
231         /*
232          * If executing...
233          */
234         if (lflg == 0 || editor || sflg) {
235                 lflg = 0;       /* ignore */
236                 editfile = NULL;
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                 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 && *argptr != NULL &&
273              ((repl = strchr(*argptr, '=')) != NULL)) {
274                 pat = *argptr;
275                 *repl++ = '\0';
276                 argptr++;
277         }
278         /*
279          * determine [first] and [last]
280          */
281         if (*argptr == NULL) {
282                 firststr = lflg ? "-16" : "-1";
283                 laststr = "-1";
284         } else if (argptr[1] == NULL) {
285                 firststr = argptr[0];
286                 laststr = lflg ? "-1" : argptr[0];
287         } else if (argptr[2] == NULL) {
288                 firststr = argptr[0];
289                 laststr = argptr[1];
290         } else
291                 error("too many arguments");
292         /*
293          * Turn into event numbers.
294          */
295         first = str_to_event(firststr, 0);
296         last = str_to_event(laststr, 1);
297
298         if (rflg) {
299                 i = last;
300                 last = first;
301                 first = i;
302         }
303         /*
304          * XXX - this should not depend on the event numbers
305          * always increasing.  Add sequence numbers or offset
306          * to the history element in next (diskbased) release.
307          */
308         direction = first < last ? H_PREV : H_NEXT;
309
310         /*
311          * If editing, grab a temp file.
312          */
313         if (editor) {
314                 int fd;
315                 INTOFF;         /* easier */
316                 sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
317                 if ((fd = mkstemp(editfilestr)) < 0)
318                         error("can't create temporary file %s", editfile);
319                 editfile = editfilestr;
320                 if ((efp = fdopen(fd, "w")) == NULL) {
321                         close(fd);
322                         error("Out of space");
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                         char *s = pat ?
343                            fc_replace(he.str, pat, repl) :
344                            __DECONST(char *, he.str);
345
346                         if (sflg) {
347                                 if (displayhist) {
348                                         out2str(s);
349                                         flushout(out2);
350                                 }
351                                 evalstring(s, 0);
352                                 if (displayhist && hist) {
353                                         /*
354                                          *  XXX what about recursive and
355                                          *  relative histnums.
356                                          */
357                                         oldhistnum = he.num;
358                                         history(hist, &he, H_ENTER, s);
359                                         /*
360                                          * XXX H_ENTER moves the internal
361                                          * cursor, set it back to the current
362                                          * entry.
363                                          */
364                                         retval = history(hist, &he,
365                                             H_NEXT_EVENT, oldhistnum);
366                                 }
367                         } else
368                                 fputs(s, efp);
369                 }
370                 /*
371                  * At end?  (if we were to lose last, we'd sure be
372                  * messed up).
373                  */
374                 if (he.num == last)
375                         break;
376         }
377         if (editor) {
378                 char *editcmd;
379
380                 fclose(efp);
381                 editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
382                 sprintf(editcmd, "%s %s", editor, editfile);
383                 evalstring(editcmd, 0); /* XXX - should use no JC command */
384                 INTON;
385                 readcmdfile(editfile);  /* XXX - should read back - quick tst */
386                 unlink(editfile);
387         }
388
389         if (lflg == 0 && active > 0)
390                 --active;
391         if (displayhist)
392                 displayhist = 0;
393         handler = savehandler;
394         return 0;
395 }
396
397 static char *
398 fc_replace(const char *s, char *p, char *r)
399 {
400         char *dest;
401         int plen = strlen(p);
402
403         STARTSTACKSTR(dest);
404         while (*s) {
405                 if (*s == *p && strncmp(s, p, plen) == 0) {
406                         STPUTS(r, dest);
407                         s += plen;
408                         *p = '\0';      /* so no more matches */
409                 } else
410                         STPUTC(*s++, dest);
411         }
412         STPUTC('\0', dest);
413         dest = grabstackstr(dest);
414
415         return (dest);
416 }
417
418 static int
419 not_fcnumber(const char *s)
420 {
421         if (s == NULL)
422                 return (0);
423         if (*s == '-')
424                 s++;
425         return (!is_number(s));
426 }
427
428 static int
429 str_to_event(const char *str, int last)
430 {
431         HistEvent he;
432         const char *s = str;
433         int relative = 0;
434         int i, retval;
435
436         retval = history(hist, &he, H_FIRST);
437         switch (*s) {
438         case '-':
439                 relative = 1;
440                 /*FALLTHROUGH*/
441         case '+':
442                 s++;
443         }
444         if (is_number(s)) {
445                 i = atoi(s);
446                 if (relative) {
447                         while (retval != -1 && i--) {
448                                 retval = history(hist, &he, H_NEXT);
449                         }
450                         if (retval == -1)
451                                 retval = history(hist, &he, H_LAST);
452                 } else {
453                         retval = history(hist, &he, H_NEXT_EVENT, i);
454                         if (retval == -1) {
455                                 /*
456                                  * the notion of first and last is
457                                  * backwards to that of the history package
458                                  */
459                                 retval = history(hist, &he, last ? H_FIRST : H_LAST);
460                         }
461                 }
462                 if (retval == -1)
463                         error("history number %s not found (internal error)",
464                                str);
465         } else {
466                 /*
467                  * pattern
468                  */
469                 retval = history(hist, &he, H_PREV_STR, str);
470                 if (retval == -1)
471                         error("history pattern not found: %s", str);
472         }
473         return (he.num);
474 }
475
476 int
477 bindcmd(int argc, char **argv)
478 {
479
480         if (el == NULL)
481                 error("line editing is disabled");
482         return (el_parse(el, argc, (const char **)argv));
483 }
484
485 #else
486 #include "error.h"
487
488 int
489 histcmd(int argc __unused, char **argv __unused)
490 {
491
492         error("not compiled with history support");
493         /*NOTREACHED*/
494         return (0);
495 }
496
497 int
498 bindcmd(int argc __unused, char **argv __unused)
499 {
500
501         error("not compiled with line editing support");
502         return (0);
503 }
504 #endif