]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/sh/histedit.c
sh: improve emacs mode
[FreeBSD/FreeBSD.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. 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 #include "builtins.h"
63
64 #define MAXHISTLOOPS    4       /* max recursions through fc */
65 #define DEFEDITOR       "ed"    /* default editor *should* be $EDITOR */
66
67 History *hist;  /* history cookie */
68 EditLine *el;   /* editline cookie */
69 int displayhist;
70 static FILE *el_in, *el_out, *el_err;
71
72 static char *fc_replace(const char *, char *, char *);
73 static int not_fcnumber(const char *);
74 static int str_to_event(const char *, int);
75
76 /*
77  * Set history and editing status.  Called whenever the status may
78  * have changed (figures out what to do).
79  */
80 void
81 histedit(void)
82 {
83
84 #define editing (Eflag || Vflag)
85
86         if (iflag) {
87                 if (!hist) {
88                         /*
89                          * turn history on
90                          */
91                         INTOFF;
92                         hist = history_init();
93                         INTON;
94
95                         if (hist != NULL)
96                                 sethistsize(histsizeval());
97                         else
98                                 out2fmt_flush("sh: can't initialize history\n");
99                 }
100                 if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
101                         /*
102                          * turn editing on
103                          */
104                         char *term;
105
106                         INTOFF;
107                         if (el_in == NULL)
108                                 el_in = fdopen(0, "r");
109                         if (el_err == NULL)
110                                 el_err = fdopen(1, "w");
111                         if (el_out == NULL)
112                                 el_out = fdopen(2, "w");
113                         if (el_in == NULL || el_err == NULL || el_out == NULL)
114                                 goto bad;
115                         term = lookupvar("TERM");
116                         if (term)
117                                 setenv("TERM", term, 1);
118                         else
119                                 unsetenv("TERM");
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                                 el_set(el, EL_ADDFN, "sh-complete",
126                                     "Filename completion",
127                                     _el_fn_complete);
128                         } else {
129 bad:
130                                 out2fmt_flush("sh: can't initialize editing\n");
131                         }
132                         INTON;
133                 } else if (!editing && el) {
134                         INTOFF;
135                         el_end(el);
136                         el = NULL;
137                         INTON;
138                 }
139                 if (el) {
140                         if (Vflag)
141                                 el_set(el, EL_EDITOR, "vi");
142                         else if (Eflag) {
143                                 el_set(el, EL_EDITOR, "emacs");
144                                 el_set(el, EL_BIND, "^R", "em-inc-search-prev", NULL);
145                         }
146                         el_set(el, EL_BIND, "^I", "sh-complete", 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 || !is_number(hs))
172                         histsize = 100;
173                 else
174                         histsize = atoi(hs);
175                 history(hist, &he, H_SETSIZE, histsize);
176                 history(hist, &he, H_SETUNIQUE, 1);
177         }
178 }
179
180 void
181 setterm(const char *term)
182 {
183         if (rootshell && el != NULL && term != NULL)
184                 el_set(el, EL_TERMINAL, term);
185 }
186
187 int
188 histcmd(int argc, char **argv __unused)
189 {
190         int ch;
191         const char *editor = NULL;
192         HistEvent he;
193         int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
194         int i, retval;
195         const char *firststr, *laststr;
196         int first, last, direction;
197         char *pat = NULL, *repl = NULL;
198         static int active = 0;
199         struct jmploc jmploc;
200         struct jmploc *savehandler;
201         char editfilestr[PATH_MAX];
202         char *volatile editfile;
203         FILE *efp = NULL;
204         int oldhistnum;
205
206         if (hist == NULL)
207                 error("history not active");
208
209         if (argc == 1)
210                 error("missing history argument");
211
212         while (not_fcnumber(*argptr) && (ch = nextopt("e:lnrs")) != '\0')
213                 switch ((char)ch) {
214                 case 'e':
215                         editor = shoptarg;
216                         break;
217                 case 'l':
218                         lflg = 1;
219                         break;
220                 case 'n':
221                         nflg = 1;
222                         break;
223                 case 'r':
224                         rflg = 1;
225                         break;
226                 case 's':
227                         sflg = 1;
228                         break;
229                 }
230
231         savehandler = handler;
232         /*
233          * If executing...
234          */
235         if (lflg == 0 || editor || sflg) {
236                 lflg = 0;       /* ignore */
237                 editfile = NULL;
238                 /*
239                  * Catch interrupts to reset active counter and
240                  * cleanup temp files.
241                  */
242                 if (setjmp(jmploc.loc)) {
243                         active = 0;
244                         if (editfile)
245                                 unlink(editfile);
246                         handler = savehandler;
247                         longjmp(handler->loc, 1);
248                 }
249                 handler = &jmploc;
250                 if (++active > MAXHISTLOOPS) {
251                         active = 0;
252                         displayhist = 0;
253                         error("called recursively too many times");
254                 }
255                 /*
256                  * Set editor.
257                  */
258                 if (sflg == 0) {
259                         if (editor == NULL &&
260                             (editor = bltinlookup("FCEDIT", 1)) == NULL &&
261                             (editor = bltinlookup("EDITOR", 1)) == NULL)
262                                 editor = DEFEDITOR;
263                         if (editor[0] == '-' && editor[1] == '\0') {
264                                 sflg = 1;       /* no edit */
265                                 editor = NULL;
266                         }
267                 }
268         }
269
270         /*
271          * If executing, parse [old=new] now
272          */
273         if (lflg == 0 && *argptr != NULL &&
274              ((repl = strchr(*argptr, '=')) != NULL)) {
275                 pat = *argptr;
276                 *repl++ = '\0';
277                 argptr++;
278         }
279         /*
280          * determine [first] and [last]
281          */
282         if (*argptr == NULL) {
283                 firststr = lflg ? "-16" : "-1";
284                 laststr = "-1";
285         } else if (argptr[1] == NULL) {
286                 firststr = argptr[0];
287                 laststr = lflg ? "-1" : argptr[0];
288         } else if (argptr[2] == NULL) {
289                 firststr = argptr[0];
290                 laststr = argptr[1];
291         } else
292                 error("too many arguments");
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(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
318                 if ((fd = mkstemp(editfilestr)) < 0)
319                         error("can't create temporary file %s", editfile);
320                 editfile = editfilestr;
321                 if ((efp = fdopen(fd, "w")) == NULL) {
322                         close(fd);
323                         error("Out of space");
324                 }
325         }
326
327         /*
328          * Loop through selected history events.  If listing or executing,
329          * do it now.  Otherwise, put into temp file and call the editor
330          * after.
331          *
332          * The history interface needs rethinking, as the following
333          * convolutions will demonstrate.
334          */
335         history(hist, &he, H_FIRST);
336         retval = history(hist, &he, H_NEXT_EVENT, first);
337         for (;retval != -1; retval = history(hist, &he, direction)) {
338                 if (lflg) {
339                         if (!nflg)
340                                 out1fmt("%5d ", he.num);
341                         out1str(he.str);
342                 } else {
343                         const char *s = pat ?
344                            fc_replace(he.str, pat, repl) : 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                                         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                 INTON;
382                 editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
383                 sprintf(editcmd, "%s %s", editor, editfile);
384                 evalstring(editcmd, 0); /* XXX - should use no JC command */
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         int ret;
480         FILE *old;
481         FILE *out;
482
483         if (el == NULL)
484                 error("line editing is disabled");
485
486         INTOFF;
487
488         out = out1fp();
489         if (out == NULL)
490                 error("Out of space");
491
492         el_get(el, EL_GETFP, 1, &old);
493         el_set(el, EL_SETFP, 1, out);
494
495         ret = el_parse(el, argc, __DECONST(const char **, argv));
496
497         el_set(el, EL_SETFP, 1, old);
498
499         fclose(out);
500
501         INTON;
502
503         return ret;
504 }
505
506 #else
507 #include "error.h"
508
509 int
510 histcmd(int argc, char **argv)
511 {
512
513         error("not compiled with history support");
514         /*NOTREACHED*/
515         return (0);
516 }
517
518 int
519 bindcmd(int argc, char **argv)
520 {
521
522         error("not compiled with line editing support");
523         return (0);
524 }
525 #endif