Debian Codegraph @

filters/wrap.c

raw
1 /* SPDX-License-Identifier: MIT */
2 /* Copyright (c) 2023 Robin Jarry */
3
4 #ifndef __NetBSD__
5 #define _XOPEN_SOURCE 700
6 #endif
7 #include <errno.h>
8 #include <getopt.h>
9 #include <langinfo.h>
10 #include <locale.h>
11 #include <regex.h>
12 #include <stdbool.h>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <wchar.h>
18 #include <wctype.h>
19
20 #ifdef __APPLE__
21 #include <xlocale.h>
22 #endif
23
24 static void usage(void)
25 {
26 puts("usage: wrap [-h] [-w INT] [-r] [-l INT] [-f FILE]");
27 puts("");
28 puts("Wrap text without messing up email quotes.");
29 puts("");
30 puts("options:");
31 puts(" -h show this help message");
32 puts(" -w INT preferred wrap margin (default 80)");
33 puts(" -r reflow all paragraphs even if no trailing space");
34 puts(" -l INT minimum percentage of letters in a line to be");
35 puts(" considered a paragraph");
36 puts(" -f FILE read from filename (default stdin)");
37 }
38
39 static size_t margin = 80;
40 static size_t prose_ratio = 50;
41 static bool reflow;
42 static FILE *in_file;
43
44 static int parse_args(int argc, char **argv)
45 {
46 const char *filename = NULL;
47 long value;
48 int c;
49
50 while ((c = getopt(argc, argv, "hrw:l:f:")) != -1) {
51 errno = 0;
52 switch (c) {
53 case 'r':
54 reflow = true;
55 break;
56 case 'l':
57 value = strtol(optarg, NULL, 10);
58 if (errno) {
59 perror("error: invalid ratio value");
60 return 1;
61 }
62 if (value <= 0 || value >= 100) {
63 fprintf(stderr, "error: ratio must be ]0,100[\n");
64 return 1;
65 }
66 prose_ratio = (size_t)value;
67 break;
68 case 'w':
69 value = strtol(optarg, NULL, 10);
70 if (errno) {
71 perror("error: invalid width value");
72 return 1;
73 }
74 if (value < 1) {
75 fprintf(stderr, "error: width must be positive\n");
76 return 1;
77 }
78 margin = (size_t)value;
79 break;
80 case 'f':
81 filename = optarg;
82 break;
83 default:
84 usage();
85 return 1;
86 }
87 }
88 if (optind < argc) {
89 fprintf(stderr, "%s: unexpected argument -- '%s'\n",
90 argv[0], argv[optind]);
91 usage();
92 return 1;
93 }
94 if (filename == NULL || !strcmp(filename, "-")) {
95 in_file = stdin;
96 } else {
97 in_file = fopen(filename, "r");
98 if (!in_file) {
99 perror("error: cannot open file");
100 return 1;
101 }
102 }
103 return 0;
104 }
105
106 static bool is_empty(const wchar_t *s)
107 {
108 while (*s != L'\0') {
109 if (!iswspace((wint_t)*s++))
110 return false;
111 }
112 return true;
113 }
114
115 __attribute__((malloc,returns_nonnull))
116 static void *xmalloc(size_t s)
117 {
118 void *ptr = malloc(s);
119 if (ptr == NULL) {
120 perror("fatal: cannot allocate buffer");
121 abort();
122 }
123 return ptr;
124 }
125
126 __attribute__((malloc,returns_nonnull))
127 static void *xrealloc(void *ptr, size_t s)
128 {
129 ptr = realloc(ptr, s);
130 if (ptr == NULL) {
131 perror("fatal: cannot reallocate buffer");
132 abort();
133 }
134 return ptr;
135 }
136
137 struct paragraph {
138 /* email quote prefix, if any */
139 wchar_t *quotes;
140 /* list item indent, if any */
141 wchar_t *indent;
142 /* actual text of this paragraph */
143 wchar_t *text;
144 /* percentage of letters in text */
145 size_t prose_ratio;
146 /* text ends with a space */
147 bool flowed;
148 /* paragraph is a list item */
149 bool list_item;
150 };
151
152 static void free_paragraph(struct paragraph *p)
153 {
154 if (!p)
155 return;
156 free(p->quotes);
157 free(p->indent);
158 free(p->text);
159 free(p);
160 }
161
162 static wchar_t *read_part(const wchar_t *in, size_t len)
163 {
164 wchar_t *out = xmalloc((len + 1) * sizeof(wchar_t));
165 wcsncpy(out, in, len);
166 out[len] = L'\0';
167 return out;
168 }
169
170 static size_t list_item_offset(const wchar_t *buf)
171 {
172 size_t i = 0;
173 wchar_t c;
174
175 if (buf[i] == L'-' || buf[i] == '*' || buf[i] == '.') {
176 /* bullet list */
177 i++;
178 } else if (iswdigit((wint_t)buf[i])) {
179 /* numbered list */
180 i++;
181 if (iswdigit((wint_t)buf[i])) {
182 i++;
183 }
184 } else if (iswalpha((wint_t)buf[i])) {
185 /* lettered list */
186 c = (wchar_t)towlower((wint_t)buf[i]);
187 i++;
188 if (c == L'i' || c == L'v') {
189 /* roman i. ii. iii. iv. ... */
190 c = (wchar_t)towlower((wint_t)buf[i]);
191 while (i < 4 && (c == L'i' || c == L'v')) {
192 c = (wchar_t)towlower((wint_t)buf[++i]);
193 }
194 }
195 } else {
196 return 0;
197 }
198 if (iswdigit((wint_t)buf[0]) || iswalpha((wint_t)buf[0])) {
199 if (buf[i] == L')' || buf[i] == L'/' || buf[i] == L'.') {
200 i++;
201 } else {
202 return 0;
203 }
204 }
205 if (buf[i] == L' ') {
206 i++;
207 } else {
208 return 0;
209 }
210
211 return i;
212 }
213
214 static bool is_cjk(wchar_t c, bool include_syllables) {
215 /* CJK Radicals Supplement */
216 if (c >= 0x2e80 && c <= 0x2fd5)
217 return true;
218 /* CJK Compatibility */
219 if (c >= 0x3300 && c <= 0x33ff)
220 return true;
221 /* CJK Unified Ideographs Extension A */
222 if (c >= 0x3400 && c <= 0x4db5)
223 return true;
224 /* CJK Unified Ideographs */
225 if (c >= 0x4e00 && c <= 0x9fcb)
226 return true;
227 /* CJK Compatibility Ideographs */
228 if (c >= 0xf900 && c <= 0xfa6a)
229 return true;
230 /* Hangul Jamo */
231 if (c >= 0x1100 && c <= 0x11ff)
232 return true;
233 /* Hangul Compatibility Jamo */
234 if (c >= 0x3130 && c <= 0x318f)
235 return true;
236 /* Hangul Jamo Extended-A */
237 if (c >= 0xa960 && c <= 0xa97f)
238 return true;
239 /* Hangul Jamo Extended-B */
240 if (c >= 0xd7b0 && c <= 0xd7ff)
241 return true;
242
243 if (include_syllables) {
244 /* Japanese Hiragana */
245 if (c >= 0x3040 && c <= 0x309f)
246 return true;
247 /* Japanese Katakana */
248 if (c >= 0x30a0 && c <= 0x30ff)
249 return true;
250 /* Hangul Syllables */
251 if (c >= 0xac00 && c <= 0xd7af)
252 return true;
253 }
254 return false;
255 }
256
257 static struct paragraph *parse_line(const wchar_t *buf)
258 {
259 size_t i, q, t, e, letters, indent_len, text_len;
260 bool list_item, flowed;
261 struct paragraph *p;
262
263 /*
264 * Find relevant positions in the line:
265 *
266 * '> > > > 2) blah blah blah blah '
267 * ^ ^ ^ ^
268 * 0 q t e
269 * <------><------------->
270 * quotes indent
271 * <-------------------------------->
272 * text
273 */
274
275 /* detect the end of quotes prefix if any */
276 q = 0;
277 while (buf[q] == L'>') {
278 q++;
279 if (buf[q] == L' ') {
280 q++;
281 }
282 }
283 /* detect list item prefix & indent */
284 t = q;
285 while (iswspace((wint_t)buf[t])) {
286 t++;
287 }
288 i = list_item_offset(&buf[t]);
289 list_item = i != 0;
290 t += i;
291 while (iswspace((wint_t)buf[t])) {
292 t++;
293 }
294 indent_len = t - q;
295 /* compute prose ratio */
296 e = t;
297 letters = 0;
298 while (buf[e] != L'\0') {
299 wchar_t c = buf[e++];
300 if (iswalpha((wint_t)c) || is_cjk(c, true)) {
301 letters++;
302 }
303 }
304 /* strip trailing whitespace unless it is a signature delimiter */
305 flowed = false;
306 if (wcscmp(&buf[q], L"-- ") != 0) {
307 while (e > q && iswspace((wint_t)buf[e - 1])) {
308 e--;
309 flowed = true;
310 }
311 }
312 text_len = e - q;
313
314 p = xmalloc(sizeof(*p));
315 memset(p, 0, sizeof(*p));
316 p->quotes = read_part(buf, q);
317 p->indent = xmalloc((indent_len + 1) * sizeof(wchar_t));
318 for (i = 0; i < indent_len; i++)
319 p->indent[i] = L' ';
320 p->indent[i] = L'\0';
321 p->text = read_part(&buf[q], text_len);
322 p->flowed = flowed;
323 p->list_item = list_item;
324 p->prose_ratio = 100 * letters / (text_len ? text_len : 1);
325
326 return p;
327 }
328
329 static bool is_continuation(
330 const struct paragraph *p, const struct paragraph *next
331 ) {
332 if (next->list_item)
333 /* new list items always start a new paragraph */
334 return false;
335 if (next->prose_ratio < prose_ratio || p->prose_ratio < prose_ratio)
336 /* does not look like prose, maybe ascii art */
337 return false;
338 if (wcscmp(next->quotes, p->quotes) != 0)
339 /* quote prefix has changed */
340 return false;
341 if (wcscmp(next->indent, p->indent) != 0)
342 /* list item indent has changed */
343 return false;
344 if (is_empty(next->text))
345 /* empty or whitespace only line */
346 return false;
347 if (wcscmp(p->text, L"--") == 0 || wcscmp(p->text, L"-- ") == 0)
348 /* never join anything with signature start */
349 return false;
350 if (p->flowed)
351 /* current paragraph has trailing space, indicating
352 * format=flowed */
353 return true;
354 if (reflow)
355 /* user forced paragraph reflow on the command line */
356 return true;
357 return false;
358 }
359
360 static void join_paragraph(
361 struct paragraph *p, const struct paragraph *next
362 ) {
363 const wchar_t *append = next->text;
364 const wchar_t *separator = L" ";
365 size_t len, extra_len;
366 wchar_t *text;
367
368 /* trim leading whitespace of the next paragraph before joining */
369 while (*append != L'\0' && iswspace((wint_t)*append))
370 append++;
371
372 len = wcslen(p->text);
373 if (len == 0) {
374 separator = L"";
375 }
376 extra_len = wcslen(separator) + wcslen(append) + 1;
377
378 text = xrealloc(p->text, (len + extra_len) * sizeof(wchar_t));
379 swprintf(&text[len], extra_len, L"%ls%ls", separator, append);
380
381 p->text = text;
382 p->prose_ratio = (p->prose_ratio + next->prose_ratio) / 2;
383 p->flowed = next->flowed;
384 }
385
386 /*
387 * BUFSIZ has different values depending on the libc implementation.
388 * Use a self defined value to have consistent behaviour across all platforms.
389 */
390 #define BUFFER_SIZE 8192
391
392 /*
393 * Check if a line can be split at the given character point.
394 */
395 static bool is_split_point(const wchar_t c)
396 {
397 if (iswspace((wint_t)c))
398 return true;
399
400 if (is_cjk(c, false))
401 return true;
402
403 return false;
404 }
405
406 /*
407 * Write a paragraph, wrapping at words boundaries.
408 *
409 * Only try to do word wrapping on things that look like prose. When the text
410 * contains too many non-letter characters, print it as-is.
411 */
412 static void write_paragraph(struct paragraph *p)
413 {
414 size_t quotes_width = (size_t)wcswidth(p->quotes, wcslen(p->quotes));
415 size_t remain = (size_t)wcswidth(p->text, wcslen(p->text));
416 const wchar_t *indent = L"";
417 wchar_t *text = p->text;
418 bool more = true;
419 int wchar_count;
420 wchar_t *line;
421 size_t width;
422
423 while (more) {
424 width = quotes_width + (size_t)wcswidth(indent, wcslen(indent));
425
426 if (width + remain <= margin || p->prose_ratio < prose_ratio) {
427 /* whole paragraph fits on a single line */
428 line = text;
429 wchar_count = (int)wcslen(text);
430 more = false;
431 } else {
432 /* find split point, preferably before margin */
433 size_t split = SIZE_MAX;
434 size_t w = 0;
435 for (size_t i = 0; text[i] != L'\0'; i++) {
436 w += (size_t)wcwidth(text[i]);
437 if (width + w > margin && split != SIZE_MAX) {
438 break;
439 }
440 if (is_split_point(text[i])) {
441 split = i;
442 }
443 }
444 if (split == SIZE_MAX) {
445 /* no space found to split, print a long line */
446 line = text;
447 wchar_count = (int)wcslen(text);
448 more = false;
449 } else {
450 wchar_count = (int)split;
451 line = text;
452 /* find start of next word */
453 while (iswspace((wint_t)text[split])) {
454 split++;
455 }
456 if (text[split] != L'\0') {
457 remain -= (size_t)wcswidth(text, split);
458 text = &text[split];
459 } else {
460 /* only trailing whitespace, we're done */
461 more = false;
462 }
463 }
464 }
465 wprintf(L"%ls%ls%.*ls\n", p->quotes, indent, wchar_count, line);
466 indent = p->indent;
467 }
468 }
469
470 #define SPACES_PER_TAB 8
471
472 /*
473 * Trim LF CR CRLF LFCR and replace tabs with spaces.
474 */
475 static void sanitize_line(const wchar_t *in, wchar_t *out)
476 {
477 /* No bounds checking needed. This function is only used with
478 * 'buf' and 'line' buffers from main. 'out' is large enough no
479 * matter what is present in 'in'. */
480 while (*in != L'\0' && *in != L'\n' && *in != L'\r') {
481 if (*in == L'\t') {
482 /* tabs cause indentation/alignment issues
483 * replace them with 8 spaces */
484 in++;
485 for (int i = 0; i < SPACES_PER_TAB; i++)
486 *out++ = L' ';
487 } else {
488 *out++ = *in++;
489 }
490 }
491 *out = L'\0';
492 }
493
494 static int set_stdio_encoding(void)
495 {
496 const char *locale = setlocale(LC_ALL, "");
497
498 if (!locale) {
499 /* Neither LC_ALL nor LANG env vars are defined or are set to
500 * a non existent/installed locale. Try with a generic UTF-8
501 * locale which is expected to be available on all POSIX
502 * systems. */
503 locale = setlocale(LC_ALL, "C.UTF-8");
504 if (!locale) {
505 /* The system is not following POSIX standards. Last
506 * resort: check if 'UTF-8' (encoding only) exists. */
507 locale = setlocale(LC_CTYPE, "UTF-8");
508 }
509 }
510 if (!locale) {
511 perror("error: failed to set locale");
512 return 1;
513 }
514
515 /* aerc will always send UTF-8 text, ensure that we read that properly */
516 locale_t loc = newlocale(LC_ALL_MASK, locale, NULL);
517 char *codeset = nl_langinfo_l(CODESET, loc);
518 freelocale(loc);
519 if (!strstr(codeset, "UTF-8")) {
520 fprintf(stderr, "error: locale '%s' is not UTF-8\n", locale);
521 return 1;
522 }
523
524 /* ensure files are configured to read/write wide characters */
525 fwide(in_file, true);
526 fwide(stdout, true);
527
528 return 0;
529 }
530
531 int main(int argc, char **argv)
532 {
533 /* line needs to be 8 times larger than buf since every read character
534 * may be a tab (very unlikely, but it could happen). */
535 static wchar_t buf[BUFFER_SIZE], line[BUFFER_SIZE * SPACES_PER_TAB];
536 struct paragraph *cur = NULL, *next;
537 bool is_patch = false;
538 regmatch_t groups[2];
539 char *subject;
540 regex_t re;
541 int err;
542
543 err = parse_args(argc, argv);
544 if (err)
545 goto end;
546
547 regcomp(&re, "\\<PATCH\\>", REG_EXTENDED);
548 subject = getenv("AERC_SUBJECT");
549 if (subject && !regexec(&re, subject, 2, groups, 0))
550 is_patch = true;
551 regfree(&re);
552
553 err = set_stdio_encoding();
554 if (err)
555 goto end;
556
557 while (fgetws(buf, BUFFER_SIZE, in_file)) {
558 if (is_patch) {
559 /* never reflow patches */
560 fputws(buf, stdout);
561 continue;
562 }
563 sanitize_line(buf, line);
564 next = parse_line(line);
565 if (!cur) {
566 cur = next;
567 } else if (is_continuation(cur, next)) {
568 join_paragraph(cur, next);
569 free_paragraph(next);
570 } else {
571 write_paragraph(cur);
572 free_paragraph(cur);
573 cur = next;
574 }
575 }
576 if (cur) {
577 write_paragraph(cur);
578 }
579
580 end:
581 free_paragraph(cur);
582 if (in_file) {
583 fclose(in_file);
584 }
585 return err;
586 }