summaryrefslogtreecommitdiff
path: root/sys/src/cmd/rc/here.c
blob: c148430ffeb9d89ee361648cd61a0e7efc427d34 (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
#include "rc.h"
#include "exec.h"
#include "io.h"
#include "fns.h"

void psubst(io*, unsigned char*);
void pstrs(io*, word*);

char*
readhere(tree *tag, io *in)
{
	io *out;
	char c, *m;

	if(tag->type!=WORD){
		yyerror("Bad here tag");
		return 0;
	}
	pprompt();
	out = openiostr();
	m = tag->str;
	while((c = rchr(in)) != EOF){
		if(c=='\0'){
			yyerror("NUL bytes in here doc");
			closeio(out);
			return 0;
		}
		if(c=='\n'){
			lex->line++;
			if(m && *m=='\0'){
				out->bufp -= m - tag->str;
				*out->bufp='\0';
				break;
			}
			pprompt();
			m = tag->str;
		} else if(m){
			if(*m == c){
				m++;
			} else {
				m = 0;
			}
		}
		pchr(out, c);
	}
	doprompt = 1;
	return closeiostr(out);
}

void
psubst(io *f, unsigned char *s)
{
	unsigned char *t, *u;
	word *star;
	int savec, n;

	while(*s){
		if(*s!='$'){
			if(0xa0 <= *s && *s <= 0xf5){
				pchr(f, *s++);
				if(*s=='\0')
					break;
			}
			else if(0xf6 <= *s && *s <= 0xf7){
				pchr(f, *s++);
				if(*s=='\0')
					break;
				pchr(f, *s++);
				if(*s=='\0')
					break;
			}
			pchr(f, *s++);
		}
		else{
			t=++s;
			if(*t=='$')
				pchr(f, *t++);
			else{
				while(*t && idchr(*t)) t++;
				savec=*t;
				*t='\0';
				n = 0;
				for(u = s;*u && '0'<=*u && *u<='9';u++) n = n*10+*u-'0';
				if(n && *u=='\0'){
					star = vlook("*")->val;
					if(star && 1<=n && n<=count(star)){
						while(--n) star = star->next;
						pstr(f, star->word);
					}
				}
				else
					pstrs(f, vlook((char *)s)->val);
				*t = savec;
				if(savec=='^')
					t++;
			}
			s = t;
		}
	}
}

void
pstrs(io *f, word *a)
{
	if(a){
		while(a->next && a->next->word){
			pstr(f, a->word);
			pchr(f, ' ');
			a = a->next;
		}
		pstr(f, a->word);
	}
}