netif - alc driver port - Finishing touches
[dragonfly.git] / bin / sh / histedit.c
blobf7dc3c669355339ae3e44f087db57e83134533ce
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.12 2008/02/13 15:13:37 matthias 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 #include "myhistedit.h"
58 #ifndef NO_HISTORY
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 el_set(el, EL_ADDFN, "rl-complete",
128 "ReadLine compatible completion function",
129 _el_fn_complete);
130 } else {
131 bad:
132 out2str("sh: can't initialize editing\n");
134 INTON;
135 } else if (!editing && el) {
136 INTOFF;
137 el_end(el);
138 el = NULL;
139 INTON;
141 if (el) {
142 if (Vflag)
143 el_set(el, EL_EDITOR, "vi");
144 else if (Eflag)
145 el_set(el, EL_EDITOR, "emacs");
146 el_set(el, EL_BIND, "^I",
147 tabcomplete ? "rl-complete" : "ed-insert", NULL);
148 el_source(el, NULL);
150 } else {
151 INTOFF;
152 if (el) { /* no editing if not interactive */
153 el_end(el);
154 el = NULL;
156 if (hist) {
157 history_end(hist);
158 hist = NULL;
160 INTON;
165 void
166 sethistsize(const char *hs)
168 int histsize;
169 HistEvent he;
171 if (hist != NULL) {
172 if (hs == NULL || *hs == '\0' ||
173 (histsize = atoi(hs)) < 0)
174 histsize = 100;
175 history(hist, &he, H_SETSIZE, histsize);
176 history(hist, &he, H_SETUNIQUE, 1);
181 histcmd(int argc, char **argv)
183 int ch;
184 const char *volatile editor = NULL;
185 HistEvent he;
186 volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
187 int i, retval;
188 const char *firststr = NULL, *laststr = NULL;
189 int first, last, direction;
190 char *pat = NULL, *repl = NULL;
191 static int active = 0;
192 struct jmploc jmploc;
193 struct jmploc *volatile savehandler;
194 char editfile[PATH_MAX];
195 FILE *efp = NULL;
196 int oldhistnum;
198 if (hist == NULL)
199 error("history not active");
201 if (argc == 1)
202 error("missing history argument");
204 optreset = 1; optind = 1; /* initialize getopt */
205 opterr = 0;
206 while (not_fcnumber(argv[optind]) &&
207 (ch = getopt(argc, argv, ":e:lnrs")) != -1)
208 switch ((char)ch) {
209 case 'e':
210 editor = optarg;
211 break;
212 case 'l':
213 lflg = 1;
214 break;
215 case 'n':
216 nflg = 1;
217 break;
218 case 'r':
219 rflg = 1;
220 break;
221 case 's':
222 sflg = 1;
223 break;
224 case ':':
225 error("option -%c expects argument", optopt);
226 case '?':
227 default:
228 error("unknown option: -%c", optopt);
230 argc -= optind, argv += optind;
233 * If executing...
235 if (lflg == 0 || editor || sflg) {
236 lflg = 0; /* ignore */
237 editfile[0] = '\0';
239 * Catch interrupts to reset active counter and
240 * cleanup temp files.
242 if (setjmp(jmploc.loc)) {
243 active = 0;
244 if (*editfile)
245 unlink(editfile);
246 handler = savehandler;
247 longjmp(handler->loc, 1);
249 savehandler = handler;
250 handler = &jmploc;
251 if (++active > MAXHISTLOOPS) {
252 active = 0;
253 displayhist = 0;
254 error("called recursively too many times");
257 * Set editor.
259 if (sflg == 0) {
260 if (editor == NULL &&
261 (editor = bltinlookup("FCEDIT", 1)) == NULL &&
262 (editor = bltinlookup("EDITOR", 1)) == NULL)
263 editor = DEFEDITOR;
264 if (editor[0] == '-' && editor[1] == '\0') {
265 sflg = 1; /* no edit */
266 editor = NULL;
272 * If executing, parse [old=new] now
274 if (lflg == 0 && argc > 0 &&
275 ((repl = strchr(argv[0], '=')) != NULL)) {
276 pat = argv[0];
277 *repl++ = '\0';
278 argc--, argv++;
281 * determine [first] and [last]
283 switch (argc) {
284 case 0:
285 firststr = lflg ? "-16" : "-1";
286 laststr = "-1";
287 break;
288 case 1:
289 firststr = argv[0];
290 laststr = lflg ? "-1" : argv[0];
291 break;
292 case 2:
293 firststr = argv[0];
294 laststr = argv[1];
295 break;
296 default:
297 error("too many args");
300 * Turn into event numbers.
302 first = str_to_event(firststr, 0);
303 last = str_to_event(laststr, 1);
305 if (rflg) {
306 i = last;
307 last = first;
308 first = i;
311 * XXX - this should not depend on the event numbers
312 * always increasing. Add sequence numbers or offset
313 * to the history element in next (diskbased) release.
315 direction = first < last ? H_PREV : H_NEXT;
318 * If editing, grab a temp file.
320 if (editor) {
321 int fd;
322 INTOFF; /* easier */
323 sprintf(editfile, "%s/_shXXXXXX", _PATH_TMP);
324 if ((fd = mkstemp(editfile)) < 0)
325 error("can't create temporary file %s", editfile);
326 if ((efp = fdopen(fd, "w")) == NULL) {
327 close(fd);
328 error("can't allocate stdio buffer for temp");
333 * Loop through selected history events. If listing or executing,
334 * do it now. Otherwise, put into temp file and call the editor
335 * after.
337 * The history interface needs rethinking, as the following
338 * convolutions will demonstrate.
340 history(hist, &he, H_FIRST);
341 retval = history(hist, &he, H_NEXT_EVENT, first);
342 for (;retval != -1; retval = history(hist, &he, direction)) {
343 if (lflg) {
344 if (!nflg)
345 out1fmt("%5d ", he.num);
346 out1str(he.str);
347 } else {
348 const char *s = pat ?
349 fc_replace(he.str, pat, repl) : he.str;
351 if (sflg) {
352 if (displayhist) {
353 out2str(s);
355 evalstring(strcpy(stalloc(strlen(s) + 1), s));
356 if (displayhist && hist) {
358 * XXX what about recursive and
359 * relative histnums.
361 oldhistnum = he.num;
362 history(hist, &he, H_ENTER, s);
364 * XXX H_ENTER moves the internal
365 * cursor, set it back to the current
366 * entry.
368 retval = history(hist, &he,
369 H_NEXT_EVENT, oldhistnum);
371 } else
372 fputs(s, efp);
375 * At end? (if we were to lose last, we'd sure be
376 * messed up).
378 if (he.num == last)
379 break;
381 if (editor) {
382 char *editcmd;
384 fclose(efp);
385 editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
386 sprintf(editcmd, "%s %s", editor, editfile);
387 evalstring(editcmd); /* XXX - should use no JC command */
388 INTON;
389 readcmdfile(editfile); /* XXX - should read back - quick tst */
390 unlink(editfile);
393 if (lflg == 0 && active > 0)
394 --active;
395 if (displayhist)
396 displayhist = 0;
397 return 0;
400 STATIC char *
401 fc_replace(const char *s, char *p, char *r)
403 char *dest;
404 int plen = strlen(p);
406 STARTSTACKSTR(dest);
407 while (*s) {
408 if (*s == *p && strncmp(s, p, plen) == 0) {
409 while (*r)
410 STPUTC(*r++, dest);
411 s += plen;
412 *p = '\0'; /* so no more matches */
413 } else
414 STPUTC(*s++, dest);
416 STACKSTRNUL(dest);
417 dest = grabstackstr(dest);
419 return (dest);
423 not_fcnumber(char *s)
425 if (s == NULL)
426 return (0);
427 if (*s == '-')
428 s++;
429 return (!is_number(s));
433 str_to_event(const char *str, int last)
435 HistEvent he;
436 const char *s = str;
437 int relative = 0;
438 int i, retval;
440 retval = history(hist, &he, H_FIRST);
441 switch (*s) {
442 case '-':
443 relative = 1;
444 /*FALLTHROUGH*/
445 case '+':
446 s++;
448 if (is_number(s)) {
449 i = atoi(s);
450 if (relative) {
451 while (retval != -1 && i--) {
452 retval = history(hist, &he, H_NEXT);
454 if (retval == -1)
455 retval = history(hist, &he, H_LAST);
456 } else {
457 retval = history(hist, &he, H_NEXT_EVENT, i);
458 if (retval == -1) {
460 * the notion of first and last is
461 * backwards to that of the history package
463 retval = history(hist, &he, last ? H_FIRST : H_LAST);
466 if (retval == -1)
467 error("history number %s not found (internal error)",
468 str);
469 } else {
471 * pattern
473 retval = history(hist, &he, H_PREV_STR, str);
474 if (retval == -1)
475 error("history pattern not found: %s", str);
477 return (he.num);
481 bindcmd(int argc, char **argv)
484 if (el == NULL)
485 error("line editing is disabled");
486 return (el_parse(el, argc, (const char **)argv));
489 #else
490 #include "error.h"
493 histcmd(int argc __unused, char **argv __unused)
496 error("not compiled with history support");
497 /*NOTREACHED*/
498 return (0);
502 bindcmd(int argc __unused, char **argv __unused)
505 error("not compiled with line editing support");
506 return (0);
508 #endif