xref: /original-bsd/bin/sh/histedit.c (revision 68d9582f)
1 /*
2  * Editline and history functions (and glue).
3  */
4 #include <stdio.h>
5 #include "parser.h"
6 #include "options.h"
7 #include "error.h"
8 
9 #include "histedit.h"
10 
11 History *hist;	/* history cookie */
12 EditLine *el;	/* editline cookie */
13 static FILE *el_in, *el_out;
14 
15 extern int is_interactive;
16 
17 /*
18  * Set history and editing status.  Called whenever the status may
19  * have changed (figures out what to do).
20  */
21 histedit() {
22 
23 	if (is_interactive) {
24 		if (!hist) {
25 			/*
26 			 * turn history on
27 			 */
28 			INTOFF;
29 			hist = history_init();
30 			INTON;
31 
32 			if (hist != NULL)
33 				sethistsize();
34 			else
35 				out2str("sh: can't initialize history\n");
36 		}
37 		if (Eflag && !el && isatty(0)) { /* && isatty(2) ??? */
38 			/*
39 			 * turn editing on
40 			 */
41 			INTOFF;
42 			if (el_in == NULL)
43 				el_in = fdopen(0, "r");
44 			if (el_out == NULL)
45 				el_out = fdopen(2, "w");
46 			if (el_in == NULL || el_out == NULL)
47 				goto bad;
48 			el = el_init(arg0, el_in, el_out);
49 			if (el != NULL) {
50 				if (hist)
51 					el_set(el, EL_HIST, history_set, hist);
52 				el_set(el, EL_PROMPT, getprompt);
53 			} else {
54 bad:
55 				out2str("sh: can't initialize editing\n");
56 			}
57 			INTON;
58 			if (el)	/* XXX - -o vi etc... */
59 				el_set(el, EL_EDITOR, "vi");
60 		} else if (!Eflag && el) {
61 			INTOFF;
62 			el_end(el);
63 			el = NULL;
64 			INTON;
65 		}
66 	} else {
67 		INTOFF;
68 		if (el) {	/* no editing if not interactive */
69 			el_end(el);
70 			el = NULL;
71 		}
72 		if (hist) {
73 			history_end(hist);
74 			hist = NULL;
75 		}
76 		INTON;
77 	}
78 }
79 
80 sethistsize() {
81 	char *cp;
82 	int histsize;
83 
84 	if (hist != NULL) {
85 		cp = lookupvar("HISTSIZE");
86 		if (cp == NULL || *cp == '\0' ||
87 		   (histsize = atoi(cp)) < 0)
88 			histsize = 100;
89 		history_set(hist, H_EVENT, histsize);
90 	}
91 }
92