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