aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/htmlroff/t16.c
blob: 9389a59afccc44a79f0dcd51d19ee74821d37337 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#include "a.h"

/*
 * 16. Conditional acceptance of input.
 *
 *	conditions are
 *		c - condition letter (o, e, t, n)
 *		!c - not c
 *		N - N>0
 *		!N - N <= 0
 *		'a'b' - if a==b
 *		!'a'b'	- if a!=b
 *
 *	\{xxx\} can be used for newline in bodies
 *
 *	.if .ie .el
 *
 */

int iftrue[20];
int niftrue;

void
startbody(void)
{
	int c;

	while((c = getrune()) == ' ' || c == '\t')
		;
	ungetrune(c);
}

void
skipbody(void)
{
	int c, cc, nbrace;

	nbrace = 0;
	for(cc=0; (c = getrune()) >= 0; cc=c){
		if(c == '\n' && nbrace <= 0)
			break;
		if(cc == '\\' && c == '{')
			nbrace++;
		if(cc == '\\' && c == '}')
			nbrace--;
	}
}

int
ifeval(void)
{
	int c, cc, neg, nc;
	Rune line[MaxLine], *p, *e, *q;
	Rune *a;

	while((c = getnext()) == ' ' || c == '\t')
		;
	neg = 0;
	while(c == '!'){
		neg = !neg;
		c = getnext();
	}

	if('0' <= c && c <= '9'){
		ungetnext(c);
		a = copyarg();
		c = (eval(a)>0) ^ neg;
		free(a);
		return c;
	}

	switch(c){
	case ' ':
	case '\n':
		ungetnext(c);
		return !neg;
	case 'o':	/* odd page */
	case 't':	/* troff */
	case 'h':	/* htmlroff */
		while((c = getrune()) != ' ' && c != '\t' && c != '\n' && c >= 0)
			;
		return 1 ^ neg;
	case 'n':	/* nroff */
	case 'e':	/* even page */
		while((c = getnext()) != ' ' && c != '\t' && c != '\n' && c >= 0)
			;
		return 0 ^ neg;
	}

	/* string comparison 'string1'string2' */
	p = line;
	e = p+nelem(line);
	nc = 0;
	q = nil;
	while((cc=getnext()) >= 0 && cc != '\n' && p<e){
		if(cc == c){
			if(++nc == 2)
				break;
			q = p;
		}
		*p++ = cc;
	}
	if(cc != c){
		ungetnext(cc);
		return 0;
	}
	if(nc < 2){
		return 0;
	}
	*p = 0;
	return (q-line == p-(q+1)
		&& memcmp(line, q+1, (q-line)*sizeof(Rune))==0) ^ neg;
}

void
r_if(Rune *name)
{
	int n;

	n = ifeval();
	if(runestrcmp(name, L("ie")) == 0){
		if(niftrue >= nelem(iftrue))
			sysfatal("%Cie overflow", dot);
		iftrue[niftrue++] = n;
	}
	if(n)
		startbody();
	else
		skipbody();
}

void
r_el(Rune *name)
{
	USED(name);

	if(niftrue <= 0){
		warn("%Cel underflow", dot);
		return;
	}
	if(iftrue[--niftrue])
		skipbody();
	else
		startbody();
}

void
t16init(void)
{
	addraw(L("if"), r_if);
	addraw(L("ie"), r_if);
	addraw(L("el"), r_el);

	addesc('{', e_nop, HtmlMode|ArgMode);
	addesc('}', e_nop, HtmlMode|ArgMode);
}