517be282a2e5974bb12ff3276e7d3a85d393cf90
[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   int saved_errno;
130
131   if (STREQ (filename, "-"))
132     {
133       istream = stdin;
134       have_read_stdin = 1;
135     }
136   else
137     istream = fopen (filename, "r");
138
139   if (istream == NULL)
140     {
141       error (0, errno, "%s", filename);
142       return 1;
143     }
144
145   while ((c = getc (istream)) != EOF)
146     {
147       if (offset_out + 1 >= allocated_out)
148         {
149           allocated_out += 1024;
150           line_out = xrealloc (line_out, allocated_out);
151         }
152
153       if (c == '\n')
154         {
155           line_out[offset_out++] = c;
156           fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
157           column = offset_out = 0;
158           continue;
159         }
160
161     rescan:
162       column = adjust_column (column, c);
163
164       if (column > width)
165         {
166           /* This character would make the line too long.
167              Print the line plus a newline, and make this character
168              start the next line. */
169           if (break_spaces)
170             {
171               /* Look for the last blank. */
172               int logical_end;
173
174               for (logical_end = offset_out - 1; logical_end >= 0;
175                    logical_end--)
176                 if (ISBLANK (line_out[logical_end]))
177                   break;
178               if (logical_end >= 0)
179                 {
180                   int i;
181
182                   /* Found a blank.  Don't output the part after it. */
183                   logical_end++;
184                   fwrite (line_out, sizeof (char), (size_t) logical_end,
185                           stdout);
186                   putchar ('\n');
187                   /* Move the remainder to the beginning of the next line.
188                      The areas being copied here might overlap. */
189                   memmove (line_out, line_out + logical_end,
190                            offset_out - logical_end);
191                   offset_out -= logical_end;
192                   for (column = i = 0; i < offset_out; i++)
193                     column = adjust_column (column, line_out[i]);
194                   goto rescan;
195                 }
196             }
197
198           if (offset_out == 0)
199             {
200               line_out[offset_out++] = c;
201               continue;
202             }
203
204           line_out[offset_out++] = '\n';
205           fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
206           column = offset_out = 0;
207           goto rescan;
208         }
209
210       line_out[offset_out++] = c;
211     }
212
213   saved_errno = errno;
214
215   if (offset_out)
216     fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
217
218   if (ferror (istream))
219     {
220       error (0, saved_errno, "%s", filename);
221       if (!STREQ (filename, "-"))
222         fclose (istream);
223       return 1;
224     }
225   if (!STREQ (filename, "-") && fclose (istream) == EOF)
226     {
227       error (0, errno, "%s", filename);
228       return 1;
229     }
230
231   return 0;
232 }
233
234 int
235 main (int argc, char **argv)
236 {
237   int width = 80;
238   int i;
239   int optc;
240   int errs = 0;
241
242   initialize_main (&argc, &argv);
243   program_name = argv[0];
244   setlocale (LC_ALL, "");
245   bindtextdomain (PACKAGE, LOCALEDIR);
246   textdomain (PACKAGE);
247
248   atexit (close_stdout);
249
250   break_spaces = count_bytes = have_read_stdin = 0;
251
252   /* Turn any numeric options into -w options.  */
253   for (i = 1; i < argc; i++)
254     {
255       char const *a = argv[i];
256       if (a[0] == '-')
257         {
258           if (a[1] == '-' && ! a[2])
259             break;
260           if (ISDIGIT (a[1]))
261             {
262               char *s = xmalloc (strlen (a) + 2);
263               s[0] = '-';
264               s[1] = 'w';
265               strcpy (s + 2, a + 1);
266               argv[i] = s;
267               if (200112 <= posix2_version ())
268                 {
269                   error (0, 0, _("`%s' option is obsolete; use `%s'"), a, s);
270                   usage (EXIT_FAILURE);
271                 }
272             }
273         }
274     }
275
276   while ((optc = getopt_long (argc, argv, "bsw:", longopts, NULL)) != -1)
277     {
278       switch (optc)
279         {
280         case 0:
281           break;
282
283         case 'b':               /* Count bytes rather than columns. */
284           count_bytes = 1;
285           break;
286
287         case 's':               /* Break at word boundaries. */
288           break_spaces = 1;
289           break;
290
291         case 'w':               /* Line width. */
292           {
293             long int tmp_long;
294             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
295                 || tmp_long <= 0 || tmp_long > INT_MAX)
296               error (EXIT_FAILURE, 0,
297                      _("invalid number of columns: `%s'"), optarg);
298             width = (int) tmp_long;
299           }
300           break;
301
302         case_GETOPT_HELP_CHAR;
303
304         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, WRITTEN_BY);
305
306         default:
307           usage (EXIT_FAILURE);
308         }
309     }
310
311   if (argc == optind)
312     errs |= fold_file ("-", width);
313   else
314     for (i = optind; i < argc; i++)
315       errs |= fold_file (argv[i], width);
316
317   if (have_read_stdin && fclose (stdin) == EOF)
318     error (EXIT_FAILURE, errno, "-");
319
320   exit (errs == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
321 }