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
|
implement P;
# Original by Steve Arons, based on Plan 9 p
include "sys.m";
sys: Sys;
FD: import Sys;
include "draw.m";
include "string.m";
str: String;
include "bufio.m";
bufio: Bufio;
Iobuf: import bufio;
include "sh.m";
stderr: ref FD;
outb, cons: ref Iobuf;
drawctxt: ref Draw->Context;
nlines := 22; # 1/3rd 66-line nroff page (!)
progname := "p";
P: module
{
init: fn(ctxt: ref Draw->Context, argv: list of string);
};
usage()
{
sys->fprint(stderr, "Usage: p [-number] [file...]\n");
raise "fail:usage";
}
init(ctxt: ref Draw->Context, argv: list of string)
{
sys = load Sys Sys->PATH;
bufio = load Bufio Bufio->PATH;
if(bufio == nil)
nomod(Bufio->PATH);
str = load String String->PATH;
if(str == nil)
nomod(String->PATH);
sys->pctl(Sys->FORKFD, nil);
drawctxt = ctxt;
stderr = sys->fildes(2);
if((stdout := sys->fildes(1)) != nil)
outb = bufio->fopen(stdout, bufio->OWRITE);
if(outb == nil){
sys->fprint(stderr, "p: can't open stdout: %r\n");
raise "fail:stdout";
}
cons = bufio->open("/dev/cons", bufio->OREAD);
if(cons == nil){
sys->fprint(stderr, "p: can't open /dev/cons: %r\n");
raise "fail:cons";
}
if(argv != nil){
progname = hd argv;
argv = tl argv;
if(argv != nil){
s := hd argv;
if(len s > 1 && s[0] == '-'){
(x, y) := str->toint(s[1:],10);
if(y == "" && x > 0)
nlines = x;
else
usage();
argv = tl argv;
}
}
}
if(argv == nil)
argv = "-" :: nil;
for(; argv != nil; argv = tl argv){
file := hd argv;
fd: ref Sys->FD;
if(file == "-"){
file = "stdin";
fd = sys->fildes(0);
}else
fd = sys->open(file, Sys->OREAD);
if(fd == nil){
sys->fprint(stderr, "%s: can't open %s: %r\n", progname, file);
continue;
}
page(fd);
fd = nil;
}
}
nomod(m: string)
{
sys->fprint(sys->fildes(2), "%s: can't load %s: %r\n", progname, m);
raise "fail:load";
}
page(fd: ref Sys->FD)
{
inb := bufio->fopen(fd, bufio->OREAD);
nl := nlines;
while((line := inb.gets('\n')) != nil){
outb.puts(line);
if(--nl == 0){
outb.flush();
nl = nlines;
pause();
}
}
outb.flush();
}
pause()
{
for(;;){
cmdline := cons.gets('\n');
if(cmdline == nil || cmdline[0] == 'q') # catch ^d
exit;
else if(cmdline[0] == '!') {
done := chan of int;
spawn command(cmdline[1:], done);
<-done;
}else
break;
}
}
command(cmdline: string, done: chan of int)
{
sh := load Sh Sh->PATH;
if(sh == nil) {
sys->fprint(stderr, "%s: can't load %s: %r\n", progname, Sh->PATH);
done <-= 0;
return;
}
sys->pctl(Sys->FORKFD, nil);
sys->dup(cons.fd.fd, 0);
sh->system(drawctxt, cmdline);
done <-= 1;
}
|