(usage): Clarify meaning of --spaces.
[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., 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 /* 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 /* If nonzero, try to break on whitespace. */
39 static int break_spaces;
40
41 /* If nonzero, count bytes, not column positions. */
42 static int count_bytes;
43
44 /* If nonzero, at least one of the files we read was standard input. */
45 static int have_read_stdin;
46
47 /* If non-zero, display usage information and exit.  */
48 static int show_help;
49
50 /* If non-zero, print the version on standard output then exit.  */
51 static int show_version;
52
53 static struct option const longopts[] =
54 {
55   {"bytes", no_argument, NULL, 'b'},
56   {"spaces", no_argument, NULL, 's'},
57   {"width", required_argument, NULL, 'w'},
58   {"help", no_argument, &show_help, 1},
59   {"version", no_argument, &show_version, 1},
60   {NULL, 0, NULL, 0}
61 };
62
63 static void
64 usage (int status)
65 {
66   if (status != 0)
67     fprintf (stderr, _("Try `%s --help' for more information.\n"),
68              program_name);
69   else
70     {
71       printf (_("\
72 Usage: %s [OPTION]... [FILE]...\n\
73 "),
74               program_name);
75       printf (_("\
76 Wrap input lines in each FILE (standard input by default), writing to\n\
77 standard output.\n\
78 \n\
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 "));
83     }
84   exit (status);
85 }
86
87 /* Assuming the current column is COLUMN, return the column that
88    printing C will move the cursor to.
89    The first column is 0. */
90
91 static int
92 adjust_column (int column, char c)
93 {
94   if (!count_bytes)
95     {
96       if (c == '\b')
97         {
98           if (column > 0)
99             column--;
100         }
101       else if (c == '\r')
102         column = 0;
103       else if (c == '\t')
104         column = column + 8 - column % 8;
105       else /* if (isprint (c)) */
106         column++;
107     }
108   else
109     column++;
110   return column;
111 }
112
113 /* Fold file FILENAME, or standard input if FILENAME is "-",
114    to stdout, with maximum line length WIDTH.
115    Return 0 if successful, 1 if an error occurs. */
116
117 static int
118 fold_file (char *filename, int width)
119 {
120   FILE *istream;
121   register int c;
122   int column = 0;               /* Screen column where next char will go. */
123   size_t offset_out = 0;        /* Index in `line_out' for next char. */
124   static char *line_out = NULL;
125   static size_t allocated_out = 0;
126
127   if (!strcmp (filename, "-"))
128     {
129       istream = stdin;
130       have_read_stdin = 1;
131     }
132   else
133     istream = fopen (filename, "r");
134
135   if (istream == NULL)
136     {
137       error (0, errno, "%s", filename);
138       return 1;
139     }
140
141   while ((c = getc (istream)) != EOF)
142     {
143       if (offset_out + 1 >= allocated_out)
144         {
145           allocated_out += 1024;
146           line_out = xrealloc (line_out, allocated_out);
147         }
148
149       if (c == '\n')
150         {
151           line_out[offset_out++] = c;
152           fwrite (line_out, sizeof (char), offset_out, stdout);
153           column = offset_out = 0;
154           continue;
155         }
156
157     rescan:
158       column = adjust_column (column, c);
159
160       if (column > width)
161         {
162           /* This character would make the line too long.
163              Print the line plus a newline, and make this character
164              start the next line. */
165           if (break_spaces)
166             {
167               /* Look for the last blank. */
168               int logical_end;
169
170               for (logical_end = offset_out - 1; logical_end >= 0;
171                    logical_end--)
172                 if (ISBLANK (line_out[logical_end]))
173                   break;
174               if (logical_end >= 0)
175                 {
176                   int i;
177
178                   /* Found a blank.  Don't output the part after it. */
179                   logical_end++;
180                   fwrite (line_out, sizeof (char), logical_end, 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), 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), offset_out, stdout);
211
212   if (ferror (istream))
213     {
214       error (0, errno, "%s", filename);
215       if (strcmp (filename, "-"))
216         fclose (istream);
217       return 1;
218     }
219   if (strcmp (filename, "-") && fclose (istream) == EOF)
220     {
221       error (0, errno, "%s", filename);
222       return 1;
223     }
224
225   if (ferror (stdout))
226     {
227       error (0, errno, _("write error"));
228       return 1;
229     }
230
231   return 0;
232 }
233
234 void
235 main (int argc, char **argv)
236 {
237   int width = 80;
238   int i;
239   int optc;
240   int errs = 0;
241
242   program_name = argv[0];
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, (int *) 0))
261          != EOF)
262     {
263       switch (optc)
264         {
265         case 0:
266           break;
267
268         case 'b':               /* Count bytes rather than columns. */
269           count_bytes = 1;
270           break;
271
272         case 's':               /* Break at word boundaries. */
273           break_spaces = 1;
274           break;
275
276         case 'w':               /* Line width. */
277           width = atoi (optarg);
278           if (width < 1)
279             error (1, 0, _("%s: invalid line width"), optarg);
280           break;
281
282         default:
283           usage (1);
284         }
285     }
286
287   if (show_version)
288     {
289       printf ("fold - %s\n", version_string);
290       exit (0);
291     }
292
293   if (show_help)
294     usage (0);
295
296   if (argc == optind)
297     errs |= fold_file ("-", width);
298   else
299     for (i = optind; i < argc; i++)
300       errs |= fold_file (argv[i], width);
301
302   if (have_read_stdin && fclose (stdin) == EOF)
303     error (1, errno, "-");
304   if (fclose (stdout) == EOF)
305     error (1, errno, _("write error"));
306
307   exit (errs);
308 }