xref: /original-bsd/bin/csh/hist.c (revision ba762ddc)
1 /*-
2  * Copyright (c) 1980, 1991 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)hist.c	5.4 (Berkeley) 04/04/91";
10 #endif /* not lint */
11 
12 #include "sh.h"
13 
14 /*
15  * C shell
16  */
17 
18 savehist(sp)
19 	struct wordent *sp;
20 {
21 	register struct Hist *hp, *np;
22 	register int histlen = 0;
23 	char *cp;
24 
25 	/* throw away null lines */
26 	if (sp->next->word[0] == '\n')
27 		return;
28 	cp = value("history");
29 	if (*cp) {
30 		register char *p = cp;
31 
32 		while (*p) {
33 			if (!digit(*p)) {
34 				histlen = 0;
35 				break;
36 			}
37 			histlen = histlen * 10 + *p++ - '0';
38 		}
39 	}
40 	for (hp = &Histlist; np = hp->Hnext;)
41 		if (eventno - np->Href >= histlen || histlen == 0)
42 			hp->Hnext = np->Hnext, hfree(np);
43 		else
44 			hp = np;
45 	(void) enthist(++eventno, sp, 1);
46 }
47 
48 struct Hist *
49 enthist(event, lp, docopy)
50 	int event;
51 	register struct wordent *lp;
52 	bool docopy;
53 {
54 	register struct Hist *np;
55 
56 	np = (struct Hist *) xalloc(sizeof *np);
57 	np->Hnum = np->Href = event;
58 	if (docopy)
59 		copylex(&np->Hlex, lp);
60 	else {
61 		np->Hlex.next = lp->next;
62 		lp->next->prev = &np->Hlex;
63 		np->Hlex.prev = lp->prev;
64 		lp->prev->next = &np->Hlex;
65 	}
66 	np->Hnext = Histlist.Hnext;
67 	Histlist.Hnext = np;
68 	return (np);
69 }
70 
71 hfree(hp)
72 	register struct Hist *hp;
73 {
74 
75 	freelex(&hp->Hlex);
76 	xfree((char *)hp);
77 }
78 
79 dohist(vp)
80 	char **vp;
81 {
82 	int n, rflg = 0, hflg = 0;
83 	if (getn(value("history")) == 0)
84 		return;
85 	if (setintr)
86 		(void) sigsetmask(sigblock(0L) & ~sigmask(SIGINT));
87  	while (*++vp && **vp == '-') {
88  		char *vp2 = *vp;
89 
90  		while (*++vp2)
91  			switch (*vp2) {
92  			case 'h':
93  				hflg++;
94  				break;
95  			case 'r':
96  				rflg++;
97  				break;
98  			case '-':	/* ignore multiple '-'s */
99  				break;
100  			default:
101  				printf("Unknown flag: -%c\n", *vp2);
102  				error("Usage: history [-rh] [# number of events]");
103 			}
104 	}
105 	if (*vp)
106 		n = getn(*vp);
107 	else {
108 		n = getn(value("history"));
109 	}
110 	dohist1(Histlist.Hnext, &n, rflg, hflg);
111 }
112 
113 dohist1(hp, np, rflg, hflg)
114 	struct Hist *hp;
115 	int *np, rflg, hflg;
116 {
117 	bool print = (*np) > 0;
118 top:
119 	if (hp == 0)
120 		return;
121 	(*np)--;
122 	hp->Href++;
123 	if (rflg == 0) {
124 		dohist1(hp->Hnext, np, rflg, hflg);
125 		if (print)
126 			phist(hp, hflg);
127 		return;
128 	}
129 	if (*np >= 0)
130 		phist(hp, hflg);
131 	hp = hp->Hnext;
132 	goto top;
133 }
134 
135 phist(hp, hflg)
136 	register struct Hist *hp;
137 	int hflg;
138 {
139 
140 	if (hflg == 0)
141 		printf("%6d\t", hp->Hnum);
142 	prlex(&hp->Hlex);
143 }
144