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