(WRITTEN_BY): Rename from AUTHORS.
[platform/upstream/coreutils.git] / src / fold.c
1 /* fold -- wrap each input line to fit in specified width.
2    Copyright (C) 91, 1995-2003 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 2, or (at your option)
7    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, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by David MacKenzie, djm@gnu.ai.mit.edu. */
19
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <getopt.h>
24 #include <sys/types.h>
25
26 #include "system.h"
27 #include "error.h"
28 #include "posixver.h"
29 #include "xstrtol.h"
30
31 /* The official name of this program (e.g., no `g' prefix).  */
32 #define PROGRAM_NAME "fold"
33
34 #define WRITTEN_BY _("Written by David MacKenzie.")
35
36 /* The name this program was run with. */
37 char *program_name;
38
39 /* If nonzero, try to break on whitespace. */
40 static int break_spaces;
41
42 /* If nonzero, count bytes, not column positions. */
43 static int count_bytes;
44
45 /* If nonzero, at least one of the files we read was standard input. */
46 static int have_read_stdin;
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 != 0)
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       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
86     }
87   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
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 int
95 adjust_column (int 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 = column + 8 - column % 8;
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 0 if successful, 1 if an error occurs. */
119
120 static int
121 fold_file (char *filename, int width)
122 {
123   FILE *istream;
124   register int c;
125   int column = 0;               /* Screen column where next char will go. */
126   int offset_out = 0;   /* Index in `line_out' for next char. */
127   static char *line_out = NULL;
128   static int allocated_out = 0;
129
130   if (STREQ (filename, "-"))
131     {
132       istream = stdin;
133       have_read_stdin = 1;
134     }
135   else
136     istream = fopen (filename, "r");
137
138   if (istream == NULL)
139     {
140       error (0, errno, "%s", filename);
141       return 1;
142     }
143
144   while ((c = getc (istream)) != EOF)
145     {
146       if (offset_out + 1 >= allocated_out)
147         {
148           allocated_out += 1024;
149           line_out = xrealloc (line_out, allocated_out);
150         }
151
152       if (c == '\n')
153         {
154           line_out[offset_out++] = c;
155           fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
156           column = offset_out = 0;
157           continue;
158         }
159
160     rescan:
161       column = adjust_column (column, c);
162
163       if (column > width)
164         {
165           /* This character would make the line too long.
166              Print the line plus a newline, and make this character
167              start the next line. */
168           if (break_spaces)
169             {
170               /* Look for the last blank. */
171               int logical_end;
172
173               for (logical_end = offset_out - 1; logical_end >= 0;
174                    logical_end--)
175                 if (ISBLANK (line_out[logical_end]))
176                   break;
177               if (logical_end >= 0)
178                 {
179                   int i;
180
181                   /* Found a blank.  Don't output the part after it. */
182                   logical_end++;
183                   fwrite (line_out, sizeof (char), (size_t) logical_end,
184                           stdout);
185                   putchar ('\n');
186                   /* Move the remainder to the beginning of the next line.
187                      The areas being copied here might overlap. */
188                   memmove (line_out, line_out + logical_end,
189                            offset_out - logical_end);
190                   offset_out -= logical_end;
191                   for (column = i = 0; i < offset_out; i++)
192                     column = adjust_column (column, line_out[i]);
193                   goto rescan;
194                 }
195             }
196
197           if (offset_out == 0)
198             {
199               line_out[offset_out++] = c;
200               continue;
201             }
202
203           line_out[offset_out++] = '\n';
204           fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
205           column = offset_out = 0;
206           goto rescan;
207         }
208
209       line_out[offset_out++] = c;
210     }
211
212   if (offset_out)
213     fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
214
215   if (ferror (istream))
216     {
217       error (0, errno, "%s", filename);
218       if (!STREQ (filename, "-"))
219         fclose (istream);
220       return 1;
221     }
222   if (!STREQ (filename, "-") && fclose (istream) == EOF)
223     {
224       error (0, errno, "%s", filename);
225       return 1;
226     }
227
228   return 0;
229 }
230
231 int
232 main (int argc, char **argv)
233 {
234   int width = 80;
235   int i;
236   int optc;
237   int errs = 0;
238
239   initialize_main (&argc, &argv);
240   program_name = argv[0];
241   setlocale (LC_ALL, "");
242   bindtextdomain (PACKAGE, LOCALEDIR);
243   textdomain (PACKAGE);
244
245   atexit (close_stdout);
246
247   break_spaces = count_bytes = have_read_stdin = 0;
248
249   /* Turn any numeric options into -w options.  */
250   for (i = 1; i < argc; i++)
251     {
252       char const *a = argv[i];
253       if (a[0] == '-')
254         {
255           if (a[1] == '-' && ! a[2])
256             break;
257           if (ISDIGIT (a[1]))
258             {
259               char *s = xmalloc (strlen (a) + 2);
260               s[0] = '-';
261               s[1] = 'w';
262               strcpy (s + 2, a + 1);
263               argv[i] = s;
264               if (200112 <= posix2_version ())
265                 {
266                   error (0, 0, _("`%s' option is obsolete; use `%s'"), a, s);
267                   usage (EXIT_FAILURE);
268                 }
269             }
270         }
271     }
272
273   while ((optc = getopt_long (argc, argv, "bsw:", longopts, NULL)) != -1)
274     {
275       switch (optc)
276         {
277         case 0:
278           break;
279
280         case 'b':               /* Count bytes rather than columns. */
281           count_bytes = 1;
282           break;
283
284         case 's':               /* Break at word boundaries. */
285           break_spaces = 1;
286           break;
287
288         case 'w':               /* Line width. */
289           {
290             long int tmp_long;
291             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
292                 || tmp_long <= 0 || tmp_long > INT_MAX)
293               error (EXIT_FAILURE, 0,
294                      _("invalid number of columns: `%s'"), optarg);
295             width = (int) tmp_long;
296           }
297           break;
298
299         case_GETOPT_HELP_CHAR;
300
301         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, WRITTEN_BY);
302
303         default:
304           usage (EXIT_FAILURE);
305         }
306     }
307
308   if (argc == optind)
309     errs |= fold_file ("-", width);
310   else
311     for (i = optind; i < argc; i++)
312       errs |= fold_file (argv[i], width);
313
314   if (have_read_stdin && fclose (stdin) == EOF)
315     error (EXIT_FAILURE, errno, "-");
316
317   exit (errs == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
318 }