mhl and mhbuild ignore to long lines
[mmh] / sbr / fold.c
1 /* fold.c -- fold a mail header field
2  *
3  * This code is Copyright (c), by the authors of nmh.  See the
4  * COPYRIGHT file in the root directory of the nmh distribution for
5  * complete copyright information. */
6
7 #include <h/mh.h>
8 #include <stdio.h>
9
10 void
11 fold(charstring_t dst, size_t namelen, const char *restrict body)
12 {
13         const char *restrict body_next;
14         const char *restrict wsp;
15         const char *restrict wsp_next;
16         const int crlf = strchr(body, '\r') != NULL;
17         charstring_clear(dst);
18         namelen++;
19
20         while (*body) {
21                 body_next = strchr(body, '\n');
22                 if ((unsigned long) (body_next - body) <= MAXTEXTPERLN - namelen) {
23                         charstring_push_back_chars(dst, body, body_next - body + 1);
24                         namelen = 0;
25                         body = body_next + 1;
26                         continue;
27                 }
28                 wsp = body;
29                 while (namelen == 0 && (*wsp == ' ' || *wsp == '\t')) {
30                         wsp++;
31                 }
32                 wsp = wsp_next = strpbrk(wsp, " \t");
33
34                 /* if now whitespace is in the current line just print the curret line as is */
35                 if (!wsp_next || wsp_next > body_next) {
36                         charstring_push_back_chars(dst, body, body_next - body + 1);
37                         namelen = 0;
38                         body = body_next + 1;
39                         continue;
40                 }
41
42                 while ((unsigned long)(wsp_next - body) <= MAXTEXTPERLN - namelen) {
43                         wsp = wsp_next;
44                         wsp_next = strpbrk(wsp+1, " \t");
45                         if (!wsp_next) {
46                                 break;
47                         }
48                         if (wsp_next > body_next) {
49                                 break;
50                         }
51                 }
52
53                 charstring_push_back_chars(dst, body, wsp - body);
54                 if (crlf) {
55                         charstring_push_back(dst, '\r');
56                 }
57                 charstring_push_back(dst, '\n');
58                 namelen = 0;
59                 body = wsp;
60         }
61 }