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