1 /* grep.c - main driver file for grep.
2 Copyright (C) 1992, 1997-2002, 2004-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, or (at your option)
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, write to the Free Software
16 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
19 /* Written July 1992 by Mike Haertel. */
22 #include <sys/types.h>
24 #include "mbsupport.h"
39 #include "fcntl-safer.h"
45 #include "propername.h"
47 #include "version-etc.h"
51 #define SEP_CHAR_SELECTED ':'
52 #define SEP_CHAR_REJECTED '-'
53 #define SEP_STR_GROUP "--"
55 #define STREQ(a, b) (strcmp (a, b) == 0)
58 proper_name ("Mike Haertel"), \
59 _("others, see\n<http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>")
61 /* When stdout is connected to a regular file, save its stat
62 information here, so that we can automatically skip it, thus
63 avoiding a potential (racy) infinite loop. */
64 static struct stat out_stat;
66 /* if non-zero, display usage information and exit */
69 /* If non-zero, print the version on standard output and exit. */
70 static int show_version;
72 /* If nonzero, suppress diagnostics for nonexistent or unreadable files. */
73 static int suppress_errors;
75 /* If nonzero, use color markers. */
76 static int color_option;
78 /* If nonzero, show only the part of a line matching the expression. */
79 static int only_matching;
81 /* If nonzero, make sure first content char in a line is on a tab stop. */
82 static int align_tabs;
84 /* The group separator used when context is requested. */
85 static const char *group_separator = SEP_STR_GROUP;
87 /* The context and logic for choosing default --color screen attributes
88 (foreground and background colors, etc.) are the following.
89 -- There are eight basic colors available, each with its own
90 nominal luminosity to the human eye and foreground/background
91 codes (black [0 %, 30/40], blue [11 %, 34/44], red [30 %, 31/41],
92 magenta [41 %, 35/45], green [59 %, 32/42], cyan [70 %, 36/46],
93 yellow [89 %, 33/43], and white [100 %, 37/47]).
94 -- Sometimes, white as a background is actually implemented using
95 a shade of light gray, so that a foreground white can be visible
96 on top of it (but most often not).
97 -- Sometimes, black as a foreground is actually implemented using
98 a shade of dark gray, so that it can be visible on top of a
99 background black (but most often not).
100 -- Sometimes, more colors are available, as extensions.
101 -- Other attributes can be selected/deselected (bold [1/22],
102 underline [4/24], standout/inverse [7/27], blink [5/25], and
103 invisible/hidden [8/28]). They are sometimes implemented by
104 using colors instead of what their names imply; e.g., bold is
105 often achieved by using brighter colors. In practice, only bold
106 is really available to us, underline sometimes being mapped by
107 the terminal to some strange color choice, and standout best
108 being left for use by downstream programs such as less(1).
109 -- We cannot assume that any of the extensions or special features
110 are available for the purpose of choosing defaults for everyone.
111 -- The most prevalent default terminal backgrounds are pure black
112 and pure white, and are not necessarily the same shades of
113 those as if they were selected explicitly with SGR sequences.
114 Some terminals use dark or light pictures as default background,
115 but those are covered over by an explicit selection of background
116 color with an SGR sequence; their users will appreciate their
117 background pictures not be covered like this, if possible.
118 -- Some uses of colors attributes is to make some output items
119 more understated (e.g., context lines); this cannot be achieved
120 by changing the background color.
121 -- For these reasons, the grep color defaults should strive not
122 to change the background color from its default, unless it's
123 for a short item that should be highlighted, not understated.
124 -- The grep foreground color defaults (without an explicitly set
125 background) should provide enough contrast to be readable on any
126 terminal with either a black (dark) or white (light) background.
127 This only leaves red, magenta, green, and cyan (and their bold
128 counterparts) and possibly bold blue. */
129 /* The color strings used for matched text.
130 The user can overwrite them using the deprecated
131 environment variable GREP_COLOR or the new GREP_COLORS. */
132 static const char *selected_match_color = "01;31"; /* bold red */
133 static const char *context_match_color = "01;31"; /* bold red */
135 /* Other colors. Defaults look damn good. */
136 static const char *filename_color = "35"; /* magenta */
137 static const char *line_num_color = "32"; /* green */
138 static const char *byte_num_color = "32"; /* green */
139 static const char *sep_color = "36"; /* cyan */
140 static const char *selected_line_color = ""; /* default color pair */
141 static const char *context_line_color = ""; /* default color pair */
143 /* Select Graphic Rendition (SGR, "\33[...m") strings. */
144 /* Also Erase in Line (EL) to Right ("\33[K") by default. */
145 /* Why have EL to Right after SGR?
146 -- The behavior of line-wrapping when at the bottom of the
147 terminal screen and at the end of the current line is often
148 such that a new line is introduced, entirely cleared with
149 the current background color which may be different from the
150 default one (see the boolean back_color_erase terminfo(5)
151 capability), thus scrolling the display by one line.
152 The end of this new line will stay in this background color
153 even after reverting to the default background color with
154 "\33[m', unless it is explicitly cleared again with "\33[K"
155 (which is the behavior the user would instinctively expect
156 from the whole thing). There may be some unavoidable
157 background-color flicker at the end of this new line because
158 of this (when timing with the monitor's redraw is just right).
159 -- The behavior of HT (tab, "\t") is usually the same as that of
160 Cursor Forward Tabulation (CHT) with a default parameter
161 of 1 ("\33[I"), i.e., it performs pure movement to the next
162 tab stop, without any clearing of either content or screen
163 attributes (including background color); try
164 printf 'asdfqwerzxcv\rASDF\tZXCV\n'
165 in a bash(1) shell to demonstrate this. This is not what the
166 user would instinctively expect of HT (but is ok for CHT).
167 The instinctive behavior would include clearing the terminal
168 cells that are skipped over by HT with blank cells in the
169 current screen attributes, including background color;
170 the boolean dest_tabs_magic_smso terminfo(5) capability
171 indicates this saner behavior for HT, but only some rare
172 terminals have it (although it also indicates a special
173 glitch with standout mode in the Teleray terminal for which
174 it was initially introduced). The remedy is to add "\33K"
175 after each SGR sequence, be it START (to fix the behavior
176 of any HT after that before another SGR) or END (to fix the
177 behavior of an HT in default background color that would
178 follow a line-wrapping at the bottom of the screen in another
179 background color, and to complement doing it after START).
180 Piping grep's output through a pager such as less(1) avoids
181 any HT problems since the pager performs tab expansion.
183 Generic disadvantages of this remedy are:
184 -- Some very rare terminals might support SGR but not EL (nobody
185 will use "grep --color" on a terminal that does not support
186 SGR in the first place).
187 -- Having these extra control sequences might somewhat complicate
188 the task of any program trying to parse "grep --color"
189 output in order to extract structuring information from it.
190 A specific disadvantage to doing it after SGR START is:
191 -- Even more possible background color flicker (when timing
192 with the monitor's redraw is just right), even when not at the
193 bottom of the screen.
194 There are no additional disadvantages specific to doing it after
197 It would be impractical for GNU grep to become a full-fledged
198 terminal program linked against ncurses or the like, so it will
199 not detect terminfo(5) capabilities. */
200 static const char *sgr_start = "\33[%sm\33[K";
201 static const char *sgr_end = "\33[m\33[K";
203 /* SGR utility functions. */
205 pr_sgr_start (char const *s)
208 print_start_colorize (sgr_start, s);
211 pr_sgr_end (char const *s)
214 print_end_colorize (sgr_end);
217 pr_sgr_start_if (char const *s)
223 pr_sgr_end_if (char const *s)
237 color_cap_mt_fct (void)
239 /* Our caller just set selected_match_color. */
240 context_match_color = selected_match_color;
244 color_cap_rv_fct (void)
246 /* By this point, it was 1 (or already -1). */
247 color_option = -1; /* That's still != 0. */
251 color_cap_ne_fct (void)
253 sgr_start = "\33[%sm";
257 /* For GREP_COLORS. */
258 static const struct color_cap color_dict[] =
260 { "mt", &selected_match_color, color_cap_mt_fct }, /* both ms/mc */
261 { "ms", &selected_match_color, NULL }, /* selected matched text */
262 { "mc", &context_match_color, NULL }, /* context matched text */
263 { "fn", &filename_color, NULL }, /* filename */
264 { "ln", &line_num_color, NULL }, /* line number */
265 { "bn", &byte_num_color, NULL }, /* byte (sic) offset */
266 { "se", &sep_color, NULL }, /* separator */
267 { "sl", &selected_line_color, NULL }, /* selected lines */
268 { "cx", &context_line_color, NULL }, /* context lines */
269 { "rv", NULL, color_cap_rv_fct }, /* -v reverses sl/cx */
270 { "ne", NULL, color_cap_ne_fct }, /* no EL on SGR_* */
274 static struct exclude *excluded_patterns;
275 static struct exclude *included_patterns;
276 static struct exclude *excluded_directory_patterns;
278 static char const short_options[] =
279 "0123456789A:B:C:D:EFGHIPTUVX:abcd:e:f:hiKLlm:noqRrsuvwxyZz";
281 /* Non-boolean long options that have no corresponding short equivalents. */
284 BINARY_FILES_OPTION = CHAR_MAX + 1,
289 LINE_BUFFERED_OPTION,
291 EXCLUDE_DIRECTORY_OPTION,
292 GROUP_SEPARATOR_OPTION,
296 /* Long options equivalences. */
297 static struct option const long_options[] =
299 {"basic-regexp", no_argument, NULL, 'G'},
300 {"extended-regexp", no_argument, NULL, 'E'},
301 {"fixed-regexp", no_argument, NULL, 'F'},
302 {"fixed-strings", no_argument, NULL, 'F'},
303 {"perl-regexp", no_argument, NULL, 'P'},
304 {"after-context", required_argument, NULL, 'A'},
305 {"before-context", required_argument, NULL, 'B'},
306 {"binary-files", required_argument, NULL, BINARY_FILES_OPTION},
307 {"byte-offset", no_argument, NULL, 'b'},
308 {"context", required_argument, NULL, 'C'},
309 {"color", optional_argument, NULL, COLOR_OPTION},
310 {"colour", optional_argument, NULL, COLOR_OPTION},
311 {"count", no_argument, NULL, 'c'},
312 {"devices", required_argument, NULL, 'D'},
313 {"directories", required_argument, NULL, 'd'},
314 {"exclude", required_argument, NULL, EXCLUDE_OPTION},
315 {"exclude-from", required_argument, NULL, EXCLUDE_FROM_OPTION},
316 {"exclude-dir", required_argument, NULL, EXCLUDE_DIRECTORY_OPTION},
317 {"file", required_argument, NULL, 'f'},
318 {"files-with-matches", no_argument, NULL, 'l'},
319 {"files-without-match", no_argument, NULL, 'L'},
320 {"group-separator", required_argument, NULL, GROUP_SEPARATOR_OPTION},
321 {"help", no_argument, &show_help, 1},
322 {"include", required_argument, NULL, INCLUDE_OPTION},
323 {"ignore-case", no_argument, NULL, 'i'},
324 {"initial-tab", no_argument, NULL, 'T'},
325 {"label", required_argument, NULL, LABEL_OPTION},
326 {"line-buffered", no_argument, NULL, LINE_BUFFERED_OPTION},
327 {"line-number", no_argument, NULL, 'n'},
328 {"line-regexp", no_argument, NULL, 'x'},
329 {"max-count", required_argument, NULL, 'm'},
331 /* FIXME: disabled in Mar 2010; warn towards end of 2011; remove in 2013. */
332 {"mmap", no_argument, NULL, MMAP_OPTION},
333 {"no-filename", no_argument, NULL, 'h'},
334 {"no-group-separator", no_argument, NULL, GROUP_SEPARATOR_OPTION},
335 {"no-messages", no_argument, NULL, 's'},
336 {"null", no_argument, NULL, 'Z'},
337 {"null-data", no_argument, NULL, 'z'},
338 {"only-matching", no_argument, NULL, 'o'},
339 {"quiet", no_argument, NULL, 'q'},
340 {"recursive", no_argument, NULL, 'r'},
341 {"dereference-recursive", no_argument, NULL, 'R'},
342 {"regexp", required_argument, NULL, 'e'},
343 {"invert-match", no_argument, NULL, 'v'},
344 {"silent", no_argument, NULL, 'q'},
345 {"text", no_argument, NULL, 'a'},
346 {"binary", no_argument, NULL, 'U'},
347 {"unix-byte-offsets", no_argument, NULL, 'u'},
348 {"version", no_argument, NULL, 'V'},
349 {"with-filename", no_argument, NULL, 'H'},
350 {"word-regexp", no_argument, NULL, 'w'},
354 /* Define flags declared in grep.h. */
358 unsigned char eolbyte;
360 /* For error messages. */
361 /* The input file name, or (if standard input) "-" or a --label argument. */
362 static char const *filename;
363 static size_t filename_prefix_len;
365 static int write_error_seen;
367 enum directories_type
369 READ_DIRECTORIES = 2,
374 /* How to handle directories. */
375 static char const *const directories_args[] =
377 "read", "recurse", "skip", NULL
379 static enum directories_type const directories_types[] =
381 READ_DIRECTORIES, RECURSE_DIRECTORIES, SKIP_DIRECTORIES
383 ARGMATCH_VERIFY (directories_args, directories_types);
385 static enum directories_type directories = READ_DIRECTORIES;
387 enum { basic_fts_options = FTS_CWDFD | FTS_NOSTAT | FTS_TIGHT_CYCLE_CHECK };
388 static int fts_options = basic_fts_options | FTS_COMFOLLOW | FTS_PHYSICAL;
390 /* How to handle devices. */
393 READ_COMMAND_LINE_DEVICES,
396 } devices = READ_COMMAND_LINE_DEVICES;
398 static int grepfile (int, char const *, int, int);
399 static int grepdesc (int, int);
400 #if defined HAVE_DOS_FILE_CONTENTS
401 static inline int undossify_input (char *, size_t);
405 is_device_mode (mode_t m)
407 return S_ISCHR (m) || S_ISBLK (m) || S_ISSOCK (m) || S_ISFIFO (m);
410 /* Functions we'll use to search. */
411 static compile_fp_t compile;
412 static execute_fp_t execute;
414 /* Like error, but suppress the diagnostic if requested. */
416 suppressible_error (char const *mesg, int errnum)
418 if (! suppress_errors)
419 error (0, errnum, "%s", mesg);
423 /* If there has already been a write error, don't bother closing
424 standard output, as that might elicit a duplicate diagnostic. */
426 clean_up_stdout (void)
428 if (! write_error_seen)
432 /* Convert STR to a nonnegative integer, storing the result in *OUT.
433 STR must be a valid context length argument; report an error if it
434 isn't. Silently ceiling *OUT at the maximum value, as that is
435 practically equivalent to infinity for grep's purposes. */
437 context_length_arg (char const *str, intmax_t *out)
439 switch (xstrtoimax (str, 0, 10, out, ""))
442 case LONGINT_OVERFLOW:
447 error (EXIT_TROUBLE, 0, "%s: %s", str,
448 _("invalid context length argument"));
453 /* Hairy buffering mechanism for grep. The intent is to keep
454 all reads aligned on a page boundary and multiples of the
455 page size, unless a read yields a partial page. */
457 static char *buffer; /* Base of buffer. */
458 static size_t bufalloc; /* Allocated buffer size, counting slop. */
459 #define INITIAL_BUFSIZE 32768 /* Initial buffer size, not counting slop. */
460 static int bufdesc; /* File descriptor. */
461 static char *bufbeg; /* Beginning of user-visible stuff. */
462 static char *buflim; /* Limit of user-visible stuff. */
463 static size_t pagesize; /* alignment of memory pages */
464 static off_t bufoffset; /* Read offset; defined on regular files. */
465 static off_t after_last_match; /* Pointer after last matching line that
466 would have been output if we were
467 outputting characters. */
469 /* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be
470 an integer or a pointer. Both args must be free of side effects. */
471 #define ALIGN_TO(val, alignment) \
472 ((size_t) (val) % (alignment) == 0 \
474 : (val) + ((alignment) - (size_t) (val) % (alignment)))
476 /* Reset the buffer for a new file, returning zero if we should skip it.
477 Initialize on the first time through. */
479 reset (int fd, struct stat const *st)
483 pagesize = getpagesize ();
484 if (pagesize == 0 || 2 * pagesize + 1 <= pagesize)
486 bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1;
487 buffer = xmalloc (bufalloc);
490 bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize);
491 bufbeg[-1] = eolbyte;
494 if (S_ISREG (st->st_mode))
496 if (fd != STDIN_FILENO)
500 bufoffset = lseek (fd, 0, SEEK_CUR);
503 suppressible_error (_("lseek failed"), errno);
511 /* Read new stuff into the buffer, saving the specified
512 amount of old stuff. When we're done, 'bufbeg' points
513 to the beginning of the buffer contents, and 'buflim'
514 points just after the end. Return zero if there's an error. */
516 fillbuf (size_t save, struct stat const *st)
523 /* Offset from start of buffer to start of old stuff
524 that we want to save. */
525 size_t saved_offset = buflim - save - buffer;
527 if (pagesize <= buffer + bufalloc - buflim)
530 bufbeg = buflim - save;
534 size_t minsize = save + pagesize;
539 /* Grow newsize until it is at least as great as minsize. */
540 for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2)
541 if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2)
544 /* Try not to allocate more memory than the file size indicates,
545 as that might cause unnecessary memory exhaustion if the file
546 is large. However, do not use the original file size as a
547 heuristic if we've already read past the file end, as most
548 likely the file is growing. */
549 if (S_ISREG (st->st_mode))
551 off_t to_be_read = st->st_size - bufoffset;
552 off_t maxsize_off = save + to_be_read;
553 if (0 <= to_be_read && to_be_read <= maxsize_off
554 && maxsize_off == (size_t) maxsize_off
555 && minsize <= (size_t) maxsize_off
556 && (size_t) maxsize_off < newsize)
557 newsize = maxsize_off;
560 /* Add enough room so that the buffer is aligned and has room
561 for byte sentinels fore and aft. */
562 newalloc = newsize + pagesize + 1;
564 newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer;
565 readbuf = ALIGN_TO (newbuf + 1 + save, pagesize);
566 bufbeg = readbuf - save;
567 memmove (bufbeg, buffer + saved_offset, save);
568 bufbeg[-1] = eolbyte;
569 if (newbuf != buffer)
576 readsize = buffer + bufalloc - readbuf;
577 readsize -= readsize % pagesize;
582 while ((bytesread = read (bufdesc, readbuf, readsize)) < 0
588 fillsize = bytesread;
591 bufoffset += fillsize;
592 #if defined HAVE_DOS_FILE_CONTENTS
594 fillsize = undossify_input (readbuf, fillsize);
596 buflim = readbuf + fillsize;
600 /* Flags controlling the style of output. */
605 WITHOUT_MATCH_BINARY_FILES
606 } binary_files; /* How to handle binary files. */
608 static int filename_mask; /* If zero, output nulls after filenames. */
609 static int out_quiet; /* Suppress all normal output. */
610 static int out_invert; /* Print nonmatching stuff. */
611 static int out_file; /* Print filenames. */
612 static int out_line; /* Print line numbers. */
613 static int out_byte; /* Print byte offsets. */
614 static intmax_t out_before; /* Lines of leading context. */
615 static intmax_t out_after; /* Lines of trailing context. */
616 static int count_matches; /* Count matching lines. */
617 static int list_files; /* List matching files. */
618 static int no_filenames; /* Suppress file names. */
619 static intmax_t max_count; /* Stop after outputting this many
620 lines from an input file. */
621 static int line_buffered; /* If nonzero, use line buffering, i.e.
622 fflush everyline out. */
623 static char *label = NULL; /* Fake filename for stdin */
626 /* Internal variables to keep track of byte count, context, etc. */
627 static uintmax_t totalcc; /* Total character count before bufbeg. */
628 static char const *lastnl; /* Pointer after last newline counted. */
629 static char const *lastout; /* Pointer after last character output;
630 NULL if no character has been output
631 or if it's conceptually before bufbeg. */
632 static uintmax_t totalnl; /* Total newline count before lastnl. */
633 static intmax_t outleft; /* Maximum number of lines to be output. */
634 static intmax_t pending; /* Pending lines of output.
635 Always kept 0 if out_quiet is true. */
636 static int done_on_match; /* Stop scanning file on first match. */
637 static int exit_on_match; /* Exit on first match. */
639 #if defined HAVE_DOS_FILE_CONTENTS
643 /* Add two numbers that count input bytes or lines, and report an
644 error if the addition overflows. */
646 add_count (uintmax_t a, uintmax_t b)
648 uintmax_t sum = a + b;
650 error (EXIT_TROUBLE, 0, _("input is too large to count"));
655 nlscan (char const *lim)
659 for (beg = lastnl; beg < lim; beg++)
661 beg = memchr (beg, eolbyte, lim - beg);
666 totalnl = add_count (totalnl, newlines);
670 /* Print the current filename. */
672 print_filename (void)
674 pr_sgr_start_if (filename_color);
675 fputs (filename, stdout);
676 pr_sgr_end_if (filename_color);
679 /* Print a character separator. */
683 pr_sgr_start_if (sep_color);
685 pr_sgr_end_if (sep_color);
688 /* Print a line number or a byte offset. */
690 print_offset (uintmax_t pos, int min_width, const char *color)
692 /* Do not rely on printf to print pos, since uintmax_t may be longer
693 than long, and long long is not portable. */
695 char buf[sizeof pos * CHAR_BIT];
696 char *p = buf + sizeof buf;
700 *--p = '0' + pos % 10;
703 while ((pos /= 10) != 0);
705 /* Do this to maximize the probability of alignment across lines. */
707 while (--min_width >= 0)
710 pr_sgr_start_if (color);
711 fwrite (p, 1, buf + sizeof buf - p, stdout);
712 pr_sgr_end_if (color);
715 /* Print a whole line head (filename, line, byte). */
717 print_line_head (char const *beg, char const *lim, int sep)
735 totalnl = add_count (totalnl, 1);
740 print_offset (totalnl, 4, line_num_color);
746 uintmax_t pos = add_count (totalcc, beg - bufbeg);
747 #if defined HAVE_DOS_FILE_CONTENTS
748 pos = dossified_pos (pos);
752 print_offset (pos, 6, byte_num_color);
758 /* This assumes sep is one column wide.
759 Try doing this any other way with Unicode
760 (and its combining and wide characters)
761 filenames and you're wasting your efforts. */
763 fputs ("\t\b", stdout);
770 print_line_middle (const char *beg, const char *lim,
771 const char *line_color, const char *match_color)
775 const char *cur = beg;
776 const char *mid = NULL;
779 && ((match_offset = execute (beg, lim - beg, &match_size,
780 beg + (cur - beg))) != (size_t) -1))
782 char const *b = beg + match_offset;
784 /* Avoid matching the empty line at the end of the buffer. */
788 /* Avoid hanging on grep --color "" foo */
791 /* Make minimal progress; there may be further non-empty matches. */
792 /* XXX - Could really advance by one whole multi-octet character. */
799 /* This function is called on a matching line only,
800 but is it selected or rejected/context? */
802 print_line_head (b, lim, (out_invert ? SEP_CHAR_REJECTED
803 : SEP_CHAR_SELECTED));
806 pr_sgr_start (line_color);
812 fwrite (cur, sizeof (char), b - cur, stdout);
815 pr_sgr_start_if (match_color);
816 fwrite (b, sizeof (char), match_size, stdout);
817 pr_sgr_end_if (match_color);
819 fputs ("\n", stdout);
821 cur = b + match_size;
833 print_line_tail (const char *beg, const char *lim, const char *line_color)
838 eol_size = (lim > beg && lim[-1] == eolbyte);
839 eol_size += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r');
840 tail_size = lim - eol_size - beg;
844 pr_sgr_start (line_color);
845 fwrite (beg, 1, tail_size, stdout);
847 pr_sgr_end (line_color);
854 prline (char const *beg, char const *lim, int sep)
857 const char *line_color;
858 const char *match_color;
861 print_line_head (beg, lim, sep);
863 matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert;
867 line_color = (((sep == SEP_CHAR_SELECTED)
868 ^ (out_invert && (color_option < 0)))
869 ? selected_line_color : context_line_color);
870 match_color = (sep == SEP_CHAR_SELECTED
871 ? selected_match_color : context_match_color);
874 line_color = match_color = NULL; /* Shouldn't be used. */
876 if ((only_matching && matching)
877 || (color_option && (*line_color || *match_color)))
879 /* We already know that non-matching lines have no match (to colorize). */
880 if (matching && (only_matching || *match_color))
881 beg = print_line_middle (beg, lim, line_color, match_color);
883 /* FIXME: this test may be removable. */
884 if (!only_matching && *line_color)
885 beg = print_line_tail (beg, lim, line_color);
888 if (!only_matching && lim > beg)
889 fwrite (beg, 1, lim - beg, stdout);
893 write_error_seen = 1;
894 error (EXIT_TROUBLE, 0, _("write error"));
903 /* Print pending lines of trailing context prior to LIM. Trailing context ends
904 at the next matching line when OUTLEFT is 0. */
906 prpending (char const *lim)
910 while (pending > 0 && lastout < lim)
912 char const *nl = memchr (lastout, eolbyte, lim - lastout);
916 || ((execute (lastout, nl + 1 - lastout,
917 &match_size, NULL) == (size_t) -1)
919 prline (lastout, nl + 1, SEP_CHAR_REJECTED);
925 /* Print the lines between BEG and LIM. Deal with context crap.
926 If NLINESP is non-null, store a count of lines between BEG and LIM. */
928 prtext (char const *beg, char const *lim, intmax_t *nlinesp)
930 static int used; /* avoid printing SEP_STR_GROUP before any output */
935 if (!out_quiet && pending > 0)
942 /* Deal with leading context crap. */
944 bp = lastout ? lastout : bufbeg;
945 for (i = 0; i < out_before; ++i)
949 while (p[-1] != eol);
951 /* We print the SEP_STR_GROUP separator only if our output is
952 discontiguous from the last output in the file. */
953 if ((out_before || out_after) && used && p != lastout && group_separator)
955 pr_sgr_start_if (sep_color);
956 fputs (group_separator, stdout);
957 pr_sgr_end_if (sep_color);
958 fputc ('\n', stdout);
963 char const *nl = memchr (p, eol, beg - p);
965 prline (p, nl, SEP_CHAR_REJECTED);
972 /* Caller wants a line count. */
973 for (n = 0; p < lim && n < outleft; n++)
975 char const *nl = memchr (p, eol, lim - p);
978 prline (p, nl, SEP_CHAR_SELECTED);
983 /* relying on it that this function is never called when outleft = 0. */
984 after_last_match = bufoffset - (buflim - p);
987 prline (beg, lim, SEP_CHAR_SELECTED);
989 pending = out_quiet ? 0 : out_after;
994 do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr)
997 const char *line_next;
999 /* With the current implementation, using --ignore-case with a multi-byte
1000 character set is very inefficient when applied to a large buffer
1001 containing many matches. We can avoid much of the wasted effort
1002 by matching line-by-line.
1004 FIXME: this is just an ugly workaround, and it doesn't really
1005 belong here. Also, PCRE is always using this same per-line
1006 matching algorithm. Either we fix -i, or we should refactor
1007 this code---for example, we could add another function pointer
1008 to struct matcher to split the buffer passed to execute. It would
1009 perform the memchr if line-by-line matching is necessary, or just
1010 return buf + size otherwise. */
1011 if (MB_CUR_MAX == 1 || !match_icase)
1012 return execute (buf, size, match_size, start_ptr);
1014 for (line_next = buf; line_next < buf + size; )
1016 const char *line_buf = line_next;
1017 const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf);
1018 if (line_end == NULL)
1019 line_next = line_end = buf + size;
1021 line_next = line_end + 1;
1023 if (start_ptr && start_ptr >= line_end)
1026 result = execute (line_buf, line_next - line_buf, match_size, start_ptr);
1027 if (result != (size_t) -1)
1028 return (line_buf - buf) + result;
1034 /* Scan the specified portion of the buffer, matching lines (or
1035 between matching lines if OUT_INVERT is true). Return a count of
1038 grepbuf (char const *beg, char const *lim)
1042 size_t match_offset;
1047 while ((match_offset = do_execute (p, lim - p, &match_size,
1048 NULL)) != (size_t) -1)
1050 char const *b = p + match_offset;
1051 char const *endp = b + match_size;
1052 /* Avoid matching the empty line at the end of the buffer. */
1057 prtext (b, endp, NULL);
1060 if (!outleft || done_on_match)
1063 exit (EXIT_SUCCESS);
1064 after_last_match = bufoffset - (buflim - endp);
1078 if (out_invert && p < lim)
1080 prtext (p, lim, &n);
1087 /* Search a given file. Normally, return a count of lines printed;
1088 but if the file is a directory and we search it recursively, then
1089 return -2 if there was a match, and -1 otherwise. */
1091 grep (int fd, struct stat const *st)
1095 size_t residue, save;
1101 if (! reset (fd, st))
1107 outleft = max_count;
1108 after_last_match = 0;
1115 if (! fillbuf (save, st))
1117 if (errno != EINVAL)
1118 suppressible_error (filename, errno);
1122 not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)
1123 || binary_files == WITHOUT_MATCH_BINARY_FILES)
1124 && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg));
1125 if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)
1127 done_on_match += not_text;
1128 out_quiet += not_text;
1136 beg = bufbeg + save;
1138 /* no more data to scan (eof) except for maybe a residue -> break */
1142 /* Determine new residue (the length of an incomplete line at the end of
1143 the buffer, 0 means there is no incomplete last line). */
1146 for (lim = buflim; lim[-1] != eol; lim--)
1150 lim = beg - residue;
1152 residue = buflim - lim;
1157 nlines += grepbuf (beg, lim);
1160 if ((!outleft && !pending) || (nlines && done_on_match && !out_invert))
1164 /* The last OUT_BEFORE lines at the end of the buffer will be needed as
1165 leading context if there is a matching line at the begin of the
1166 next data. Make beg point to their begin. */
1169 while (i < out_before && beg > bufbeg && beg != lastout)
1174 while (beg[-1] != eol);
1177 /* detect if leading context is discontinuous from last printed line. */
1181 /* Handle some details and read more data to scan. */
1182 save = residue + lim - beg;
1184 totalcc = add_count (totalcc, buflim - bufbeg - save);
1187 if (! fillbuf (save, st))
1189 suppressible_error (filename, errno);
1197 nlines += grepbuf (bufbeg + save - residue, buflim);
1203 done_on_match -= not_text;
1204 out_quiet -= not_text;
1205 if ((not_text & ~out_quiet) && nlines != 0)
1206 printf (_("Binary file %s matches\n"), filename);
1211 grepdirent (FTS *fts, FTSENT *ent)
1213 int follow, dirdesc;
1214 int command_line = ent->fts_level == FTS_ROOTLEVEL;
1215 struct stat *st = ent->fts_statp;
1217 if (ent->fts_info == FTS_DP)
1219 if (directories == RECURSE_DIRECTORIES && command_line)
1220 out_file &= ~ (2 * !no_filenames);
1224 if ((ent->fts_info == FTS_D || ent->fts_info == FTS_DC
1225 || ent->fts_info == FTS_DNR)
1226 ? (directories == SKIP_DIRECTORIES
1227 || (! (command_line && filename_prefix_len != 0)
1228 && excluded_directory_patterns
1229 && excluded_file_name (excluded_directory_patterns,
1231 : ((included_patterns
1232 && excluded_file_name (included_patterns, ent->fts_name))
1233 || (excluded_patterns
1234 && excluded_file_name (excluded_patterns, ent->fts_name))))
1236 fts_set (fts, ent, FTS_SKIP);
1240 filename = ent->fts_path + filename_prefix_len;
1241 follow = (fts->fts_options & FTS_LOGICAL
1242 || (fts->fts_options & FTS_COMFOLLOW && command_line));
1244 switch (ent->fts_info)
1247 if (directories == RECURSE_DIRECTORIES)
1249 out_file |= 2 * !no_filenames;
1252 fts_set (fts, ent, FTS_SKIP);
1256 if (!suppress_errors)
1257 error (0, 0, _("warning: %s: %s"), filename,
1258 _("recursive directory loop"));
1264 suppressible_error (filename, ent->fts_errno);
1269 if (devices == SKIP_DEVICES
1270 || (devices == READ_COMMAND_LINE_DEVICES && !command_line))
1275 /* The file type is not already known. Get the file status
1276 before opening, since opening might have side effects
1278 int flag = follow ? 0 : AT_SYMLINK_NOFOLLOW;
1279 if (fstatat (fts->fts_cwd_fd, ent->fts_accpath, &st1, flag) != 0)
1281 suppressible_error (filename, errno);
1286 if (is_device_mode (st->st_mode))
1303 dirdesc = ((fts->fts_options & (FTS_NOCHDIR | FTS_CWDFD)) == FTS_CWDFD
1306 return grepfile (dirdesc, ent->fts_accpath, follow, command_line);
1310 grepfile (int dirdesc, char const *name, int follow, int command_line)
1312 int desc = openat_safer (dirdesc, name, O_RDONLY | (follow ? 0 : O_NOFOLLOW));
1315 if (follow || (errno != ELOOP && errno != EMLINK))
1316 suppressible_error (filename, errno);
1319 return grepdesc (desc, command_line);
1323 grepdesc (int desc, int command_line)
1329 /* Get the file status, possibly for the second time. This catches
1330 a race condition if the directory entry changes after the
1331 directory entry is read and before the file is opened. For
1332 example, normally DESC is a directory only at the top level, but
1333 there is an exception if some other process substitutes a
1334 directory for a non-directory while 'grep' is running. */
1335 if (fstat (desc, &st) != 0)
1337 suppressible_error (filename, errno);
1340 if (desc != STDIN_FILENO
1341 && directories == RECURSE_DIRECTORIES && S_ISDIR (st.st_mode))
1343 /* Traverse the directory starting with its full name, because
1344 unfortunately fts provides no way to traverse the directory
1345 starting from its file descriptor. */
1349 int opts = fts_options & ~(command_line ? 0 : FTS_COMFOLLOW);
1352 /* Close DESC now, to conserve file descriptors if the race
1353 condition occurs many times in a deep recursion. */
1354 if (close (desc) != 0)
1355 suppressible_error (filename, errno);
1357 fts_arg[0] = (char *) filename;
1359 fts = fts_open (fts_arg, opts, NULL);
1363 while ((ent = fts_read (fts)))
1364 status &= grepdirent (fts, ent);
1366 suppressible_error (filename, errno);
1367 if (fts_close (fts) != 0)
1368 suppressible_error (filename, errno);
1371 if (desc != STDIN_FILENO
1372 && ((directories == SKIP_DIRECTORIES && S_ISDIR (st.st_mode))
1373 || ((devices == SKIP_DEVICES
1374 || (devices == READ_COMMAND_LINE_DEVICES && !command_line))
1375 && is_device_mode (st.st_mode))))
1378 /* If there is a regular file on stdout and the current file refers
1379 to the same i-node, we have to report the problem and skip it.
1380 Otherwise when matching lines from some other input reach the
1381 disk before we open this file, we can end up reading and matching
1382 those lines and appending them to the file from which we're reading.
1383 Then we'd have what appears to be an infinite loop that'd terminate
1384 only upon filling the output file system or reaching a quota.
1385 However, there is no risk of an infinite loop if grep is generating
1386 no output, i.e., with --silent, --quiet, -q.
1387 Similarly, with any of these:
1388 --max-count=N (-m) (for N >= 2)
1389 --files-with-matches (-l)
1390 --files-without-match (-L)
1391 there is no risk of trouble.
1392 For --max-count=1, grep stops after printing the first match,
1393 so there is no risk of malfunction. But even --max-count=2, with
1394 input==output, while there is no risk of infloop, there is a race
1395 condition that could result in "alternate" output. */
1396 if (!out_quiet && list_files == 0 && 1 < max_count
1397 && S_ISREG (out_stat.st_mode) && out_stat.st_ino
1398 && SAME_INODE (st, out_stat))
1400 if (! suppress_errors)
1401 error (0, 0, _("input file %s is also the output"), quote (filename));
1406 #if defined SET_BINARY
1407 /* Set input to binary mode. Pipes are simulated with files
1408 on DOS, so this includes the case of "foo | grep bar". */
1413 count = grep (desc, &st);
1424 print_sep (SEP_CHAR_SELECTED);
1428 printf ("%" PRIdMAX "\n", count);
1432 if (list_files == 1 - 2 * status)
1435 fputc ('\n' & filename_mask, stdout);
1438 if (desc == STDIN_FILENO)
1440 off_t required_offset = outleft ? bufoffset : after_last_match;
1441 if (required_offset != bufoffset
1442 && lseek (desc, required_offset, SEEK_SET) < 0
1443 && S_ISREG (st.st_mode))
1444 suppressible_error (filename, errno);
1449 if (desc != STDIN_FILENO && close (desc) != 0)
1450 suppressible_error (filename, errno);
1455 grep_command_line_arg (char const *arg)
1457 if (STREQ (arg, "-"))
1459 filename = label ? label : _("(standard input)");
1460 return grepdesc (STDIN_FILENO, 1);
1465 return grepfile (AT_FDCWD, arg, 1, 1);
1469 _Noreturn void usage (int);
1475 fprintf (stderr, _("Usage: %s [OPTION]... PATTERN [FILE]...\n"),
1477 fprintf (stderr, _("Try '%s --help' for more information.\n"),
1482 printf (_("Usage: %s [OPTION]... PATTERN [FILE]...\n"), program_name);
1484 Search for PATTERN in each FILE or standard input.\n"));
1485 fputs (_(before_options), stdout);
1487 Example: %s -i 'hello world' menu.h main.c\n\
1489 Regexp selection and interpretation:\n"), program_name);
1490 if (matchers[1].name)
1492 -E, --extended-regexp PATTERN is an extended regular expression (ERE)\n\
1493 -F, --fixed-strings PATTERN is a set of newline-separated fixed strings\n\
1494 -G, --basic-regexp PATTERN is a basic regular expression (BRE)\n\
1495 -P, --perl-regexp PATTERN is a Perl regular expression\n"));
1496 /* -X is undocumented on purpose. */
1498 -e, --regexp=PATTERN use PATTERN for matching\n\
1499 -f, --file=FILE obtain PATTERN from FILE\n\
1500 -i, --ignore-case ignore case distinctions\n\
1501 -w, --word-regexp force PATTERN to match only whole words\n\
1502 -x, --line-regexp force PATTERN to match only whole lines\n\
1503 -z, --null-data a data line ends in 0 byte, not newline\n"));
1507 -s, --no-messages suppress error messages\n\
1508 -v, --invert-match select non-matching lines\n\
1509 -V, --version print version information and exit\n\
1510 --help display this help and exit\n\
1511 --mmap deprecated no-op; evokes a warning\n"));
1515 -m, --max-count=NUM stop after NUM matches\n\
1516 -b, --byte-offset print the byte offset with output lines\n\
1517 -n, --line-number print line number with output lines\n\
1518 --line-buffered flush output on every line\n\
1519 -H, --with-filename print the file name for each match\n\
1520 -h, --no-filename suppress the file name prefix on output\n\
1521 --label=LABEL use LABEL as the standard input file name prefix\n\
1524 -o, --only-matching show only the part of a line matching PATTERN\n\
1525 -q, --quiet, --silent suppress all normal output\n\
1526 --binary-files=TYPE assume that binary files are TYPE;\n\
1527 TYPE is `binary', `text', or `without-match'\n\
1528 -a, --text equivalent to --binary-files=text\n\
1531 -I equivalent to --binary-files=without-match\n\
1532 -d, --directories=ACTION how to handle directories;\n\
1533 ACTION is `read', `recurse', or `skip'\n\
1534 -D, --devices=ACTION how to handle devices, FIFOs and sockets;\n\
1535 ACTION is `read' or `skip'\n\
1536 -r, --recursive like --directories=recurse\n\
1537 -R, --dereference-recursive likewise, but follow all symlinks\n\
1540 --include=FILE_PATTERN search only files that match FILE_PATTERN\n\
1541 --exclude=FILE_PATTERN skip files and directories matching FILE_PATTERN\n\
1542 --exclude-from=FILE skip files matching any file pattern from FILE\n\
1543 --exclude-dir=PATTERN directories that match PATTERN will be skipped.\n\
1546 -L, --files-without-match print only names of FILEs containing no match\n\
1547 -l, --files-with-matches print only names of FILEs containing matches\n\
1548 -c, --count print only a count of matching lines per FILE\n\
1549 -T, --initial-tab make tabs line up (if needed)\n\
1550 -Z, --null print 0 byte after FILE name\n"));
1554 -B, --before-context=NUM print NUM lines of leading context\n\
1555 -A, --after-context=NUM print NUM lines of trailing context\n\
1556 -C, --context=NUM print NUM lines of output context\n\
1559 -NUM same as --context=NUM\n\
1561 --colour[=WHEN] use markers to highlight the matching strings;\n\
1562 WHEN is `always', `never', or `auto'\n\
1563 -U, --binary do not strip CR characters at EOL (MSDOS/Windows)\n\
1564 -u, --unix-byte-offsets report offsets as if CRs were not there\n\
1567 fputs (_(after_options), stdout);
1569 When FILE is -, read standard input. With no FILE, read . if a command-line\n\
1570 -r is given, - otherwise. If fewer than two FILEs are given, assume -h.\n\
1571 Exit status is 0 if any line is selected, 1 otherwise;\n\
1572 if any error occurs and -q is not given, the exit status is 2.\n"));
1573 printf (_("\nReport bugs to: %s\n"), PACKAGE_BUGREPORT);
1574 printf (_("GNU Grep home page: <%s>\n"),
1575 "http://www.gnu.org/software/grep/");
1576 fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
1583 /* If M is NULL, initialize the matcher to the default. Otherwise set the
1584 matcher to M if available. Exit in case of conflicts or if M is not
1587 setmatcher (char const *m)
1589 static char const *matcher;
1594 compile = matchers[0].compile;
1595 execute = matchers[0].execute;
1596 if (!matchers[1].name)
1597 matcher = matchers[0].name;
1602 if (matcher && STREQ (matcher, m))
1605 else if (!matchers[1].name)
1606 error (EXIT_TROUBLE, 0, _("%s can only use the %s pattern syntax"),
1607 program_name, matcher);
1609 error (EXIT_TROUBLE, 0, _("conflicting matchers specified"));
1614 for (i = 0; matchers[i].name; i++)
1615 if (STREQ (m, matchers[i].name))
1617 compile = matchers[i].compile;
1618 execute = matchers[i].execute;
1623 error (EXIT_TROUBLE, 0, _("invalid matcher %s"), m);
1627 /* Find the white-space-separated options specified by OPTIONS, and
1628 using BUF to store copies of these options, set ARGV[0], ARGV[1],
1629 etc. to the option copies. Return the number N of options found.
1630 Do not set ARGV[N] to NULL. If ARGV is NULL, do not store ARGV[0]
1631 etc. Backslash can be used to escape whitespace (and backslashes). */
1633 prepend_args (char const *options, char *buf, char **argv)
1635 char const *o = options;
1641 while (c_isspace ((unsigned char) *o))
1650 if ((*b++ = *o++) == '\\' && *o)
1652 while (*o && ! c_isspace ((unsigned char) *o));
1658 /* Prepend the whitespace-separated options in OPTIONS to the argument
1659 vector of a main program with argument count *PARGC and argument
1660 vector *PARGV. Return the number of options prepended. */
1662 prepend_default_options (char const *options, int *pargc, char ***pargv)
1664 if (options && *options)
1666 char *buf = xmalloc (strlen (options) + 1);
1667 size_t prepended = prepend_args (options, buf, NULL);
1669 char *const *argv = *pargv;
1671 enum { MAX_ARGS = MIN (INT_MAX, SIZE_MAX / sizeof *pp - 1) };
1672 if (MAX_ARGS - argc < prepended)
1674 pp = xmalloc ((prepended + argc + 1) * sizeof *pp);
1675 *pargc = prepended + argc;
1678 pp += prepend_args (options, buf, pp);
1679 while ((*pp++ = *argv++))
1687 /* Get the next non-digit option from ARGC and ARGV.
1688 Return -1 if there are no more options.
1689 Process any digit options that were encountered on the way,
1690 and store the resulting integer into *DEFAULT_CONTEXT. */
1692 get_nondigit_option (int argc, char *const *argv, intmax_t *default_context)
1694 static int prev_digit_optind = -1;
1695 int opt, this_digit_optind, was_digit;
1696 char buf[INT_BUFSIZE_BOUND (intmax_t) + 4];
1700 this_digit_optind = optind;
1701 while (opt = getopt_long (argc, (char **) argv, short_options, long_options,
1703 '0' <= opt && opt <= '9')
1705 if (prev_digit_optind != this_digit_optind || !was_digit)
1707 /* Reset to start another context length argument. */
1712 /* Suppress trivial leading zeros, to avoid incorrect
1713 diagnostic on strings like 00000000000. */
1717 if (p == buf + sizeof buf - 4)
1719 /* Too many digits. Append "..." to make context_length_arg
1720 complain about "X...", where X contains the digits seen
1729 prev_digit_optind = this_digit_optind;
1730 this_digit_optind = optind;
1735 context_length_arg (buf, default_context);
1741 /* Parse GREP_COLORS. The default would look like:
1742 GREP_COLORS='ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36'
1743 with boolean capabilities (ne and rv) unset (i.e., omitted).
1744 No character escaping is needed or supported. */
1746 parse_grep_colors (void)
1753 p = getenv ("GREP_COLORS"); /* Plural! */
1754 if (p == NULL || *p == '\0')
1757 /* Work off a writable copy. */
1762 /* From now on, be well-formed or you're gone. */
1764 if (*q == ':' || *q == '\0')
1767 struct color_cap const *cap;
1769 *q++ = '\0'; /* Terminate name or val. */
1770 /* Empty name without val (empty cap)
1771 * won't match and will be ignored. */
1772 for (cap = color_dict; cap->name; cap++)
1773 if (STREQ (cap->name, name))
1775 /* If name unknown, go on for forward compatibility. */
1776 if (cap->var && val)
1787 if (q == name || val)
1789 *q++ = '\0'; /* Terminate name. */
1790 val = q; /* Can be the empty string. */
1792 else if (val == NULL)
1793 q++; /* Accumulate name. */
1794 else if (*q == ';' || (*q >= '0' && *q <= '9'))
1795 q++; /* Accumulate val. Protect the terminal from being sent crap. */
1801 main (int argc, char **argv)
1804 size_t keycc, oldcc, keyalloc;
1807 int opt, status, prepended;
1808 int prev_optind, last_recursive;
1809 intmax_t default_context;
1811 exit_failure = EXIT_TROUBLE;
1812 initialize_main (&argc, &argv);
1813 set_program_name (argv[0]);
1814 program_name = argv[0];
1822 max_count = INTMAX_MAX;
1824 /* The value -1 means to use DEFAULT_CONTEXT. */
1825 out_after = out_before = -1;
1826 /* Default before/after context: changed by -C/-NUM options */
1827 default_context = 0;
1828 /* Changed by -o option */
1831 /* Internationalization. */
1832 #if defined HAVE_SETLOCALE
1833 setlocale (LC_ALL, "");
1835 #if defined ENABLE_NLS
1836 bindtextdomain (PACKAGE, LOCALEDIR);
1837 textdomain (PACKAGE);
1840 exit_failure = EXIT_TROUBLE;
1841 atexit (clean_up_stdout);
1844 prepended = prepend_default_options (getenv ("GREP_OPTIONS"), &argc, &argv);
1847 while (prev_optind = optind,
1848 (opt = get_nondigit_option (argc, argv, &default_context)) != -1)
1852 context_length_arg (optarg, &out_after);
1856 context_length_arg (optarg, &out_before);
1860 /* Set output match context, but let any explicit leading or
1861 trailing amount specified with -A or -B stand. */
1862 context_length_arg (optarg, &default_context);
1866 if (STREQ (optarg, "read"))
1867 devices = READ_DEVICES;
1868 else if (STREQ (optarg, "skip"))
1869 devices = SKIP_DEVICES;
1871 error (EXIT_TROUBLE, 0, _("unknown devices method"));
1875 setmatcher ("egrep");
1879 setmatcher ("fgrep");
1883 setmatcher ("perl");
1887 setmatcher ("grep");
1890 case 'X': /* undocumented on purpose */
1891 setmatcher (optarg);
1900 binary_files = WITHOUT_MATCH_BINARY_FILES;
1908 #if defined HAVE_DOS_FILE_CONTENTS
1909 dos_use_file_type = DOS_BINARY;
1914 #if defined HAVE_DOS_FILE_CONTENTS
1915 dos_report_unix_offset = 1;
1924 binary_files = TEXT_BINARY_FILES;
1936 directories = XARGMATCH ("--directories", optarg,
1937 directories_args, directories_types);
1938 if (directories == RECURSE_DIRECTORIES)
1939 last_recursive = prev_optind;
1943 cc = strlen (optarg);
1944 keys = xrealloc (keys, keycc + cc + 1);
1945 strcpy (&keys[keycc], optarg);
1947 keys[keycc++] = '\n';
1951 fp = STREQ (optarg, "-") ? stdin : fopen (optarg, "r");
1953 error (EXIT_TROUBLE, errno, "%s", optarg);
1954 for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
1956 keys = xrealloc (keys, keyalloc);
1959 && (cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) > 0)
1962 if (keycc == keyalloc - 1)
1963 keys = x2nrealloc (keys, &keyalloc, sizeof *keys);
1967 /* Append final newline if file ended in non-newline. */
1968 if (oldcc != keycc && keys[keycc - 1] != '\n')
1969 keys[keycc++] = '\n';
1978 case 'y': /* For old-timers . . . */
1983 /* Like -l, except list files that don't contain matches.
1984 Inspired by the same option in Hume's gre. */
1993 switch (xstrtoimax (optarg, 0, 10, &max_count, ""))
1996 case LONGINT_OVERFLOW:
2000 error (EXIT_TROUBLE, 0, _("invalid max count"));
2018 fts_options = basic_fts_options | FTS_LOGICAL;
2021 directories = RECURSE_DIRECTORIES;
2022 last_recursive = prev_optind;
2026 suppress_errors = 1;
2049 case BINARY_FILES_OPTION:
2050 if (STREQ (optarg, "binary"))
2051 binary_files = BINARY_BINARY_FILES;
2052 else if (STREQ (optarg, "text"))
2053 binary_files = TEXT_BINARY_FILES;
2054 else if (STREQ (optarg, "without-match"))
2055 binary_files = WITHOUT_MATCH_BINARY_FILES;
2057 error (EXIT_TROUBLE, 0, _("unknown binary-files type"));
2063 if (!strcasecmp (optarg, "always") || !strcasecmp (optarg, "yes")
2064 || !strcasecmp (optarg, "force"))
2066 else if (!strcasecmp (optarg, "never") || !strcasecmp (optarg, "no")
2067 || !strcasecmp (optarg, "none"))
2069 else if (!strcasecmp (optarg, "auto") || !strcasecmp (optarg, "tty")
2070 || !strcasecmp (optarg, "if-tty"))
2079 case EXCLUDE_OPTION:
2080 if (!excluded_patterns)
2081 excluded_patterns = new_exclude ();
2082 add_exclude (excluded_patterns, optarg, EXCLUDE_WILDCARDS);
2084 case EXCLUDE_FROM_OPTION:
2085 if (!excluded_patterns)
2086 excluded_patterns = new_exclude ();
2087 if (add_exclude_file (add_exclude, excluded_patterns, optarg,
2088 EXCLUDE_WILDCARDS, '\n') != 0)
2090 error (EXIT_TROUBLE, errno, "%s", optarg);
2094 case EXCLUDE_DIRECTORY_OPTION:
2095 if (!excluded_directory_patterns)
2096 excluded_directory_patterns = new_exclude ();
2097 add_exclude (excluded_directory_patterns, optarg, EXCLUDE_WILDCARDS);
2100 case INCLUDE_OPTION:
2101 if (!included_patterns)
2102 included_patterns = new_exclude ();
2103 add_exclude (included_patterns, optarg,
2104 EXCLUDE_WILDCARDS | EXCLUDE_INCLUDE);
2107 case GROUP_SEPARATOR_OPTION:
2108 group_separator = optarg;
2111 case LINE_BUFFERED_OPTION:
2120 error (0, 0, _("the --mmap option has been a no-op since 2010"));
2128 usage (EXIT_TROUBLE);
2133 if (color_option == 2)
2134 color_option = isatty (STDOUT_FILENO) && should_colorize ();
2137 /* POSIX.2 says that -q overrides -l, which in turn overrides the
2138 other output options. */
2141 if (exit_on_match | list_files)
2146 out_quiet = count_matches | done_on_match;
2149 out_after = default_context;
2151 out_before = default_context;
2156 char *userval = getenv ("GREP_COLOR");
2157 if (userval != NULL && *userval != '\0')
2158 selected_match_color = context_match_color = userval;
2160 /* New GREP_COLORS has priority. */
2161 parse_grep_colors ();
2166 version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS,
2168 exit (EXIT_SUCCESS);
2172 usage (EXIT_SUCCESS);
2174 struct stat tmp_stat;
2175 if (fstat (STDOUT_FILENO, &tmp_stat) == 0 && S_ISREG (tmp_stat.st_mode))
2176 out_stat = tmp_stat;
2182 /* No keys were specified (e.g. -f /dev/null). Match nothing. */
2184 match_lines = match_words = 0;
2187 /* Strip trailing newline. */
2190 else if (optind < argc)
2192 /* A copy must be made in case of an xrealloc() or free() later. */
2193 keycc = strlen (argv[optind]);
2194 keys = xmalloc (keycc + 1);
2195 strcpy (keys, argv[optind++]);
2198 usage (EXIT_TROUBLE);
2200 compile (keys, keycc);
2203 if ((argc - optind > 1 && !no_filenames) || with_filenames)
2207 /* Output is set to binary mode because we shouldn't convert
2208 NL to CR-LF pairs, especially when grepping binary files. */
2214 exit (EXIT_FAILURE);
2216 if (fts_options & FTS_LOGICAL && devices == READ_COMMAND_LINE_DEVICES)
2217 devices = READ_DEVICES;
2223 status &= grep_command_line_arg (argv[optind]);
2224 while (++optind < argc);
2226 else if (directories == RECURSE_DIRECTORIES && prepended < last_recursive)
2228 /* Grep through ".", omitting leading "./" from diagnostics. */
2229 filename_prefix_len = 2;
2230 status = grep_command_line_arg (".");
2233 status = grep_command_line_arg ("-");
2235 /* We register via atexit() to test stdout. */
2236 exit (errseen ? EXIT_TROUBLE : status);
2238 /* vim:set shiftwidth=2: */