1#include "toys.h"
2
3
4
5
6int crunch_str(char **str, int width, FILE *out, char *escmore,
7 int (*escout)(FILE *out, int cols, int wc))
8{
9 int columns = 0, col, bytes;
10 char *start, *end;
11 unsigned wc;
12
13 for (end = start = *str; *end; columns += col, end += bytes) {
14 if ((bytes = utf8towc(&wc, end, 4))>0 && (col = wcwidth(wc))>=0) {
15 if (!escmore || wc>255 || !strchr(escmore, wc)) {
16 if (width-columns<col) break;
17 if (out) fwrite(end, bytes, 1, out);
18
19 continue;
20 }
21 }
22
23 if (bytes<1) {
24 bytes = 1;
25 wc = *end;
26 }
27 col = width-columns;
28 if (col<1) break;
29 if (escout) {
30 if ((col = escout(out, col, wc))<0) break;
31 } else if (out) fwrite(end, 1, bytes, out);
32 }
33 *str = end;
34
35 return columns;
36}
37
38
39
40int crunch_escape(FILE *out, int cols, int wc)
41{
42 char buf[11];
43 int rc;
44
45 if (wc<' ') rc = sprintf(buf, "^%c", '@'+wc);
46 else if (wc<256) rc = sprintf(buf, "<%02X>", wc);
47 else rc = sprintf(buf, "U+%04X", wc);
48
49 if (rc > cols) buf[rc = cols] = 0;
50 if (out) fputs(buf, out);
51
52 return rc;
53}
54
55
56int crunch_rev_escape(FILE *out, int cols, int wc)
57{
58 int rc;
59
60 xputsn("\e[7m");
61 rc = crunch_escape(out, cols, wc);
62 xputsn("\e[27m");
63
64 return rc;
65}
66
67
68
69int draw_str(char *start, int width)
70{
71 return crunch_str(&start, width, stdout, 0, crunch_rev_escape);
72}
73
74
75int utf8len(char *str)
76{
77 return crunch_str(&str, INT_MAX, 0, 0, crunch_rev_escape);
78}
79
80
81int utf8skip(char *str, int width)
82{
83 char *s = str;
84
85 crunch_str(&s, width, 0, 0, crunch_rev_escape);
86
87 return s-str;
88}
89
90
91
92int draw_trim_esc(char *str, int padto, int width, char *escmore,
93 int (*escout)(FILE *out, int cols, int wc))
94{
95 int apad = abs(padto), len = utf8len(str);
96
97 if (padto>=0 && len>width) str += utf8skip(str, len-width);
98 if (len>width) len = width;
99
100
101 if (padto>0 && apad>len) printf("%*s", apad-len, "");
102 crunch_str(&str, len, stdout, 0, crunch_rev_escape);
103 if (padto<0 && apad>len) printf("%*s", apad-len, "");
104
105 return (apad > len) ? apad : len;
106}
107
108
109int draw_trim(char *str, int padto, int width)
110{
111 return draw_trim_esc(str, padto, width, 0, 0);
112}
113