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