-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrap.c
68 lines (57 loc) · 1.33 KB
/
wrap.c
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
#include <ctype.h>
#include <string.h>
#include "buf.h"
void wrap(struct buf_s *buf, const char *src, int width);
int wrap_lines(const char *str);
void wrap(struct buf_s *buf, const char *src, int width) {
int wlen, llen, rlen, i;
wlen = 0;
llen = 0;
while (*src) {
if ((wlen = strspn(src, " \r\t"))) {
src += wlen;
rlen += wlen;
} else if (*src == '\n') {
buf_append(buf, "\n", 1);
src++;
llen = 0;
} else if ((wlen = strcspn(src, " \n\t"))) {
if (llen + wlen >= width) {
if (wlen > width) {
for (i = 0; i < wlen; i += width - 1) {
buf_append(buf, "\n", 1);
if (wlen - i > width - 1) {
buf_append(buf, &(src[i]), width - 1);
buf_append(buf, "-", 1);
} else {
buf_append(buf, &(src[i]), wlen - i);
}
}
} else {
buf_append(buf, "\n", 1);
buf_append(buf, src, wlen);
llen = wlen;
}
} else {
if (llen > 0) {
buf_append(buf, " ", 1);
llen += 1;
}
buf_append(buf, src, wlen);
llen += wlen;
}
src += wlen;
}
}
}
int wrap_lines(const char *str) {
char c;
int n;
n = 1;
while ((c = *str++)) {
if (c == '\n') {
n += 1;
}
}
return n;
}