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