xref: /original-bsd/bin/csh/hist.c (revision fbed46ce)
1 static	char *sccsid = "@(#)hist.c 4.3 11/19/81";
2 
3 #include "sh.h"
4 
5 /*
6  * C shell
7  */
8 
9 savehist(sp)
10 	struct wordent *sp;
11 {
12 	register struct Hist *hp, *np;
13 	int histlen;
14 	register char *cp;
15 
16 	cp = value("history");
17 	if (*cp == 0)
18 		histlen = 0;
19 	else {
20 		while (*cp && digit(*cp))
21 			cp++;
22 		/* avoid a looping snafu */
23 		if (*cp)
24 			set("history", "10");
25 		histlen = getn(value("history"));
26 	}
27 	/* throw away null lines */
28 	if (sp->next->word[0] == '\n')
29 		return;
30 	for (hp = &Histlist; np = hp->Hnext;)
31 		if (eventno - np->Href >= histlen || histlen == 0)
32 			hp->Hnext = np->Hnext, hfree(np);
33 		else
34 			hp = np;
35 	enthist(++eventno, sp, 1);
36 }
37 
38 struct Hist *
39 enthist(event, lp, docopy)
40 	int event;
41 	register struct wordent *lp;
42 	bool docopy;
43 {
44 	register struct Hist *np;
45 
46 	np = (struct Hist *) calloc(1, sizeof *np);
47 	np->Hnum = np->Href = event;
48 	if (docopy)
49 		copylex(&np->Hlex, lp);
50 	else {
51 		np->Hlex.next = lp->next;
52 		lp->next->prev = &np->Hlex;
53 		np->Hlex.prev = lp->prev;
54 		lp->prev->next = &np->Hlex;
55 	}
56 	np->Hnext = Histlist.Hnext;
57 	Histlist.Hnext = np;
58 	return (np);
59 }
60 
61 hfree(hp)
62 	register struct Hist *hp;
63 {
64 
65 	freelex(&hp->Hlex);
66 	xfree((char *)hp);
67 }
68 
69 dohist(vp)
70 	char **vp;
71 {
72 	int n, rflg = 0, hflg = 0;
73 	if (getn(value("history")) == 0)
74 		return;
75 	if (setintr)
76 		sigrelse(SIGINT);
77 	vp++;
78 	while (*vp[0] == '-') {
79 		if (*vp && eq(*vp, "-h")) {
80 			hflg++;
81 			vp++;
82 		}
83 		if (*vp && eq(*vp, "-r")) {
84 			rflg++;
85 			vp++;
86 		}
87 	}
88 	if (*vp)
89 		n = getn(*vp);
90 	else {
91 		n = getn(value("history"));
92 	}
93 	dohist1(Histlist.Hnext, &n, rflg, hflg);
94 }
95 
96 dohist1(hp, np, rflg, hflg)
97 	struct Hist *hp;
98 	int *np, rflg, hflg;
99 {
100 	bool print = (*np) > 0;
101 top:
102 	if (hp == 0)
103 		return;
104 	(*np)--;
105 	hp->Href++;
106 	if (rflg == 0) {
107 		dohist1(hp->Hnext, np, rflg, hflg);
108 		if (print)
109 			phist(hp, hflg);
110 		return;
111 	}
112 	if (*np >= 0)
113 		phist(hp, hflg);
114 	hp = hp->Hnext;
115 	goto top;
116 }
117 
118 phist(hp, hflg)
119 	register struct Hist *hp;
120 	int hflg;
121 {
122 
123 	if (hflg == 0)
124 		printf("%6d\t", hp->Hnum);
125 	prlex(&hp->Hlex);
126 }
127