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