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