TODO: add an item for a chmod optimization
[platform/upstream/coreutils.git] / src / fold.c
1 /* fold -- wrap each input line to fit in specified width.
2    Copyright (C) 91, 1995-2006, 2008 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by David MacKenzie, djm@gnu.ai.mit.edu. */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
24
25 #include "system.h"
26 #include "error.h"
27 #include "quote.h"
28 #include "xstrtol.h"
29
30 #define TAB_WIDTH 8
31
32 /* The official name of this program (e.g., no `g' prefix).  */
33 #define PROGRAM_NAME "fold"
34
35 #define AUTHORS proper_name ("David MacKenzie")
36
37 /* If nonzero, try to break on whitespace. */
38 static bool break_spaces;
39
40 /* If nonzero, count bytes, not column positions. */
41 static bool count_bytes;
42
43 /* If nonzero, at least one of the files we read was standard input. */
44 static bool have_read_stdin;
45
46 static char const shortopts[] = "bsw:0::1::2::3::4::5::6::7::8::9::";
47
48 static struct option const longopts[] =
49 {
50   {"bytes", no_argument, NULL, 'b'},
51   {"spaces", no_argument, NULL, 's'},
52   {"width", required_argument, NULL, 'w'},
53   {GETOPT_HELP_OPTION_DECL},
54   {GETOPT_VERSION_OPTION_DECL},
55   {NULL, 0, NULL, 0}
56 };
57
58 void
59 usage (int status)
60 {
61   if (status != EXIT_SUCCESS)
62     fprintf (stderr, _("Try `%s --help' for more information.\n"),
63              program_name);
64   else
65     {
66       printf (_("\
67 Usage: %s [OPTION]... [FILE]...\n\
68 "),
69               program_name);
70       fputs (_("\
71 Wrap input lines in each FILE (standard input by default), writing to\n\
72 standard output.\n\
73 \n\
74 "), stdout);
75       fputs (_("\
76 Mandatory arguments to long options are mandatory for short options too.\n\
77 "), stdout);
78       fputs (_("\
79   -b, --bytes         count bytes rather than columns\n\
80   -s, --spaces        break at spaces\n\
81   -w, --width=WIDTH   use WIDTH columns instead of 80\n\
82 "), stdout);
83       fputs (HELP_OPTION_DESCRIPTION, stdout);
84       fputs (VERSION_OPTION_DESCRIPTION, stdout);
85       emit_bug_reporting_address ();
86     }
87   exit (status);
88 }
89
90 /* Assuming the current column is COLUMN, return the column that
91    printing C will move the cursor to.
92    The first column is 0. */
93
94 static size_t
95 adjust_column (size_t column, char c)
96 {
97   if (!count_bytes)
98     {
99       if (c == '\b')
100         {
101           if (column > 0)
102             column--;
103         }
104       else if (c == '\r')
105         column = 0;
106       else if (c == '\t')
107         column += TAB_WIDTH - column % TAB_WIDTH;
108       else /* if (isprint (c)) */
109         column++;
110     }
111   else
112     column++;
113   return column;
114 }
115
116 /* Fold file FILENAME, or standard input if FILENAME is "-",
117    to stdout, with maximum line length WIDTH.
118    Return true if successful.  */
119
120 static bool
121 fold_file (char const *filename, size_t width)
122 {
123   FILE *istream;
124   int c;
125   size_t column = 0;            /* Screen column where next char will go. */
126   size_t offset_out = 0;        /* Index in `line_out' for next char. */
127   static char *line_out = NULL;
128   static size_t allocated_out = 0;
129   int saved_errno;
130
131   if (STREQ (filename, "-"))
132     {
133       istream = stdin;
134       have_read_stdin = true;
135     }
136   else
137     istream = fopen (filename, "r");
138
139   if (istream == NULL)
140     {
141       error (0, errno, "%s", filename);
142       return false;
143     }
144
145   while ((c = getc (istream)) != EOF)
146     {
147       if (offset_out + 1 >= allocated_out)
148         line_out = X2REALLOC (line_out, &allocated_out);
149
150       if (c == '\n')
151         {
152           line_out[offset_out++] = c;
153           fwrite (line_out, sizeof (char), offset_out, stdout);
154           column = offset_out = 0;
155           continue;
156         }
157
158     rescan:
159       column = adjust_column (column, c);
160
161       if (column > width)
162         {
163           /* This character would make the line too long.
164              Print the line plus a newline, and make this character
165              start the next line. */
166           if (break_spaces)
167             {
168               bool found_blank = false;
169               size_t logical_end = offset_out;
170
171               /* Look for the last blank. */
172               while (logical_end)
173                 {
174                   --logical_end;
175                   if (isblank (to_uchar (line_out[logical_end])))
176                     {
177                       found_blank = true;
178                       break;
179                     }
180                 }
181
182               if (found_blank)
183                 {
184                   size_t i;
185
186                   /* Found a blank.  Don't output the part after it. */
187                   logical_end++;
188                   fwrite (line_out, sizeof (char), (size_t) logical_end,
189                           stdout);
190                   putchar ('\n');
191                   /* Move the remainder to the beginning of the next line.
192                      The areas being copied here might overlap. */
193                   memmove (line_out, line_out + logical_end,
194                            offset_out - logical_end);
195                   offset_out -= logical_end;
196                   for (column = i = 0; i < offset_out; i++)
197                     column = adjust_column (column, line_out[i]);
198                   goto rescan;
199                 }
200             }
201
202           if (offset_out == 0)
203             {
204               line_out[offset_out++] = c;
205               continue;
206             }
207
208           line_out[offset_out++] = '\n';
209           fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
210           column = offset_out = 0;
211           goto rescan;
212         }
213
214       line_out[offset_out++] = c;
215     }
216
217   saved_errno = errno;
218
219   if (offset_out)
220     fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
221
222   if (ferror (istream))
223     {
224       error (0, saved_errno, "%s", filename);
225       if (!STREQ (filename, "-"))
226         fclose (istream);
227       return false;
228     }
229   if (!STREQ (filename, "-") && fclose (istream) == EOF)
230     {
231       error (0, errno, "%s", filename);
232       return false;
233     }
234
235   return true;
236 }
237
238 int
239 main (int argc, char **argv)
240 {
241   size_t width = 80;
242   int i;
243   int optc;
244   bool ok;
245
246   initialize_main (&argc, &argv);
247   set_program_name (argv[0]);
248   setlocale (LC_ALL, "");
249   bindtextdomain (PACKAGE, LOCALEDIR);
250   textdomain (PACKAGE);
251
252   atexit (close_stdout);
253
254   break_spaces = count_bytes = have_read_stdin = false;
255
256   while ((optc = getopt_long (argc, argv, shortopts, longopts, NULL)) != -1)
257     {
258       char optargbuf[2];
259
260       switch (optc)
261         {
262         case 'b':               /* Count bytes rather than columns. */
263           count_bytes = true;
264           break;
265
266         case 's':               /* Break at word boundaries. */
267           break_spaces = true;
268           break;
269
270         case '0': case '1': case '2': case '3': case '4':
271         case '5': case '6': case '7': case '8': case '9':
272           if (optarg)
273             optarg--;
274           else
275             {
276               optargbuf[0] = optc;
277               optargbuf[1] = '\0';
278               optarg = optargbuf;
279             }
280           /* Fall through.  */
281         case 'w':               /* Line width. */
282           {
283             unsigned long int tmp_ulong;
284             if (! (xstrtoul (optarg, NULL, 10, &tmp_ulong, "") == LONGINT_OK
285                    && 0 < tmp_ulong && tmp_ulong < SIZE_MAX - TAB_WIDTH))
286               error (EXIT_FAILURE, 0,
287                      _("invalid number of columns: %s"), quote (optarg));
288             width = tmp_ulong;
289           }
290           break;
291
292         case_GETOPT_HELP_CHAR;
293
294         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
295
296         default:
297           usage (EXIT_FAILURE);
298         }
299     }
300
301   if (argc == optind)
302     ok = fold_file ("-", width);
303   else
304     {
305       ok = true;
306       for (i = optind; i < argc; i++)
307         ok &= fold_file (argv[i], width);
308     }
309
310   if (have_read_stdin && fclose (stdin) == EOF)
311     error (EXIT_FAILURE, errno, "-");
312
313   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
314 }