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