1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24#define FOR_fold
25#include "toys.h"
26
27GLOBALS(
28 int width;
29)
30
31
32void do_fold(int fd, char *name)
33{
34 int bufsz, len = 0, maxlen;
35
36 if (toys.optflags & FLAG_w) maxlen = TT.width;
37 else if (toys.optflags & FLAG_u) maxlen = 0;
38 else maxlen = 80;
39
40 while ((bufsz = read(fd, toybuf, sizeof(toybuf))) > 0) {
41 char *buf = toybuf;
42 int pos = 0, split = -1;
43
44 while (pos < bufsz) {
45 switch (buf[pos]) {
46 case '\n':
47
48 if ((toys.optflags & FLAG_u) && buf[pos-1] != '\n'
49 && buf[pos+1] != '\n') {
50 xwrite(1, buf, pos);
51 bufsz -= pos + 1;
52 buf += pos + 1;
53 pos = 0;
54 split = -1;
55
56 } else len = 0;
57 break;
58 case '\b':
59
60 if (toys.optflags & FLAG_b) len++;
61 else if (len > 0) len--;
62 break;
63 case '\r':
64
65 if (toys.optflags & FLAG_b) len++;
66 else len = 0;
67 break;
68 case '\t':
69
70
71 if (!(toys.optflags & FLAG_b)) len = (len & ~7) + 7;
72 case ' ':
73 split = pos;
74 default:
75 len++;
76 }
77
78
79 if (maxlen > 0 && len >= maxlen && buf[pos+1] != '\n' && buf[pos+1] != '\b') {
80 if (!(toys.optflags & FLAG_s) || split < 0) split = pos;
81 xwrite(1, buf, split + 1);
82 xputc('\n');
83 bufsz -= split + 1;
84 buf += split + 1;
85 len = pos = 0;
86 split = -1;
87 } else pos++;
88 }
89 xwrite(1, buf, bufsz);
90 }
91 xputc('\n');
92}
93
94void fold_main(void)
95{
96 loopfiles(toys.optargs, do_fold);
97}
98