97afc55405764a3854d8b422f65d4a4eba0c6345
[platform/upstream/coreutils.git] / src / fold.c
1 /* fold -- wrap each input line to fit in specified width.
2    Copyright (C) 91, 1995-2000 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 "closeout.h"
28 #include "error.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 AUTHORS "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       printf (_("\
71 Wrap input lines in each FILE (standard input by default), writing to\n\
72 standard output.\n\
73 \n\
74   -b, --bytes         count bytes rather than columns\n\
75   -s, --spaces        break at spaces\n\
76   -w, --width=WIDTH   use WIDTH columns instead of 80\n\
77       --help          display this help and exit\n\
78       --version       output version information and exit\n\
79 "));
80       puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
81     }
82   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
83 }
84
85 /* Assuming the current column is COLUMN, return the column that
86    printing C will move the cursor to.
87    The first column is 0. */
88
89 static int
90 adjust_column (int column, char c)
91 {
92   if (!count_bytes)
93     {
94       if (c == '\b')
95         {
96           if (column > 0)
97             column--;
98         }
99       else if (c == '\r')
100         column = 0;
101       else if (c == '\t')
102         column = column + 8 - column % 8;
103       else /* if (isprint (c)) */
104         column++;
105     }
106   else
107     column++;
108   return column;
109 }
110
111 /* Fold file FILENAME, or standard input if FILENAME is "-",
112    to stdout, with maximum line length WIDTH.
113    Return 0 if successful, 1 if an error occurs. */
114
115 static int
116 fold_file (char *filename, int width)
117 {
118   FILE *istream;
119   register int c;
120   int column = 0;               /* Screen column where next char will go. */
121   int offset_out = 0;   /* Index in `line_out' for next char. */
122   static char *line_out = NULL;
123   static int allocated_out = 0;
124
125   if (STREQ (filename, "-"))
126     {
127       istream = stdin;
128       have_read_stdin = 1;
129     }
130   else
131     istream = fopen (filename, "r");
132
133   if (istream == NULL)
134     {
135       error (0, errno, "%s", filename);
136       return 1;
137     }
138
139   while ((c = getc (istream)) != EOF)
140     {
141       if (offset_out + 1 >= allocated_out)
142         {
143           allocated_out += 1024;
144           line_out = xrealloc (line_out, allocated_out);
145         }
146
147       if (c == '\n')
148         {
149           line_out[offset_out++] = c;
150           fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
151           column = offset_out = 0;
152           continue;
153         }
154
155     rescan:
156       column = adjust_column (column, c);
157
158       if (column > width)
159         {
160           /* This character would make the line too long.
161              Print the line plus a newline, and make this character
162              start the next line. */
163           if (break_spaces)
164             {
165               /* Look for the last blank. */
166               int logical_end;
167
168               for (logical_end = offset_out - 1; logical_end >= 0;
169                    logical_end--)
170                 if (ISBLANK (line_out[logical_end]))
171                   break;
172               if (logical_end >= 0)
173                 {
174                   int i;
175
176                   /* Found a blank.  Don't output the part after it. */
177                   logical_end++;
178                   fwrite (line_out, sizeof (char), (size_t) logical_end,
179                           stdout);
180                   putchar ('\n');
181                   /* Move the remainder to the beginning of the next line.
182                      The areas being copied here might overlap. */
183                   memmove (line_out, line_out + logical_end,
184                            offset_out - logical_end);
185                   offset_out -= logical_end;
186                   for (column = i = 0; i < offset_out; i++)
187                     column = adjust_column (column, line_out[i]);
188                   goto rescan;
189                 }
190             }
191           else
192             {
193               if (offset_out == 0)
194                 {
195                   line_out[offset_out++] = c;
196                   continue;
197                 }
198             }
199           line_out[offset_out++] = '\n';
200           fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
201           column = offset_out = 0;
202           goto rescan;
203         }
204
205       line_out[offset_out++] = c;
206     }
207
208   if (offset_out)
209     fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
210
211   if (ferror (istream))
212     {
213       error (0, errno, "%s", filename);
214       if (!STREQ (filename, "-"))
215         fclose (istream);
216       return 1;
217     }
218   if (!STREQ (filename, "-") && fclose (istream) == EOF)
219     {
220       error (0, errno, "%s", filename);
221       return 1;
222     }
223
224   return 0;
225 }
226
227 int
228 main (int argc, char **argv)
229 {
230   int width = 80;
231   int i;
232   int optc;
233   int errs = 0;
234
235   program_name = argv[0];
236   setlocale (LC_ALL, "");
237   bindtextdomain (PACKAGE, LOCALEDIR);
238   textdomain (PACKAGE);
239
240   atexit (close_stdout);
241
242   break_spaces = count_bytes = have_read_stdin = 0;
243
244   /* Turn any numeric options into -w options.  */
245   for (i = 1; i < argc; i++)
246     {
247       if (argv[i][0] == '-' && ISDIGIT (argv[i][1]))
248         {
249           char *s;
250
251           s = xmalloc (strlen (argv[i]) + 2);
252           s[0] = '-';
253           s[1] = 'w';
254           strcpy (s + 2, argv[i] + 1);
255           argv[i] = s;
256         }
257     }
258
259   while ((optc = getopt_long (argc, argv, "bsw:", longopts, NULL)) != -1)
260     {
261       switch (optc)
262         {
263         case 0:
264           break;
265
266         case 'b':               /* Count bytes rather than columns. */
267           count_bytes = 1;
268           break;
269
270         case 's':               /* Break at word boundaries. */
271           break_spaces = 1;
272           break;
273
274         case 'w':               /* Line width. */
275           {
276             long int tmp_long;
277             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
278                 || tmp_long <= 0 || tmp_long > INT_MAX)
279               error (EXIT_FAILURE, 0,
280                      _("invalid number of columns: `%s'"), optarg);
281             width = (int) tmp_long;
282           }
283           break;
284
285         case_GETOPT_HELP_CHAR;
286
287         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
288
289         default:
290           usage (1);
291         }
292     }
293
294   if (argc == optind)
295     errs |= fold_file ("-", width);
296   else
297     for (i = optind; i < argc; i++)
298       errs |= fold_file (argv[i], width);
299
300   if (have_read_stdin && fclose (stdin) == EOF)
301     error (EXIT_FAILURE, errno, "-");
302
303   exit (errs == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
304 }