maint: adjust quoting: emit '...', not `...' in diagnostics
[coreutils/ericb.git] / src / fold.c
blob243156a26edb14aa5473c6f2b20d3cb95a1f5ba6
1 /* fold -- wrap each input line to fit in specified width.
2 Copyright (C) 1991, 1995-2006, 2008-2012 Free Software Foundation, Inc.
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 3 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by David MacKenzie, djm@gnu.ai.mit.edu. */
19 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
25 #include "system.h"
26 #include "error.h"
27 #include "fadvise.h"
28 #include "quote.h"
29 #include "xstrtol.h"
31 #define TAB_WIDTH 8
33 /* The official name of this program (e.g., no `g' prefix). */
34 #define PROGRAM_NAME "fold"
36 #define AUTHORS proper_name ("David MacKenzie")
38 /* If nonzero, try to break on whitespace. */
39 static bool break_spaces;
41 /* If nonzero, count bytes, not column positions. */
42 static bool count_bytes;
44 /* If nonzero, at least one of the files we read was standard input. */
45 static bool have_read_stdin;
47 static char const shortopts[] = "bsw:0::1::2::3::4::5::6::7::8::9::";
49 static struct option const longopts[] =
51 {"bytes", no_argument, NULL, 'b'},
52 {"spaces", no_argument, NULL, 's'},
53 {"width", required_argument, NULL, 'w'},
54 {GETOPT_HELP_OPTION_DECL},
55 {GETOPT_VERSION_OPTION_DECL},
56 {NULL, 0, NULL, 0}
59 void
60 usage (int status)
62 if (status != EXIT_SUCCESS)
63 emit_try_help ();
64 else
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 (HELP_OPTION_DESCRIPTION, stdout);
84 fputs (VERSION_OPTION_DESCRIPTION, stdout);
85 emit_ancillary_info ();
87 exit (status);
90 /* Assuming the current column is COLUMN, return the column that
91 printing C will move the cursor to.
92 The first column is 0. */
94 static size_t
95 adjust_column (size_t column, char c)
97 if (!count_bytes)
99 if (c == '\b')
101 if (column > 0)
102 column--;
104 else if (c == '\r')
105 column = 0;
106 else if (c == '\t')
107 column += TAB_WIDTH - column % TAB_WIDTH;
108 else /* if (isprint (c)) */
109 column++;
111 else
112 column++;
113 return column;
116 /* Fold file FILENAME, or standard input if FILENAME is "-",
117 to stdout, with maximum line length WIDTH.
118 Return true if successful. */
120 static bool
121 fold_file (char const *filename, size_t width)
123 FILE *istream;
124 int c;
125 size_t column = 0; /* Screen column where next char will go. */
126 size_t offset_out = 0; /* Index in `line_out' for next char. */
127 static char *line_out = NULL;
128 static size_t allocated_out = 0;
129 int saved_errno;
131 if (STREQ (filename, "-"))
133 istream = stdin;
134 have_read_stdin = true;
136 else
137 istream = fopen (filename, "r");
139 if (istream == NULL)
141 error (0, errno, "%s", filename);
142 return false;
145 fadvise (istream, FADVISE_SEQUENTIAL);
147 while ((c = getc (istream)) != EOF)
149 if (offset_out + 1 >= allocated_out)
150 line_out = X2REALLOC (line_out, &allocated_out);
152 if (c == '\n')
154 line_out[offset_out++] = c;
155 fwrite (line_out, sizeof (char), offset_out, stdout);
156 column = offset_out = 0;
157 continue;
160 rescan:
161 column = adjust_column (column, c);
163 if (column > width)
165 /* This character would make the line too long.
166 Print the line plus a newline, and make this character
167 start the next line. */
168 if (break_spaces)
170 bool found_blank = false;
171 size_t logical_end = offset_out;
173 /* Look for the last blank. */
174 while (logical_end)
176 --logical_end;
177 if (isblank (to_uchar (line_out[logical_end])))
179 found_blank = true;
180 break;
184 if (found_blank)
186 size_t i;
188 /* Found a blank. Don't output the part after it. */
189 logical_end++;
190 fwrite (line_out, sizeof (char), (size_t) logical_end,
191 stdout);
192 putchar ('\n');
193 /* Move the remainder to the beginning of the next line.
194 The areas being copied here might overlap. */
195 memmove (line_out, line_out + logical_end,
196 offset_out - logical_end);
197 offset_out -= logical_end;
198 for (column = i = 0; i < offset_out; i++)
199 column = adjust_column (column, line_out[i]);
200 goto rescan;
204 if (offset_out == 0)
206 line_out[offset_out++] = c;
207 continue;
210 line_out[offset_out++] = '\n';
211 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
212 column = offset_out = 0;
213 goto rescan;
216 line_out[offset_out++] = c;
219 saved_errno = errno;
221 if (offset_out)
222 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
224 if (ferror (istream))
226 error (0, saved_errno, "%s", filename);
227 if (!STREQ (filename, "-"))
228 fclose (istream);
229 return false;
231 if (!STREQ (filename, "-") && fclose (istream) == EOF)
233 error (0, errno, "%s", filename);
234 return false;
237 return true;
241 main (int argc, char **argv)
243 size_t width = 80;
244 int i;
245 int optc;
246 bool ok;
248 initialize_main (&argc, &argv);
249 set_program_name (argv[0]);
250 setlocale (LC_ALL, "");
251 bindtextdomain (PACKAGE, LOCALEDIR);
252 textdomain (PACKAGE);
254 atexit (close_stdout);
256 break_spaces = count_bytes = have_read_stdin = false;
258 while ((optc = getopt_long (argc, argv, shortopts, longopts, NULL)) != -1)
260 char optargbuf[2];
262 switch (optc)
264 case 'b': /* Count bytes rather than columns. */
265 count_bytes = true;
266 break;
268 case 's': /* Break at word boundaries. */
269 break_spaces = true;
270 break;
272 case '0': case '1': case '2': case '3': case '4':
273 case '5': case '6': case '7': case '8': case '9':
274 if (optarg)
275 optarg--;
276 else
278 optargbuf[0] = optc;
279 optargbuf[1] = '\0';
280 optarg = optargbuf;
282 /* Fall through. */
283 case 'w': /* Line width. */
285 unsigned long int tmp_ulong;
286 if (! (xstrtoul (optarg, NULL, 10, &tmp_ulong, "") == LONGINT_OK
287 && 0 < tmp_ulong && tmp_ulong < SIZE_MAX - TAB_WIDTH))
288 error (EXIT_FAILURE, 0,
289 _("invalid number of columns: %s"), quote (optarg));
290 width = tmp_ulong;
292 break;
294 case_GETOPT_HELP_CHAR;
296 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
298 default:
299 usage (EXIT_FAILURE);
303 if (argc == optind)
304 ok = fold_file ("-", width);
305 else
307 ok = true;
308 for (i = optind; i < argc; i++)
309 ok &= fold_file (argv[i], width);
312 if (have_read_stdin && fclose (stdin) == EOF)
313 error (EXIT_FAILURE, errno, "-");
315 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);