move help text from include/usage.src.h to coreutils/*.c
[oweals/busybox.git] / coreutils / fold.c
1 /* vi: set sw=4 ts=4: */
2 /* fold -- wrap each input line to fit in specified width.
3
4    Written by David MacKenzie, djm@gnu.ai.mit.edu.
5    Copyright (C) 91, 1995-2002 Free Software Foundation, Inc.
6
7    Modified for busybox based on coreutils v 5.0
8    Copyright (C) 2003 Glenn McGrath
9
10    Licensed under GPLv2 or later, see file LICENSE in this source tree.
11 */
12
13 //usage:#define fold_trivial_usage
14 //usage:       "[-bs] [-w WIDTH] [FILE]..."
15 //usage:#define fold_full_usage "\n\n"
16 //usage:       "Wrap input lines in each FILE (or stdin), writing to stdout\n"
17 //usage:     "\nOptions:"
18 //usage:     "\n        -b      Count bytes rather than columns"
19 //usage:     "\n        -s      Break at spaces"
20 //usage:     "\n        -w      Use WIDTH columns instead of 80"
21
22 #include "libbb.h"
23 #include "unicode.h"
24
25 /* This is a NOEXEC applet. Be very careful! */
26
27 /* Must match getopt32 call */
28 #define FLAG_COUNT_BYTES        1
29 #define FLAG_BREAK_SPACES       2
30 #define FLAG_WIDTH              4
31
32 /* Assuming the current column is COLUMN, return the column that
33    printing C will move the cursor to.
34    The first column is 0. */
35 static int adjust_column(unsigned column, char c)
36 {
37         if (option_mask32 & FLAG_COUNT_BYTES)
38                 return ++column;
39
40         if (c == '\t')
41                 return column + 8 - column % 8;
42
43         if (c == '\b') {
44                 if ((int)--column < 0)
45                         column = 0;
46         }
47         else if (c == '\r')
48                 column = 0;
49         else { /* just a printable char */
50                 if (unicode_status != UNICODE_ON /* every byte is a new char */
51                  || (c & 0xc0) != 0x80 /* it isn't a 2nd+ byte of a Unicode char */
52                 ) {
53                         column++;
54                 }
55         }
56         return column;
57 }
58
59 /* Note that this function can write NULs, unlike fputs etc. */
60 static void write2stdout(const void *buf, unsigned size)
61 {
62         fwrite(buf, 1, size, stdout);
63 }
64
65 int fold_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
66 int fold_main(int argc UNUSED_PARAM, char **argv)
67 {
68         char *line_out = NULL;
69         const char *w_opt = "80";
70         unsigned width;
71         smallint exitcode = EXIT_SUCCESS;
72
73         init_unicode();
74
75         if (ENABLE_INCLUDE_SUSv2) {
76                 /* Turn any numeric options into -w options.  */
77                 int i;
78                 for (i = 1; argv[i]; i++) {
79                         const char *a = argv[i];
80                         if (*a == '-') {
81                                 a++;
82                                 if (*a == '-' && !a[1]) /* "--" */
83                                         break;
84                                 if (isdigit(*a))
85                                         argv[i] = xasprintf("-w%s", a);
86                         }
87                 }
88         }
89
90         getopt32(argv, "bsw:", &w_opt);
91         width = xatou_range(w_opt, 1, 10000);
92
93         argv += optind;
94         if (!*argv)
95                 *--argv = (char*)"-";
96
97         do {
98                 FILE *istream = fopen_or_warn_stdin(*argv);
99                 int c;
100                 unsigned column = 0;     /* Screen column where next char will go */
101                 unsigned offset_out = 0; /* Index in 'line_out' for next char */
102
103                 if (istream == NULL) {
104                         exitcode = EXIT_FAILURE;
105                         continue;
106                 }
107
108                 while ((c = getc(istream)) != EOF) {
109                         /* We grow line_out in chunks of 0x1000 bytes */
110                         if ((offset_out & 0xfff) == 0) {
111                                 line_out = xrealloc(line_out, offset_out + 0x1000);
112                         }
113  rescan:
114                         line_out[offset_out] = c;
115                         if (c == '\n') {
116                                 write2stdout(line_out, offset_out + 1);
117                                 column = offset_out = 0;
118                                 continue;
119                         }
120                         column = adjust_column(column, c);
121                         if (column <= width || offset_out == 0) {
122                                 /* offset_out == 0 case happens
123                                  * with small width (say, 1) and tabs.
124                                  * The very first tab already goes to column 8,
125                                  * but we must not wrap it */
126                                 offset_out++;
127                                 continue;
128                         }
129
130                         /* This character would make the line too long.
131                          * Print the line plus a newline, and make this character
132                          * start the next line */
133                         if (option_mask32 & FLAG_BREAK_SPACES) {
134                                 unsigned i;
135                                 unsigned logical_end;
136
137                                 /* Look for the last blank. */
138                                 for (logical_end = offset_out - 1; (int)logical_end >= 0; logical_end--) {
139                                         if (!isblank(line_out[logical_end]))
140                                                 continue;
141
142                                         /* Found a space or tab.
143                                          * Output up to and including it, and start a new line */
144                                         logical_end++;
145                                         /*line_out[logical_end] = '\n'; - NO! this nukes one buffered character */
146                                         write2stdout(line_out, logical_end);
147                                         putchar('\n');
148                                         /* Move the remainder to the beginning of the next line.
149                                          * The areas being copied here might overlap. */
150                                         memmove(line_out, line_out + logical_end, offset_out - logical_end);
151                                         offset_out -= logical_end;
152                                         for (column = i = 0; i < offset_out; i++) {
153                                                 column = adjust_column(column, line_out[i]);
154                                         }
155                                         goto rescan;
156                                 }
157                                 /* No blank found, wrap will split the overlong word */
158                         }
159                         /* Output what we accumulated up to now, and start a new line */
160                         line_out[offset_out] = '\n';
161                         write2stdout(line_out, offset_out + 1);
162                         column = offset_out = 0;
163                         goto rescan;
164                 } /* while (not EOF) */
165
166                 if (offset_out) {
167                         write2stdout(line_out, offset_out);
168                 }
169
170                 if (fclose_if_not_stdin(istream)) {
171                         bb_simple_perror_msg(*argv);
172                         exitcode = EXIT_FAILURE;
173                 }
174         } while (*++argv);
175
176         fflush_stdout_and_exit(exitcode);
177 }