maint: pacify ‘make syntax-check’
[coreutils.git] / src / fold.c
blob1a38590976dbf013505d955ead252444308eead1
1 /* fold -- wrap each input line to fit in specified width.
2 Copyright (C) 1991-2023 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 <https://www.gnu.org/licenses/>. */
17 /* Written by David MacKenzie, djm@gnu.ai.mit.edu. */
19 #include <config.h>
21 #include <ctype.h>
22 #include <stdio.h>
23 #include <getopt.h>
24 #include <sys/types.h>
26 #include "system.h"
27 #include "fadvise.h"
28 #include "xdectoint.h"
30 #define TAB_WIDTH 8
32 /* The official name of this program (e.g., no 'g' prefix). */
33 #define PROGRAM_NAME "fold"
35 #define AUTHORS proper_name ("David MacKenzie")
37 /* If nonzero, try to break on whitespace. */
38 static bool break_spaces;
40 /* If nonzero, count bytes, not column positions. */
41 static bool count_bytes;
43 /* If nonzero, at least one of the files we read was standard input. */
44 static bool have_read_stdin;
46 static char const shortopts[] = "bsw:0::1::2::3::4::5::6::7::8::9::";
48 static struct option const longopts[] =
50 {"bytes", no_argument, nullptr, 'b'},
51 {"spaces", no_argument, nullptr, 's'},
52 {"width", required_argument, nullptr, 'w'},
53 {GETOPT_HELP_OPTION_DECL},
54 {GETOPT_VERSION_OPTION_DECL},
55 {nullptr, 0, nullptr, 0}
58 void
59 usage (int status)
61 if (status != EXIT_SUCCESS)
62 emit_try_help ();
63 else
65 printf (_("\
66 Usage: %s [OPTION]... [FILE]...\n\
67 "),
68 program_name);
69 fputs (_("\
70 Wrap input lines in each FILE, writing to standard output.\n\
71 "), stdout);
73 emit_stdin_note ();
74 emit_mandatory_arg_note ();
76 fputs (_("\
77 -b, --bytes count bytes rather than columns\n\
78 -s, --spaces break at spaces\n\
79 -w, --width=WIDTH use WIDTH columns instead of 80\n\
80 "), stdout);
81 fputs (HELP_OPTION_DESCRIPTION, stdout);
82 fputs (VERSION_OPTION_DESCRIPTION, stdout);
83 emit_ancillary_info (PROGRAM_NAME);
85 exit (status);
88 /* Assuming the current column is COLUMN, return the column that
89 printing C will move the cursor to.
90 The first column is 0. */
92 static size_t
93 adjust_column (size_t column, char c)
95 if (!count_bytes)
97 if (c == '\b')
99 if (column > 0)
100 column--;
102 else if (c == '\r')
103 column = 0;
104 else if (c == '\t')
105 column += TAB_WIDTH - column % TAB_WIDTH;
106 else /* if (isprint (c)) */
107 column++;
109 else
110 column++;
111 return column;
114 /* Fold file FILENAME, or standard input if FILENAME is "-",
115 to stdout, with maximum line length WIDTH.
116 Return true if successful. */
118 static bool
119 fold_file (char const *filename, size_t width)
121 FILE *istream;
122 int c;
123 size_t column = 0; /* Screen column where next char will go. */
124 size_t offset_out = 0; /* Index in 'line_out' for next char. */
125 static char *line_out = nullptr;
126 static size_t allocated_out = 0;
127 int saved_errno;
129 if (STREQ (filename, "-"))
131 istream = stdin;
132 have_read_stdin = true;
134 else
135 istream = fopen (filename, "r");
137 if (istream == nullptr)
139 error (0, errno, "%s", quotef (filename));
140 return false;
143 fadvise (istream, FADVISE_SEQUENTIAL);
145 while ((c = getc (istream)) != EOF)
147 if (offset_out + 1 >= allocated_out)
148 line_out = X2REALLOC (line_out, &allocated_out);
150 if (c == '\n')
152 line_out[offset_out++] = c;
153 fwrite (line_out, sizeof (char), offset_out, stdout);
154 column = offset_out = 0;
155 continue;
158 rescan:
159 column = adjust_column (column, c);
161 if (column > width)
163 /* This character would make the line too long.
164 Print the line plus a newline, and make this character
165 start the next line. */
166 if (break_spaces)
168 bool found_blank = false;
169 size_t logical_end = offset_out;
171 /* Look for the last blank. */
172 while (logical_end)
174 --logical_end;
175 if (isblank (to_uchar (line_out[logical_end])))
177 found_blank = true;
178 break;
182 if (found_blank)
184 size_t i;
186 /* Found a blank. Don't output the part after it. */
187 logical_end++;
188 fwrite (line_out, sizeof (char), (size_t) logical_end,
189 stdout);
190 putchar ('\n');
191 /* Move the remainder to the beginning of the next line.
192 The areas being copied here might overlap. */
193 memmove (line_out, line_out + logical_end,
194 offset_out - logical_end);
195 offset_out -= logical_end;
196 for (column = i = 0; i < offset_out; i++)
197 column = adjust_column (column, line_out[i]);
198 goto rescan;
202 if (offset_out == 0)
204 line_out[offset_out++] = c;
205 continue;
208 line_out[offset_out++] = '\n';
209 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
210 column = offset_out = 0;
211 goto rescan;
214 line_out[offset_out++] = c;
217 saved_errno = errno;
218 if (!ferror (istream))
219 saved_errno = 0;
221 if (offset_out)
222 fwrite (line_out, sizeof (char), (size_t) offset_out, stdout);
224 if (STREQ (filename, "-"))
225 clearerr (istream);
226 else if (fclose (istream) != 0 && !saved_errno)
227 saved_errno = errno;
229 if (saved_errno)
231 error (0, saved_errno, "%s", quotef (filename));
232 return false;
235 return true;
239 main (int argc, char **argv)
241 size_t width = 80;
242 int i;
243 int optc;
244 bool ok;
246 initialize_main (&argc, &argv);
247 set_program_name (argv[0]);
248 setlocale (LC_ALL, "");
249 bindtextdomain (PACKAGE, LOCALEDIR);
250 textdomain (PACKAGE);
252 atexit (close_stdout);
254 break_spaces = count_bytes = have_read_stdin = false;
256 while ((optc = getopt_long (argc, argv, shortopts, longopts, nullptr)) != -1)
258 char optargbuf[2];
260 switch (optc)
262 case 'b': /* Count bytes rather than columns. */
263 count_bytes = true;
264 break;
266 case 's': /* Break at word boundaries. */
267 break_spaces = true;
268 break;
270 case '0': case '1': case '2': case '3': case '4':
271 case '5': case '6': case '7': case '8': case '9':
272 if (optarg)
273 optarg--;
274 else
276 optargbuf[0] = optc;
277 optargbuf[1] = '\0';
278 optarg = optargbuf;
280 FALLTHROUGH;
281 case 'w': /* Line width. */
282 width = xdectoumax (optarg, 1, SIZE_MAX - TAB_WIDTH - 1, "",
283 _("invalid number of columns"), 0);
284 break;
286 case_GETOPT_HELP_CHAR;
288 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
290 default:
291 usage (EXIT_FAILURE);
295 if (argc == optind)
296 ok = fold_file ("-", width);
297 else
299 ok = true;
300 for (i = optind; i < argc; i++)
301 ok &= fold_file (argv[i], width);
304 if (have_read_stdin && fclose (stdin) == EOF)
305 error (EXIT_FAILURE, errno, "-");
307 return ok ? EXIT_SUCCESS : EXIT_FAILURE;