Fix typo and remove unneeded comments.
[dragonfly/port-amd64.git] / bin / sh / histedit.c
blob29fa0d385a65418c6291722c32f4794ef35fa0ad
1 /*-
2 * Copyright (c) 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
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.
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.
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.10 2007/01/13 19:47:55 pavalos Exp $
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>
48 * Editline and history functions (and glue).
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"
63 #define MAXHISTLOOPS 4 /* max recursions through fc */
64 #define DEFEDITOR "ed" /* default editor *should* be $EDITOR */
66 History *hist; /* history cookie */
67 EditLine *el; /* editline cookie */
68 int displayhist;
69 static FILE *el_in, *el_out, *el_err;
71 STATIC char *fc_replace(const char *, char *, char *);
74 * Set history and editing status. Called whenever the status may
75 * have changed (figures out what to do).
77 void
78 histedit(void)
81 #define editing (Eflag || Vflag)
83 if (iflag) {
84 if (!hist) {
86 * turn history on
88 INTOFF;
89 hist = history_init();
90 INTON;
92 if (hist != NULL)
93 sethistsize(histsizeval());
94 else
95 out2str("sh: can't initialize history\n");
97 if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
99 * turn editing on
101 char *term, *shname;
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");
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");
131 INTON;
132 } else if (!editing && el) {
133 INTOFF;
134 el_end(el);
135 el = NULL;
136 INTON;
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);
145 } else {
146 INTOFF;
147 if (el) { /* no editing if not interactive */
148 el_end(el);
149 el = NULL;
151 if (hist) {
152 history_end(hist);
153 hist = NULL;
155 INTON;
160 void
161 sethistsize(const char *hs)
163 int histsize;
164 HistEvent he;
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);
175 histcmd(int argc, char **argv)
177 int ch;
178 const char *editor = NULL;
179 HistEvent he;
180 int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
181 int i, retval;
182 const char *firststr, *laststr;
183 int first, last, direction;
184 char *pat = NULL, *repl;
185 static int active = 0;
186 struct jmploc jmploc;
187 struct jmploc *volatile savehandler;
188 char editfile[PATH_MAX];
189 FILE *efp;
190 int oldhistnum;
191 #ifdef __GNUC__
192 /* Avoid longjmp clobbering */
193 (void) &editor;
194 (void) &lflg;
195 (void) &nflg;
196 (void) &rflg;
197 (void) &sflg;
198 (void) &firststr;
199 (void) &laststr;
200 (void) &pat;
201 (void) &repl;
202 (void) &efp;
203 (void) &argc;
204 (void) &argv;
205 #endif
207 if (hist == NULL)
208 error("history not active");
210 if (argc == 1)
211 error("missing history argument");
213 optreset = 1; optind = 1; /* initialize getopt */
214 opterr = 0;
215 while (not_fcnumber(argv[optind]) &&
216 (ch = getopt(argc, argv, ":e:lnrs")) != -1)
217 switch ((char)ch) {
218 case 'e':
219 editor = optarg;
220 break;
221 case 'l':
222 lflg = 1;
223 break;
224 case 'n':
225 nflg = 1;
226 break;
227 case 'r':
228 rflg = 1;
229 break;
230 case 's':
231 sflg = 1;
232 break;
233 case ':':
234 error("option -%c expects argument", optopt);
235 case '?':
236 default:
237 error("unknown option: -%c", optopt);
239 argc -= optind, argv += optind;
242 * If executing...
244 if (lflg == 0 || editor || sflg) {
245 lflg = 0; /* ignore */
246 editfile[0] = '\0';
248 * Catch interrupts to reset active counter and
249 * cleanup temp files.
251 if (setjmp(jmploc.loc)) {
252 active = 0;
253 if (*editfile)
254 unlink(editfile);
255 handler = savehandler;
256 longjmp(handler->loc, 1);
258 savehandler = handler;
259 handler = &jmploc;
260 if (++active > MAXHISTLOOPS) {
261 active = 0;
262 displayhist = 0;
263 error("called recursively too many times");
266 * Set editor.
268 if (sflg == 0) {
269 if (editor == NULL &&
270 (editor = bltinlookup("FCEDIT", 1)) == NULL &&
271 (editor = bltinlookup("EDITOR", 1)) == NULL)
272 editor = DEFEDITOR;
273 if (editor[0] == '-' && editor[1] == '\0') {
274 sflg = 1; /* no edit */
275 editor = NULL;
281 * If executing, parse [old=new] now
283 if (lflg == 0 && argc > 0 &&
284 ((repl = strchr(argv[0], '=')) != NULL)) {
285 pat = argv[0];
286 *repl++ = '\0';
287 argc--, argv++;
290 * determine [first] and [last]
292 switch (argc) {
293 case 0:
294 firststr = lflg ? "-16" : "-1";
295 laststr = "-1";
296 break;
297 case 1:
298 firststr = argv[0];
299 laststr = lflg ? "-1" : argv[0];
300 break;
301 case 2:
302 firststr = argv[0];
303 laststr = argv[1];
304 break;
305 default:
306 error("too many args");
309 * Turn into event numbers.
311 first = str_to_event(firststr, 0);
312 last = str_to_event(laststr, 1);
314 if (rflg) {
315 i = last;
316 last = first;
317 first = i;
320 * XXX - this should not depend on the event numbers
321 * always increasing. Add sequence numbers or offset
322 * to the history element in next (diskbased) release.
324 direction = first < last ? H_PREV : H_NEXT;
327 * If editing, grab a temp file.
329 if (editor) {
330 int fd;
331 INTOFF; /* easier */
332 sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
333 if ((fd = mkstemp(editfile)) < 0)
334 error("can't create temporary file %s", editfile);
335 if ((efp = fdopen(fd, "w")) == NULL) {
336 close(fd);
337 error("can't allocate stdio buffer for temp");
342 * Loop through selected history events. If listing or executing,
343 * do it now. Otherwise, put into temp file and call the editor
344 * after.
346 * The history interface needs rethinking, as the following
347 * convolutions will demonstrate.
349 history(hist, &he, H_FIRST);
350 retval = history(hist, &he, H_NEXT_EVENT, first);
351 for (;retval != -1; retval = history(hist, &he, direction)) {
352 if (lflg) {
353 if (!nflg)
354 out1fmt("%5d ", he.num);
355 out1str(he.str);
356 } else {
357 const char *s = pat ?
358 fc_replace(he.str, pat, repl) : he.str;
360 if (sflg) {
361 if (displayhist) {
362 out2str(s);
364 evalstring(strcpy(stalloc(strlen(s) + 1), s));
365 if (displayhist && hist) {
367 * XXX what about recursive and
368 * relative histnums.
370 oldhistnum = he.num;
371 history(hist, &he, H_ENTER, s);
373 * XXX H_ENTER moves the internal
374 * cursor, set it back to the current
375 * entry.
377 retval = history(hist, &he,
378 H_NEXT_EVENT, oldhistnum);
380 } else
381 fputs(s, efp);
384 * At end? (if we were to lose last, we'd sure be
385 * messed up).
387 if (he.num == last)
388 break;
390 if (editor) {
391 char *editcmd;
393 fclose(efp);
394 editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
395 sprintf(editcmd, "%s %s", editor, editfile);
396 evalstring(editcmd); /* XXX - should use no JC command */
397 INTON;
398 readcmdfile(editfile); /* XXX - should read back - quick tst */
399 unlink(editfile);
402 if (lflg == 0 && active > 0)
403 --active;
404 if (displayhist)
405 displayhist = 0;
406 return 0;
409 STATIC char *
410 fc_replace(const char *s, char *p, char *r)
412 char *dest;
413 int plen = strlen(p);
415 STARTSTACKSTR(dest);
416 while (*s) {
417 if (*s == *p && strncmp(s, p, plen) == 0) {
418 while (*r)
419 STPUTC(*r++, dest);
420 s += plen;
421 *p = '\0'; /* so no more matches */
422 } else
423 STPUTC(*s++, dest);
425 STACKSTRNUL(dest);
426 dest = grabstackstr(dest);
428 return (dest);
432 not_fcnumber(char *s)
434 if (s == NULL)
435 return (0);
436 if (*s == '-')
437 s++;
438 return (!is_number(s));
442 str_to_event(const char *str, int last)
444 HistEvent he;
445 const char *s = str;
446 int relative = 0;
447 int i, retval;
449 retval = history(hist, &he, H_FIRST);
450 switch (*s) {
451 case '-':
452 relative = 1;
453 /*FALLTHROUGH*/
454 case '+':
455 s++;
457 if (is_number(s)) {
458 i = atoi(s);
459 if (relative) {
460 while (retval != -1 && i--) {
461 retval = history(hist, &he, H_NEXT);
463 if (retval == -1)
464 retval = history(hist, &he, H_LAST);
465 } else {
466 retval = history(hist, &he, H_NEXT_EVENT, i);
467 if (retval == -1) {
469 * the notion of first and last is
470 * backwards to that of the history package
472 retval = history(hist, &he, last ? H_FIRST : H_LAST);
475 if (retval == -1)
476 error("history number %s not found (internal error)",
477 str);
478 } else {
480 * pattern
482 retval = history(hist, &he, H_PREV_STR, str);
483 if (retval == -1)
484 error("history pattern not found: %s", str);
486 return (he.num);
490 bindcmd(int argc, char **argv)
493 if (el == NULL)
494 error("line editing is disabled");
495 return (el_parse(el, argc, (const char **)argv));
498 #else
499 #include "error.h"
502 histcmd(int argc, char **argv)
505 error("not compiled with history support");
506 /*NOTREACHED*/
507 return (0);
511 bindcmd(int argc, char **argv)
514 error("not compiled with line editing support");
515 return (0);
517 #endif