sh: Fix duplicate prototypes for builtins.
[dragonfly.git] / bin / sh / histedit.c
CommitLineData
984263bc
MD
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.
1de703da
MD
35 *
36 * @(#)histedit.c 8.2 (Berkeley) 5/4/95
c3e3bc7a 37 * $FreeBSD: src/bin/sh/histedit.c,v 1.43 2011/06/13 21:03:27 jilles Exp $
984263bc
MD
38 */
39
984263bc
MD
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"
984263bc 56#include "myhistedit.h"
29359575 57#ifndef NO_HISTORY
984263bc
MD
58#include "error.h"
59#include "eval.h"
60#include "memalloc.h"
c3e3bc7a 61#include "builtins.h"
984263bc
MD
62
63#define MAXHISTLOOPS 4 /* max recursions through fc */
64#define DEFEDITOR "ed" /* default editor *should* be $EDITOR */
65
66History *hist; /* history cookie */
67EditLine *el; /* editline cookie */
68int displayhist;
dae86e27 69static FILE *el_in, *el_out, *el_err;
984263bc 70
99512ac4 71static char *fc_replace(const char *, char *, char *);
984263bc
MD
72
73/*
74 * Set history and editing status. Called whenever the status may
75 * have changed (figures out what to do).
76 */
77void
78histedit(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
99512ac4 95 out2fmt_flush("sh: can't initialize history\n");
984263bc
MD
96 }
97 if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
98 /*
99 * turn editing on
100 */
99512ac4 101 char *term;
9fa62156 102
984263bc
MD
103 INTOFF;
104 if (el_in == NULL)
105 el_in = fdopen(0, "r");
dae86e27
PA
106 if (el_err == NULL)
107 el_err = fdopen(1, "w");
984263bc
MD
108 if (el_out == NULL)
109 el_out = fdopen(2, "w");
dae86e27 110 if (el_in == NULL || el_err == NULL || el_out == NULL)
984263bc 111 goto bad;
9fa62156 112 term = lookupvar("TERM");
8ef0e968
SS
113 if (term) {
114 if (setenv("TERM", term, 1) == -1)
115 error("setenv: cannot set TERM=1");
116 }
9fa62156
SS
117 else
118 unsetenv("TERM");
9fa62156 119 el = el_init(arg0, el_in, el_out, el_err);
984263bc
MD
120 if (el != NULL) {
121 if (hist)
122 el_set(el, EL_HIST, history, hist);
123 el_set(el, EL_PROMPT, getprompt);
3f2d021a
YT
124 el_set(el, EL_ADDFN, "rl-complete",
125 "ReadLine compatible completion function",
126 _el_fn_complete);
984263bc
MD
127 } else {
128bad:
99512ac4 129 out2fmt_flush("sh: can't initialize editing\n");
984263bc
MD
130 }
131 INTON;
132 } else if (!editing && el) {
133 INTOFF;
134 el_end(el);
135 el = NULL;
136 INTON;
137 }
138 if (el) {
139 if (Vflag)
140 el_set(el, EL_EDITOR, "vi");
141 else if (Eflag)
142 el_set(el, EL_EDITOR, "emacs");
3f2d021a
YT
143 el_set(el, EL_BIND, "^I",
144 tabcomplete ? "rl-complete" : "ed-insert", NULL);
984263bc
MD
145 el_source(el, NULL);
146 }
147 } else {
148 INTOFF;
149 if (el) { /* no editing if not interactive */
150 el_end(el);
151 el = NULL;
152 }
153 if (hist) {
154 history_end(hist);
155 hist = NULL;
156 }
157 INTON;
158 }
159}
160
161
162void
1f0f7b35 163sethistsize(const char *hs)
984263bc
MD
164{
165 int histsize;
9fa62156 166 HistEvent he;
984263bc
MD
167
168 if (hist != NULL) {
169 if (hs == NULL || *hs == '\0' ||
170 (histsize = atoi(hs)) < 0)
171 histsize = 100;
9fa62156 172 history(hist, &he, H_SETSIZE, histsize);
64d68b44 173 history(hist, &he, H_SETUNIQUE, 1);
984263bc
MD
174 }
175}
176
99512ac4
PA
177void
178setterm(const char *term)
179{
180 if (rootshell && el != NULL && term != NULL)
181 el_set(el, EL_TERMINAL, term);
182}
183
984263bc
MD
184int
185histcmd(int argc, char **argv)
186{
187 int ch;
f2aa3fa5 188 const char *volatile editor = NULL;
9fa62156 189 HistEvent he;
f2aa3fa5 190 volatile int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
9fa62156 191 int i, retval;
f2aa3fa5 192 const char *firststr = NULL, *laststr = NULL;
984263bc 193 int first, last, direction;
f2aa3fa5 194 char *pat = NULL, *repl = NULL;
984263bc
MD
195 static int active = 0;
196 struct jmploc jmploc;
99512ac4
PA
197 struct jmploc *savehandler;
198 char editfilestr[PATH_MAX];
199 char *volatile editfile;
f2aa3fa5 200 FILE *efp = NULL;
dae86e27 201 int oldhistnum;
984263bc
MD
202
203 if (hist == NULL)
204 error("history not active");
205
206 if (argc == 1)
207 error("missing history argument");
208
209 optreset = 1; optind = 1; /* initialize getopt */
210 opterr = 0;
211 while (not_fcnumber(argv[optind]) &&
212 (ch = getopt(argc, argv, ":e:lnrs")) != -1)
213 switch ((char)ch) {
214 case 'e':
215 editor = optarg;
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 case ':':
230 error("option -%c expects argument", optopt);
231 case '?':
232 default:
233 error("unknown option: -%c", optopt);
234 }
235 argc -= optind, argv += optind;
236
99512ac4 237 savehandler = handler;
984263bc
MD
238 /*
239 * If executing...
240 */
241 if (lflg == 0 || editor || sflg) {
242 lflg = 0; /* ignore */
99512ac4 243 editfile = NULL;
984263bc
MD
244 /*
245 * Catch interrupts to reset active counter and
246 * cleanup temp files.
247 */
248 if (setjmp(jmploc.loc)) {
249 active = 0;
99512ac4 250 if (editfile)
984263bc
MD
251 unlink(editfile);
252 handler = savehandler;
253 longjmp(handler->loc, 1);
254 }
984263bc
MD
255 handler = &jmploc;
256 if (++active > MAXHISTLOOPS) {
257 active = 0;
258 displayhist = 0;
259 error("called recursively too many times");
260 }
261 /*
262 * Set editor.
263 */
264 if (sflg == 0) {
265 if (editor == NULL &&
266 (editor = bltinlookup("FCEDIT", 1)) == NULL &&
267 (editor = bltinlookup("EDITOR", 1)) == NULL)
268 editor = DEFEDITOR;
269 if (editor[0] == '-' && editor[1] == '\0') {
270 sflg = 1; /* no edit */
271 editor = NULL;
272 }
273 }
274 }
275
276 /*
277 * If executing, parse [old=new] now
278 */
279 if (lflg == 0 && argc > 0 &&
280 ((repl = strchr(argv[0], '=')) != NULL)) {
281 pat = argv[0];
282 *repl++ = '\0';
283 argc--, argv++;
284 }
285 /*
286 * determine [first] and [last]
287 */
288 switch (argc) {
289 case 0:
290 firststr = lflg ? "-16" : "-1";
291 laststr = "-1";
292 break;
293 case 1:
294 firststr = argv[0];
295 laststr = lflg ? "-1" : argv[0];
296 break;
297 case 2:
298 firststr = argv[0];
299 laststr = argv[1];
300 break;
301 default:
99512ac4 302 error("too many arguments");
984263bc
MD
303 }
304 /*
305 * Turn into event numbers.
306 */
307 first = str_to_event(firststr, 0);
308 last = str_to_event(laststr, 1);
309
310 if (rflg) {
311 i = last;
312 last = first;
313 first = i;
314 }
315 /*
316 * XXX - this should not depend on the event numbers
317 * always increasing. Add sequence numbers or offset
318 * to the history element in next (diskbased) release.
319 */
320 direction = first < last ? H_PREV : H_NEXT;
321
322 /*
323 * If editing, grab a temp file.
324 */
325 if (editor) {
326 int fd;
327 INTOFF; /* easier */
99512ac4
PA
328 sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
329 if ((fd = mkstemp(editfilestr)) < 0)
984263bc 330 error("can't create temporary file %s", editfile);
99512ac4 331 editfile = editfilestr;
984263bc
MD
332 if ((efp = fdopen(fd, "w")) == NULL) {
333 close(fd);
99512ac4 334 error("Out of space");
984263bc
MD
335 }
336 }
337
338 /*
339 * Loop through selected history events. If listing or executing,
340 * do it now. Otherwise, put into temp file and call the editor
341 * after.
342 *
343 * The history interface needs rethinking, as the following
344 * convolutions will demonstrate.
345 */
9fa62156
SS
346 history(hist, &he, H_FIRST);
347 retval = history(hist, &he, H_NEXT_EVENT, first);
348 for (;retval != -1; retval = history(hist, &he, direction)) {
984263bc
MD
349 if (lflg) {
350 if (!nflg)
9fa62156
SS
351 out1fmt("%5d ", he.num);
352 out1str(he.str);
984263bc 353 } else {
99512ac4
PA
354 char *s = pat ?
355 fc_replace(he.str, pat, repl) :
356 __DECONST(char *, he.str);
984263bc
MD
357
358 if (sflg) {
359 if (displayhist) {
360 out2str(s);
99512ac4 361 flushout(out2);
984263bc 362 }
99512ac4 363 evalstring(s, 0);
984263bc
MD
364 if (displayhist && hist) {
365 /*
366 * XXX what about recursive and
367 * relative histnums.
368 */
dae86e27 369 oldhistnum = he.num;
9fa62156 370 history(hist, &he, H_ENTER, s);
dae86e27
PA
371 /*
372 * XXX H_ENTER moves the internal
373 * cursor, set it back to the current
374 * entry.
375 */
376 retval = history(hist, &he,
377 H_NEXT_EVENT, oldhistnum);
984263bc
MD
378 }
379 } else
380 fputs(s, efp);
381 }
382 /*
dae86e27 383 * At end? (if we were to lose last, we'd sure be
984263bc
MD
384 * messed up).
385 */
9fa62156 386 if (he.num == last)
984263bc
MD
387 break;
388 }
389 if (editor) {
390 char *editcmd;
391
392 fclose(efp);
393 editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
394 sprintf(editcmd, "%s %s", editor, editfile);
99512ac4 395 evalstring(editcmd, 0); /* XXX - should use no JC command */
984263bc
MD
396 INTON;
397 readcmdfile(editfile); /* XXX - should read back - quick tst */
398 unlink(editfile);
399 }
400
401 if (lflg == 0 && active > 0)
402 --active;
403 if (displayhist)
404 displayhist = 0;
99512ac4 405 handler = savehandler;
984263bc
MD
406 return 0;
407}
408
99512ac4 409static char *
984263bc
MD
410fc_replace(const char *s, char *p, char *r)
411{
412 char *dest;
413 int plen = strlen(p);
414
415 STARTSTACKSTR(dest);
416 while (*s) {
417 if (*s == *p && strncmp(s, p, plen) == 0) {
99512ac4 418 STPUTS(r, dest);
984263bc
MD
419 s += plen;
420 *p = '\0'; /* so no more matches */
421 } else
422 STPUTC(*s++, dest);
423 }
99512ac4 424 STPUTC('\0', dest);
984263bc
MD
425 dest = grabstackstr(dest);
426
427 return (dest);
428}
429
430int
99512ac4 431not_fcnumber(const char *s)
984263bc
MD
432{
433 if (s == NULL)
434 return (0);
435 if (*s == '-')
436 s++;
437 return (!is_number(s));
438}
439
440int
492efe05 441str_to_event(const char *str, int last)
984263bc 442{
9fa62156 443 HistEvent he;
492efe05 444 const char *s = str;
984263bc 445 int relative = 0;
dae86e27 446 int i, retval;
984263bc 447
dae86e27 448 retval = history(hist, &he, H_FIRST);
984263bc
MD
449 switch (*s) {
450 case '-':
451 relative = 1;
452 /*FALLTHROUGH*/
453 case '+':
454 s++;
455 }
456 if (is_number(s)) {
457 i = atoi(s);
458 if (relative) {
9fa62156
SS
459 while (retval != -1 && i--) {
460 retval = history(hist, &he, H_NEXT);
984263bc 461 }
9fa62156
SS
462 if (retval == -1)
463 retval = history(hist, &he, H_LAST);
984263bc 464 } else {
9fa62156
SS
465 retval = history(hist, &he, H_NEXT_EVENT, i);
466 if (retval == -1) {
984263bc
MD
467 /*
468 * the notion of first and last is
469 * backwards to that of the history package
470 */
9fa62156 471 retval = history(hist, &he, last ? H_FIRST : H_LAST);
984263bc
MD
472 }
473 }
9fa62156 474 if (retval == -1)
984263bc
MD
475 error("history number %s not found (internal error)",
476 str);
477 } else {
478 /*
479 * pattern
480 */
9fa62156
SS
481 retval = history(hist, &he, H_PREV_STR, str);
482 if (retval == -1)
984263bc
MD
483 error("history pattern not found: %s", str);
484 }
9fa62156 485 return (he.num);
984263bc
MD
486}
487
488int
489bindcmd(int argc, char **argv)
490{
491
492 if (el == NULL)
493 error("line editing is disabled");
9fa62156 494 return (el_parse(el, argc, (const char **)argv));
984263bc
MD
495}
496
497#else
498#include "error.h"
499
500int
29359575 501histcmd(int argc __unused, char **argv __unused)
984263bc
MD
502{
503
504 error("not compiled with history support");
505 /*NOTREACHED*/
506 return (0);
507}
508
509int
29359575 510bindcmd(int argc __unused, char **argv __unused)
984263bc
MD
511{
512
513 error("not compiled with line editing support");
514 return (0);
515}
516#endif