1 /* grep.c - main driver file for grep.
2 Copyright (C) 1992, 1997-2002, 2004-2010 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 #if defined HAVE_SETRLIMIT
25 # include <sys/time.h>
26 # include <sys/resource.h>
28 #include "mbsupport.h"
46 #include "propername.h"
48 #include "version-etc.h"
52 #define SEP_CHAR_SELECTED ':'
53 #define SEP_CHAR_REJECTED '-'
54 #define SEP_STR_GROUP "--"
56 #define STREQ(a, b) (strcmp (a, b) == 0)
59 proper_name ("Mike Haertel"), \
60 _("others, see\n<http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>")
64 struct stats const *parent;
68 /* base of chain of stat buffers, used to detect directory loops */
69 static struct stats stats_base;
71 /* if non-zero, display usage information and exit */
74 /* If non-zero, print the version on standard output and exit. */
75 static int show_version;
77 /* If nonzero, suppress diagnostics for nonexistent or unreadable files. */
78 static int suppress_errors;
80 /* If nonzero, use color markers. */
81 static int color_option;
83 /* If nonzero, show only the part of a line matching the expression. */
84 static int only_matching;
86 /* If nonzero, make sure first content char in a line is on a tab stop. */
87 static int align_tabs;
89 /* The group separator used when context is requested. */
90 static const char *group_separator = SEP_STR_GROUP;
92 /* The context and logic for choosing default --color screen attributes
93 (foreground and background colors, etc.) are the following.
94 -- There are eight basic colors available, each with its own
95 nominal luminosity to the human eye and foreground/background
96 codes (black [0 %, 30/40], blue [11 %, 34/44], red [30 %, 31/41],
97 magenta [41 %, 35/45], green [59 %, 32/42], cyan [70 %, 36/46],
98 yellow [89 %, 33/43], and white [100 %, 37/47]).
99 -- Sometimes, white as a background is actually implemented using
100 a shade of light gray, so that a foreground white can be visible
101 on top of it (but most often not).
102 -- Sometimes, black as a foreground is actually implemented using
103 a shade of dark gray, so that it can be visible on top of a
104 background black (but most often not).
105 -- Sometimes, more colors are available, as extensions.
106 -- Other attributes can be selected/deselected (bold [1/22],
107 underline [4/24], standout/inverse [7/27], blink [5/25], and
108 invisible/hidden [8/28]). They are sometimes implemented by
109 using colors instead of what their names imply; e.g., bold is
110 often achieved by using brighter colors. In practice, only bold
111 is really available to us, underline sometimes being mapped by
112 the terminal to some strange color choice, and standout best
113 being left for use by downstream programs such as less(1).
114 -- We cannot assume that any of the extensions or special features
115 are available for the purpose of choosing defaults for everyone.
116 -- The most prevalent default terminal backgrounds are pure black
117 and pure white, and are not necessarily the same shades of
118 those as if they were selected explicitly with SGR sequences.
119 Some terminals use dark or light pictures as default background,
120 but those are covered over by an explicit selection of background
121 color with an SGR sequence; their users will appreciate their
122 background pictures not be covered like this, if possible.
123 -- Some uses of colors attributes is to make some output items
124 more understated (e.g., context lines); this cannot be achieved
125 by changing the background color.
126 -- For these reasons, the grep color defaults should strive not
127 to change the background color from its default, unless it's
128 for a short item that should be highlighted, not understated.
129 -- The grep foreground color defaults (without an explicitly set
130 background) should provide enough contrast to be readable on any
131 terminal with either a black (dark) or white (light) background.
132 This only leaves red, magenta, green, and cyan (and their bold
133 counterparts) and possibly bold blue. */
134 /* The color strings used for matched text.
135 The user can overwrite them using the deprecated
136 environment variable GREP_COLOR or the new GREP_COLORS. */
137 static const char *selected_match_color = "01;31"; /* bold red */
138 static const char *context_match_color = "01;31"; /* bold red */
140 /* Other colors. Defaults look damn good. */
141 static const char *filename_color = "35"; /* magenta */
142 static const char *line_num_color = "32"; /* green */
143 static const char *byte_num_color = "32"; /* green */
144 static const char *sep_color = "36"; /* cyan */
145 static const char *selected_line_color = ""; /* default color pair */
146 static const char *context_line_color = ""; /* default color pair */
148 /* Select Graphic Rendition (SGR, "\33[...m") strings. */
149 /* Also Erase in Line (EL) to Right ("\33[K") by default. */
150 /* Why have EL to Right after SGR?
151 -- The behavior of line-wrapping when at the bottom of the
152 terminal screen and at the end of the current line is often
153 such that a new line is introduced, entirely cleared with
154 the current background color which may be different from the
155 default one (see the boolean back_color_erase terminfo(5)
156 capability), thus scrolling the display by one line.
157 The end of this new line will stay in this background color
158 even after reverting to the default background color with
159 "\33[m', unless it is explicitly cleared again with "\33[K"
160 (which is the behavior the user would instinctively expect
161 from the whole thing). There may be some unavoidable
162 background-color flicker at the end of this new line because
163 of this (when timing with the monitor's redraw is just right).
164 -- The behavior of HT (tab, "\t") is usually the same as that of
165 Cursor Forward Tabulation (CHT) with a default parameter
166 of 1 ("\33[I"), i.e., it performs pure movement to the next
167 tab stop, without any clearing of either content or screen
168 attributes (including background color); try
169 printf 'asdfqwerzxcv\rASDF\tZXCV\n'
170 in a bash(1) shell to demonstrate this. This is not what the
171 user would instinctively expect of HT (but is ok for CHT).
172 The instinctive behavior would include clearing the terminal
173 cells that are skipped over by HT with blank cells in the
174 current screen attributes, including background color;
175 the boolean dest_tabs_magic_smso terminfo(5) capability
176 indicates this saner behavior for HT, but only some rare
177 terminals have it (although it also indicates a special
178 glitch with standout mode in the Teleray terminal for which
179 it was initially introduced). The remedy is to add "\33K"
180 after each SGR sequence, be it START (to fix the behavior
181 of any HT after that before another SGR) or END (to fix the
182 behavior of an HT in default background color that would
183 follow a line-wrapping at the bottom of the screen in another
184 background color, and to complement doing it after START).
185 Piping grep's output through a pager such as less(1) avoids
186 any HT problems since the pager performs tab expansion.
188 Generic disadvantages of this remedy are:
189 -- Some very rare terminals might support SGR but not EL (nobody
190 will use "grep --color" on a terminal that does not support
191 SGR in the first place).
192 -- Having these extra control sequences might somewhat complicate
193 the task of any program trying to parse "grep --color"
194 output in order to extract structuring information from it.
195 A specific disadvantage to doing it after SGR START is:
196 -- Even more possible background color flicker (when timing
197 with the monitor's redraw is just right), even when not at the
198 bottom of the screen.
199 There are no additional disadvantages specific to doing it after
202 It would be impractical for GNU grep to become a full-fledged
203 terminal program linked against ncurses or the like, so it will
204 not detect terminfo(5) capabilities. */
205 static const char *sgr_start = "\33[%sm\33[K";
206 #define SGR_START sgr_start
207 static const char *sgr_end = "\33[m\33[K";
208 #define SGR_END sgr_end
210 /* SGR utility macros. */
211 #define PR_SGR_FMT(fmt, s) do { if (*(s)) printf((fmt), (s)); } while (0)
212 #define PR_SGR_FMT_IF(fmt, s) \
213 do { if (color_option && *(s)) printf((fmt), (s)); } while (0)
214 #define PR_SGR_START(s) PR_SGR_FMT( SGR_START, (s))
215 #define PR_SGR_END(s) PR_SGR_FMT( SGR_END, (s))
216 #define PR_SGR_START_IF(s) PR_SGR_FMT_IF(SGR_START, (s))
217 #define PR_SGR_END_IF(s) PR_SGR_FMT_IF(SGR_END, (s))
223 const char *(*fct)(void);
227 color_cap_mt_fct(void)
229 /* Our caller just set selected_match_color. */
230 context_match_color = selected_match_color;
236 color_cap_rv_fct(void)
238 /* By this point, it was 1 (or already -1). */
239 color_option = -1; /* That's still != 0. */
245 color_cap_ne_fct(void)
247 sgr_start = "\33[%sm";
253 /* For GREP_COLORS. */
254 static struct color_cap color_dict[] =
256 { "mt", &selected_match_color, color_cap_mt_fct }, /* both ms/mc */
257 { "ms", &selected_match_color, NULL }, /* selected matched text */
258 { "mc", &context_match_color, NULL }, /* context matched text */
259 { "fn", &filename_color, NULL }, /* filename */
260 { "ln", &line_num_color, NULL }, /* line number */
261 { "bn", &byte_num_color, NULL }, /* byte (sic) offset */
262 { "se", &sep_color, NULL }, /* separator */
263 { "sl", &selected_line_color, NULL }, /* selected lines */
264 { "cx", &context_line_color, NULL }, /* context lines */
265 { "rv", NULL, color_cap_rv_fct }, /* -v reverses sl/cx */
266 { "ne", NULL, color_cap_ne_fct }, /* no EL on SGR_* */
270 static struct exclude *excluded_patterns;
271 static struct exclude *included_patterns;
272 static struct exclude *excluded_directory_patterns;
274 static char const short_options[] =
275 "0123456789A:B:C:D:EFGHIPTUVX:abcd:e:f:hiKLlm:noqRrsuvwxyZz";
277 /* Non-boolean long options that have no corresponding short equivalents. */
280 BINARY_FILES_OPTION = CHAR_MAX + 1,
285 LINE_BUFFERED_OPTION,
287 EXCLUDE_DIRECTORY_OPTION,
288 GROUP_SEPARATOR_OPTION,
292 /* Long options equivalences. */
293 static struct option const long_options[] =
295 {"basic-regexp", no_argument, NULL, 'G'},
296 {"extended-regexp", no_argument, NULL, 'E'},
297 {"fixed-regexp", no_argument, NULL, 'F'},
298 {"fixed-strings", no_argument, NULL, 'F'},
299 {"perl-regexp", no_argument, NULL, 'P'},
300 {"after-context", required_argument, NULL, 'A'},
301 {"before-context", required_argument, NULL, 'B'},
302 {"binary-files", required_argument, NULL, BINARY_FILES_OPTION},
303 {"byte-offset", no_argument, NULL, 'b'},
304 {"context", required_argument, NULL, 'C'},
305 {"color", optional_argument, NULL, COLOR_OPTION},
306 {"colour", optional_argument, NULL, COLOR_OPTION},
307 {"count", no_argument, NULL, 'c'},
308 {"devices", required_argument, NULL, 'D'},
309 {"directories", required_argument, NULL, 'd'},
310 {"exclude", required_argument, NULL, EXCLUDE_OPTION},
311 {"exclude-from", required_argument, NULL, EXCLUDE_FROM_OPTION},
312 {"exclude-dir", required_argument, NULL, EXCLUDE_DIRECTORY_OPTION},
313 {"file", required_argument, NULL, 'f'},
314 {"files-with-matches", no_argument, NULL, 'l'},
315 {"files-without-match", no_argument, NULL, 'L'},
316 {"group-separator", required_argument, NULL, GROUP_SEPARATOR_OPTION},
317 {"help", no_argument, &show_help, 1},
318 {"include", required_argument, NULL, INCLUDE_OPTION},
319 {"ignore-case", no_argument, NULL, 'i'},
320 {"initial-tab", no_argument, NULL, 'T'},
321 {"label", required_argument, NULL, LABEL_OPTION},
322 {"line-buffered", no_argument, NULL, LINE_BUFFERED_OPTION},
323 {"line-number", no_argument, NULL, 'n'},
324 {"line-regexp", no_argument, NULL, 'x'},
325 {"max-count", required_argument, NULL, 'm'},
327 /* FIXME: disabled in Mar 2010; warn towards end of 2011; remove in 2013. */
328 {"mmap", no_argument, NULL, MMAP_OPTION},
329 {"no-filename", no_argument, NULL, 'h'},
330 {"no-group-separator", no_argument, NULL, GROUP_SEPARATOR_OPTION},
331 {"no-messages", no_argument, NULL, 's'},
332 {"null", no_argument, NULL, 'Z'},
333 {"null-data", no_argument, NULL, 'z'},
334 {"only-matching", no_argument, NULL, 'o'},
335 {"quiet", no_argument, NULL, 'q'},
336 {"recursive", no_argument, NULL, 'r'},
337 {"recursive", no_argument, NULL, 'R'},
338 {"regexp", required_argument, NULL, 'e'},
339 {"invert-match", no_argument, NULL, 'v'},
340 {"silent", no_argument, NULL, 'q'},
341 {"text", no_argument, NULL, 'a'},
342 {"binary", no_argument, NULL, 'U'},
343 {"unix-byte-offsets", no_argument, NULL, 'u'},
344 {"version", no_argument, NULL, 'V'},
345 {"with-filename", no_argument, NULL, 'H'},
346 {"word-regexp", no_argument, NULL, 'w'},
350 /* Define flags declared in grep.h. */
354 unsigned char eolbyte;
356 /* For error messages. */
357 /* The name the program was run with, stripped of any leading path. */
358 static char const *filename;
361 enum directories_type
363 READ_DIRECTORIES = 2,
368 /* How to handle directories. */
369 static char const *const directories_args[] =
371 "read", "recurse", "skip", NULL
373 static enum directories_type const directories_types[] =
375 READ_DIRECTORIES, RECURSE_DIRECTORIES, SKIP_DIRECTORIES
377 ARGMATCH_VERIFY (directories_args, directories_types);
379 static enum directories_type directories = READ_DIRECTORIES;
381 /* How to handle devices. */
386 } devices = READ_DEVICES;
388 static int grepdir (char const *, struct stats const *);
389 #if defined HAVE_DOS_FILE_CONTENTS
390 static inline int undossify_input (char *, size_t);
393 /* Functions we'll use to search. */
394 static compile_fp_t compile;
395 static execute_fp_t execute;
397 /* Like error, but suppress the diagnostic if requested. */
399 suppressible_error (char const *mesg, int errnum)
401 if (! suppress_errors)
402 error (0, errnum, "%s", mesg);
406 /* Convert STR to a positive integer, storing the result in *OUT.
407 STR must be a valid context length argument; report an error if it
410 context_length_arg (char const *str, int *out)
413 if (! (xstrtoumax (str, 0, 10, &value, "") == LONGINT_OK
414 && 0 <= (*out = value)
417 error (EXIT_TROUBLE, 0, "%s: %s", str,
418 _("invalid context length argument"));
423 /* Hairy buffering mechanism for grep. The intent is to keep
424 all reads aligned on a page boundary and multiples of the
425 page size, unless a read yields a partial page. */
427 static char *buffer; /* Base of buffer. */
428 static size_t bufalloc; /* Allocated buffer size, counting slop. */
429 #define INITIAL_BUFSIZE 32768 /* Initial buffer size, not counting slop. */
430 static int bufdesc; /* File descriptor. */
431 static char *bufbeg; /* Beginning of user-visible stuff. */
432 static char *buflim; /* Limit of user-visible stuff. */
433 static size_t pagesize; /* alignment of memory pages */
434 static off_t bufoffset; /* Read offset; defined on regular files. */
435 static off_t after_last_match; /* Pointer after last matching line that
436 would have been output if we were
437 outputting characters. */
439 /* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be
440 an integer or a pointer. Both args must be free of side effects. */
441 #define ALIGN_TO(val, alignment) \
442 ((size_t) (val) % (alignment) == 0 \
444 : (val) + ((alignment) - (size_t) (val) % (alignment)))
446 /* Reset the buffer for a new file, returning zero if we should skip it.
447 Initialize on the first time through. */
449 reset (int fd, char const *file, struct stats *stats)
453 pagesize = getpagesize ();
454 if (pagesize == 0 || 2 * pagesize + 1 <= pagesize)
456 bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1;
457 buffer = xmalloc (bufalloc);
460 bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize);
461 bufbeg[-1] = eolbyte;
464 if (S_ISREG (stats->stat.st_mode))
470 bufoffset = lseek (fd, 0, SEEK_CUR);
473 error (0, errno, _("lseek failed"));
481 /* Read new stuff into the buffer, saving the specified
482 amount of old stuff. When we're done, 'bufbeg' points
483 to the beginning of the buffer contents, and 'buflim'
484 points just after the end. Return zero if there's an error. */
486 fillbuf (size_t save, struct stats const *stats)
493 /* Offset from start of buffer to start of old stuff
494 that we want to save. */
495 size_t saved_offset = buflim - save - buffer;
497 if (pagesize <= buffer + bufalloc - buflim)
500 bufbeg = buflim - save;
504 size_t minsize = save + pagesize;
509 /* Grow newsize until it is at least as great as minsize. */
510 for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2)
511 if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2)
514 /* Try not to allocate more memory than the file size indicates,
515 as that might cause unnecessary memory exhaustion if the file
516 is large. However, do not use the original file size as a
517 heuristic if we've already read past the file end, as most
518 likely the file is growing. */
519 if (S_ISREG (stats->stat.st_mode))
521 off_t to_be_read = stats->stat.st_size - bufoffset;
522 off_t maxsize_off = save + to_be_read;
523 if (0 <= to_be_read && to_be_read <= maxsize_off
524 && maxsize_off == (size_t) maxsize_off
525 && minsize <= (size_t) maxsize_off
526 && (size_t) maxsize_off < newsize)
527 newsize = maxsize_off;
530 /* Add enough room so that the buffer is aligned and has room
531 for byte sentinels fore and aft. */
532 newalloc = newsize + pagesize + 1;
534 newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer;
535 readbuf = ALIGN_TO (newbuf + 1 + save, pagesize);
536 bufbeg = readbuf - save;
537 memmove (bufbeg, buffer + saved_offset, save);
538 bufbeg[-1] = eolbyte;
539 if (newbuf != buffer)
546 readsize = buffer + bufalloc - readbuf;
547 readsize -= readsize % pagesize;
552 while ((bytesread = read (bufdesc, readbuf, readsize)) < 0
558 fillsize = bytesread;
561 bufoffset += fillsize;
562 #if defined HAVE_DOS_FILE_CONTENTS
564 fillsize = undossify_input (readbuf, fillsize);
566 buflim = readbuf + fillsize;
570 /* Flags controlling the style of output. */
575 WITHOUT_MATCH_BINARY_FILES
576 } binary_files; /* How to handle binary files. */
578 static int filename_mask; /* If zero, output nulls after filenames. */
579 static int out_quiet; /* Suppress all normal output. */
580 static int out_invert; /* Print nonmatching stuff. */
581 static int out_file; /* Print filenames. */
582 static int out_line; /* Print line numbers. */
583 static int out_byte; /* Print byte offsets. */
584 static int out_before; /* Lines of leading context. */
585 static int out_after; /* Lines of trailing context. */
586 static int count_matches; /* Count matching lines. */
587 static int list_files; /* List matching files. */
588 static int no_filenames; /* Suppress file names. */
589 static off_t max_count; /* Stop after outputting this many
590 lines from an input file. */
591 static int line_buffered; /* If nonzero, use line buffering, i.e.
592 fflush everyline out. */
593 static char *label = NULL; /* Fake filename for stdin */
596 /* Internal variables to keep track of byte count, context, etc. */
597 static uintmax_t totalcc; /* Total character count before bufbeg. */
598 static char const *lastnl; /* Pointer after last newline counted. */
599 static char const *lastout; /* Pointer after last character output;
600 NULL if no character has been output
601 or if it's conceptually before bufbeg. */
602 static uintmax_t totalnl; /* Total newline count before lastnl. */
603 static off_t outleft; /* Maximum number of lines to be output. */
604 static int pending; /* Pending lines of output.
605 Always kept 0 if out_quiet is true. */
606 static int done_on_match; /* Stop scanning file on first match. */
607 static int exit_on_match; /* Exit on first match. */
609 #if defined HAVE_DOS_FILE_CONTENTS
613 /* Add two numbers that count input bytes or lines, and report an
614 error if the addition overflows. */
616 add_count (uintmax_t a, uintmax_t b)
618 uintmax_t sum = a + b;
620 error (EXIT_TROUBLE, 0, _("input is too large to count"));
625 nlscan (char const *lim)
629 for (beg = lastnl; beg < lim; beg++)
631 beg = memchr (beg, eolbyte, lim - beg);
636 totalnl = add_count (totalnl, newlines);
640 /* Print the current filename. */
642 print_filename (void)
644 PR_SGR_START_IF(filename_color);
645 fputs(filename, stdout);
646 PR_SGR_END_IF(filename_color);
649 /* Print a character separator. */
653 PR_SGR_START_IF(sep_color);
655 PR_SGR_END_IF(sep_color);
658 /* Print a line number or a byte offset. */
660 print_offset (uintmax_t pos, int min_width, const char *color)
662 /* Do not rely on printf to print pos, since uintmax_t may be longer
663 than long, and long long is not portable. */
665 char buf[sizeof pos * CHAR_BIT];
666 char *p = buf + sizeof buf;
670 *--p = '0' + pos % 10;
673 while ((pos /= 10) != 0);
675 /* Do this to maximize the probability of alignment across lines. */
677 while (--min_width >= 0)
680 PR_SGR_START_IF(color);
681 fwrite (p, 1, buf + sizeof buf - p, stdout);
682 PR_SGR_END_IF(color);
685 /* Print a whole line head (filename, line, byte). */
687 print_line_head (char const *beg, char const *lim, int sep)
705 totalnl = add_count (totalnl, 1);
710 print_offset (totalnl, 4, line_num_color);
716 uintmax_t pos = add_count (totalcc, beg - bufbeg);
717 #if defined HAVE_DOS_FILE_CONTENTS
718 pos = dossified_pos (pos);
722 print_offset (pos, 6, byte_num_color);
728 /* This assumes sep is one column wide.
729 Try doing this any other way with Unicode
730 (and its combining and wide characters)
731 filenames and you're wasting your efforts. */
733 fputs("\t\b", stdout);
740 print_line_middle (const char *beg, const char *lim,
741 const char *line_color, const char *match_color)
745 const char *cur = beg;
746 const char *mid = NULL;
749 && ((match_offset = execute(beg, lim - beg, &match_size,
750 beg + (cur - beg))) != (size_t) -1))
752 char const *b = beg + match_offset;
754 /* Avoid matching the empty line at the end of the buffer. */
758 /* Avoid hanging on grep --color "" foo */
761 /* Make minimal progress; there may be further non-empty matches. */
762 /* XXX - Could really advance by one whole multi-octet character. */
769 /* This function is called on a matching line only,
770 but is it selected or rejected/context? */
772 print_line_head(b, lim, out_invert ? SEP_CHAR_REJECTED
773 : SEP_CHAR_SELECTED);
776 PR_SGR_START(line_color);
782 fwrite (cur, sizeof (char), b - cur, stdout);
785 PR_SGR_START_IF(match_color);
786 fwrite (b, sizeof (char), match_size, stdout);
787 PR_SGR_END_IF(match_color);
791 cur = b + match_size;
803 print_line_tail (const char *beg, const char *lim, const char *line_color)
808 eol_size = (lim > beg && lim[-1] == eolbyte);
809 eol_size += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r');
810 tail_size = lim - eol_size - beg;
814 PR_SGR_START(line_color);
815 fwrite(beg, 1, tail_size, stdout);
817 PR_SGR_END(line_color);
824 prline (char const *beg, char const *lim, int sep)
827 const char *line_color;
828 const char *match_color;
831 print_line_head(beg, lim, sep);
833 matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert;
837 line_color = ( (sep == SEP_CHAR_SELECTED)
838 ^ (out_invert && (color_option < 0)))
839 ? selected_line_color : context_line_color;
840 match_color = (sep == SEP_CHAR_SELECTED)
841 ? selected_match_color : context_match_color;
844 line_color = match_color = NULL; /* Shouldn't be used. */
846 if ( (only_matching && matching)
847 || (color_option && (*line_color || *match_color)))
849 /* We already know that non-matching lines have no match (to colorize). */
850 if (matching && (only_matching || *match_color))
851 beg = print_line_middle(beg, lim, line_color, match_color);
853 /* FIXME: this test may be removable. */
854 if (!only_matching && *line_color)
855 beg = print_line_tail(beg, lim, line_color);
858 if (!only_matching && lim > beg)
859 fwrite (beg, 1, lim - beg, stdout);
862 error (0, errno, _("writing output"));
870 /* Print pending lines of trailing context prior to LIM. Trailing context ends
871 at the next matching line when OUTLEFT is 0. */
873 prpending (char const *lim)
877 while (pending > 0 && lastout < lim)
879 char const *nl = memchr (lastout, eolbyte, lim - lastout);
883 || ((execute(lastout, nl + 1 - lastout,
884 &match_size, NULL) == (size_t) -1)
886 prline (lastout, nl + 1, SEP_CHAR_REJECTED);
892 /* Print the lines between BEG and LIM. Deal with context crap.
893 If NLINESP is non-null, store a count of lines between BEG and LIM. */
895 prtext (char const *beg, char const *lim, int *nlinesp)
897 static int used; /* avoid printing SEP_STR_GROUP before any output */
902 if (!out_quiet && pending > 0)
909 /* Deal with leading context crap. */
911 bp = lastout ? lastout : bufbeg;
912 for (i = 0; i < out_before; ++i)
916 while (p[-1] != eol);
918 /* We print the SEP_STR_GROUP separator only if our output is
919 discontiguous from the last output in the file. */
920 if ((out_before || out_after) && used && p != lastout && group_separator)
922 PR_SGR_START_IF(sep_color);
923 fputs (group_separator, stdout);
924 PR_SGR_END_IF(sep_color);
930 char const *nl = memchr (p, eol, beg - p);
932 prline (p, nl, SEP_CHAR_REJECTED);
939 /* Caller wants a line count. */
940 for (n = 0; p < lim && n < outleft; n++)
942 char const *nl = memchr (p, eol, lim - p);
945 prline (p, nl, SEP_CHAR_SELECTED);
950 /* relying on it that this function is never called when outleft = 0. */
951 after_last_match = bufoffset - (buflim - p);
955 prline (beg, lim, SEP_CHAR_SELECTED);
957 pending = out_quiet ? 0 : out_after;
962 do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr)
965 const char *line_next;
967 /* With the current implementation, using --ignore-case with a multi-byte
968 character set is very inefficient when applied to a large buffer
969 containing many matches. We can avoid much of the wasted effort
970 by matching line-by-line.
972 FIXME: this is just an ugly workaround, and it doesn't really
973 belong here. Also, PCRE is always using this same per-line
974 matching algorithm. Either we fix -i, or we should refactor
975 this code---for example, we could add another function pointer
976 to struct matcher to split the buffer passed to execute. It would
977 perform the memchr if line-by-line matching is necessary, or just
978 return buf + size otherwise. */
979 if (MB_CUR_MAX == 1 || !match_icase)
980 return execute(buf, size, match_size, start_ptr);
982 for (line_next = buf; line_next < buf + size; )
984 const char *line_buf = line_next;
985 const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf);
986 if (line_end == NULL)
987 line_next = line_end = buf + size;
989 line_next = line_end + 1;
991 if (start_ptr && start_ptr >= line_end)
994 result = execute (line_buf, line_next - line_buf, match_size, start_ptr);
995 if (result != (size_t) -1)
996 return (line_buf - buf) + result;
1002 /* Scan the specified portion of the buffer, matching lines (or
1003 between matching lines if OUT_INVERT is true). Return a count of
1006 grepbuf (char const *beg, char const *lim)
1010 size_t match_offset;
1015 while ((match_offset = do_execute(p, lim - p, &match_size,
1016 NULL)) != (size_t) -1)
1018 char const *b = p + match_offset;
1019 char const *endp = b + match_size;
1020 /* Avoid matching the empty line at the end of the buffer. */
1025 prtext (b, endp, (int *) 0);
1028 if (!outleft || done_on_match)
1031 exit (EXIT_SUCCESS);
1032 after_last_match = bufoffset - (buflim - endp);
1046 if (out_invert && p < lim)
1048 prtext (p, lim, &n);
1055 /* Search a given file. Normally, return a count of lines printed;
1056 but if the file is a directory and we search it recursively, then
1057 return -2 if there was a match, and -1 otherwise. */
1059 grep (int fd, char const *file, struct stats *stats)
1063 size_t residue, save;
1069 if (!reset (fd, file, stats))
1072 if (file && directories == RECURSE_DIRECTORIES
1073 && S_ISDIR (stats->stat.st_mode))
1075 /* Close fd now, so that we don't open a lot of file descriptors
1076 when we recurse deeply. */
1077 if (close (fd) != 0)
1078 error (0, errno, "%s", file);
1079 return grepdir (file, stats) - 2;
1085 outleft = max_count;
1086 after_last_match = 0;
1093 if (! fillbuf (save, stats))
1095 if (! is_EISDIR (errno, file))
1097 if (errno != EINVAL)
1098 suppressible_error (filename, errno);
1103 not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)
1104 || binary_files == WITHOUT_MATCH_BINARY_FILES)
1105 && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg));
1106 if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)
1108 done_on_match += not_text;
1109 out_quiet += not_text;
1117 beg = bufbeg + save;
1119 /* no more data to scan (eof) except for maybe a residue -> break */
1123 /* Determine new residue (the length of an incomplete line at the end of
1124 the buffer, 0 means there is no incomplete last line). */
1127 for (lim = buflim; lim[-1] != eol; lim--)
1131 lim = beg - residue;
1133 residue = buflim - lim;
1138 nlines += grepbuf (beg, lim);
1141 if((!outleft && !pending) || (nlines && done_on_match && !out_invert))
1145 /* The last OUT_BEFORE lines at the end of the buffer will be needed as
1146 leading context if there is a matching line at the begin of the
1147 next data. Make beg point to their begin. */
1150 while (i < out_before && beg > bufbeg && beg != lastout)
1155 while (beg[-1] != eol);
1158 /* detect if leading context is discontinuous from last printed line. */
1162 /* Handle some details and read more data to scan. */
1163 save = residue + lim - beg;
1165 totalcc = add_count (totalcc, buflim - bufbeg - save);
1168 if (! fillbuf (save, stats))
1170 if (! is_EISDIR (errno, file))
1171 suppressible_error (filename, errno);
1179 nlines += grepbuf (bufbeg + save - residue, buflim);
1185 done_on_match -= not_text;
1186 out_quiet -= not_text;
1187 if ((not_text & ~out_quiet) && nlines != 0)
1188 printf (_("Binary file %s matches\n"), filename);
1193 grepfile (char const *file, struct stats *stats)
1202 filename = label ? label : _("(standard input)");
1206 if (stat (file, &stats->stat) != 0)
1208 suppressible_error (file, errno);
1211 if (directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode))
1213 if (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode)
1214 || S_ISBLK (stats->stat.st_mode)
1215 || S_ISSOCK (stats->stat.st_mode)
1216 || S_ISFIFO (stats->stat.st_mode)))
1218 while ((desc = open (file, O_RDONLY)) < 0 && errno == EINTR)
1225 if (is_EISDIR (e, file) && directories == RECURSE_DIRECTORIES)
1227 if (stat (file, &stats->stat) != 0)
1229 error (0, errno, "%s", file);
1233 return grepdir (file, stats);
1236 if (!suppress_errors)
1238 if (directories == SKIP_DIRECTORIES)
1246 /* When skipping directories, don't worry about
1247 directories that can't be opened. */
1254 suppressible_error (file, e);
1261 #if defined SET_BINARY
1262 /* Set input to binary mode. Pipes are simulated with files
1263 on DOS, so this includes the case of "foo | grep bar". */
1268 count = grep (desc, file, stats);
1279 print_sep(SEP_CHAR_SELECTED);
1283 printf ("%d\n", count);
1287 if (list_files == 1 - 2 * status)
1290 fputc('\n' & filename_mask, stdout);
1295 off_t required_offset = outleft ? bufoffset : after_last_match;
1296 if (required_offset != bufoffset
1297 && lseek (desc, required_offset, SEEK_SET) < 0
1298 && S_ISREG (stats->stat.st_mode))
1299 error (0, errno, "%s", filename);
1302 while (close (desc) != 0)
1305 error (0, errno, "%s", file);
1314 grepdir (char const *dir, struct stats const *stats)
1316 struct stats const *ancestor;
1319 if ( excluded_directory_patterns &&
1320 excluded_file_name (excluded_directory_patterns, dir) ) {
1325 /* Mingw32 does not support st_ino. No known working hosts use zero
1326 for st_ino, so assume that the Mingw32 bug applies if it's zero. */
1327 if (stats->stat.st_ino)
1328 for (ancestor = stats; (ancestor = ancestor->parent) != 0; )
1329 if (ancestor->stat.st_ino == stats->stat.st_ino
1330 && ancestor->stat.st_dev == stats->stat.st_dev)
1332 if (!suppress_errors)
1333 error (0, 0, _("warning: %s: %s"), dir,
1334 _("recursive directory loop"));
1338 name_space = savedir (dir, stats->stat.st_size, included_patterns,
1339 excluded_patterns, excluded_directory_patterns);
1344 suppressible_error (dir, errno);
1350 size_t dirlen = strlen (dir);
1351 int needs_slash = ! (dirlen == FILE_SYSTEM_PREFIX_LEN (dir)
1352 || ISSLASH (dir[dirlen - 1]));
1354 char const *namep = name_space;
1356 child.parent = stats;
1357 out_file += !no_filenames;
1360 size_t namelen = strlen (namep);
1361 file = xrealloc (file, dirlen + 1 + namelen + 1);
1364 strcpy (file + dirlen + needs_slash, namep);
1365 namep += namelen + 1;
1366 status &= grepfile (file, &child);
1368 out_file -= !no_filenames;
1376 void usage (int status) __attribute__ ((noreturn));
1382 fprintf (stderr, _("Usage: %s [OPTION]... PATTERN [FILE]...\n"),
1384 fprintf (stderr, _("Try `%s --help' for more information.\n"),
1389 printf (_("Usage: %s [OPTION]... PATTERN [FILE]...\n"), program_name);
1391 Search for PATTERN in each FILE or standard input.\n"));
1392 printf ("%s", gettext (before_options));
1394 Example: %s -i 'hello world' menu.h main.c\n\
1396 Regexp selection and interpretation:\n"), program_name);
1397 if (matchers[1].name)
1399 -E, --extended-regexp PATTERN is an extended regular expression (ERE)\n\
1400 -F, --fixed-strings PATTERN is a set of newline-separated fixed strings\n\
1401 -G, --basic-regexp PATTERN is a basic regular expression (BRE)\n\
1402 -P, --perl-regexp PATTERN is a Perl regular expression\n"));
1403 /* -X is undocumented on purpose. */
1405 -e, --regexp=PATTERN use PATTERN for matching\n\
1406 -f, --file=FILE obtain PATTERN from FILE\n\
1407 -i, --ignore-case ignore case distinctions\n\
1408 -w, --word-regexp force PATTERN to match only whole words\n\
1409 -x, --line-regexp force PATTERN to match only whole lines\n\
1410 -z, --null-data a data line ends in 0 byte, not newline\n"));
1414 -s, --no-messages suppress error messages\n\
1415 -v, --invert-match select non-matching lines\n\
1416 -V, --version print version information and exit\n\
1417 --help display this help and exit\n\
1418 --mmap ignored for backwards compatibility\n"));
1422 -m, --max-count=NUM stop after NUM matches\n\
1423 -b, --byte-offset print the byte offset with output lines\n\
1424 -n, --line-number print line number with output lines\n\
1425 --line-buffered flush output on every line\n\
1426 -H, --with-filename print the filename for each match\n\
1427 -h, --no-filename suppress the prefixing filename on output\n\
1428 --label=LABEL print LABEL as filename for standard input\n\
1431 -o, --only-matching show only the part of a line matching PATTERN\n\
1432 -q, --quiet, --silent suppress all normal output\n\
1433 --binary-files=TYPE assume that binary files are TYPE;\n\
1434 TYPE is `binary', `text', or `without-match'\n\
1435 -a, --text equivalent to --binary-files=text\n\
1438 -I equivalent to --binary-files=without-match\n\
1439 -d, --directories=ACTION how to handle directories;\n\
1440 ACTION is `read', `recurse', or `skip'\n\
1441 -D, --devices=ACTION how to handle devices, FIFOs and sockets;\n\
1442 ACTION is `read' or `skip'\n\
1443 -R, -r, --recursive equivalent to --directories=recurse\n\
1446 --include=FILE_PATTERN search only files that match FILE_PATTERN\n\
1447 --exclude=FILE_PATTERN skip files and directories matching FILE_PATTERN\n\
1448 --exclude-from=FILE skip files matching any file pattern from FILE\n\
1449 --exclude-dir=PATTERN directories that match PATTERN will be skipped.\n\
1452 -L, --files-without-match print only names of FILEs containing no match\n\
1453 -l, --files-with-matches print only names of FILEs containing matches\n\
1454 -c, --count print only a count of matching lines per FILE\n\
1455 -T, --initial-tab make tabs line up (if needed)\n\
1456 -Z, --null print 0 byte after FILE name\n"));
1460 -B, --before-context=NUM print NUM lines of leading context\n\
1461 -A, --after-context=NUM print NUM lines of trailing context\n\
1462 -C, --context=NUM print NUM lines of output context\n\
1465 -NUM same as --context=NUM\n\
1467 --colour[=WHEN] use markers to highlight the matching strings;\n\
1468 WHEN is `always', `never', or `auto'\n\
1469 -U, --binary do not strip CR characters at EOL (MSDOS)\n\
1470 -u, --unix-byte-offsets report offsets as if CRs were not there (MSDOS)\n\
1472 printf ("%s", _(after_options));
1474 With no FILE, or when FILE is -, read standard input. If less than two FILEs\n\
1475 are given, assume -h. Exit status is 0 if any line was selected, 1 otherwise;\n\
1476 if any error occurs and -q was not given, the exit status is 2.\n"));
1477 printf (_("\nReport bugs to: %s\n"), PACKAGE_BUGREPORT);
1478 printf (_("GNU Grep home page: <%s>\n"),
1479 "http://www.gnu.org/software/grep/");
1480 fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
1487 /* If M is NULL, initialize the matcher to the default. Otherwise set the
1488 matcher to M if available. Exit in case of conflicts or if M is not
1491 setmatcher (char const *m)
1493 static char const *matcher;
1498 compile = matchers[0].compile;
1499 execute = matchers[0].execute;
1500 if (!matchers[1].name)
1501 matcher = matchers[0].name;
1506 if (matcher && STREQ (matcher, m))
1509 else if (!matchers[1].name)
1510 error (EXIT_TROUBLE, 0, _("%s can only use the %s pattern syntax"),
1511 program_name, matcher);
1513 error (EXIT_TROUBLE, 0, _("conflicting matchers specified"));
1518 for (i = 0; matchers[i].name; i++)
1519 if (STREQ (m, matchers[i].name))
1521 compile = matchers[i].compile;
1522 execute = matchers[i].execute;
1527 error (EXIT_TROUBLE, 0, _("invalid matcher %s"), m);
1534 #if defined HAVE_SETRLIMIT && defined RLIMIT_STACK
1537 /* I think every platform needs to do this, so that regex.c
1538 doesn't oveflow the stack. The default value of
1539 `re_max_failures' is too large for some platforms: it needs
1540 more than 3MB-large stack.
1542 The test for HAVE_SETRLIMIT should go into `configure'. */
1543 if (!getrlimit (RLIMIT_STACK, &rlim))
1546 extern long int re_max_failures; /* from regex.c */
1548 /* Approximate the amount regex.c needs, plus some more. */
1549 newlim = re_max_failures * 2 * 20 * sizeof (char *);
1550 if (newlim > rlim.rlim_max)
1552 newlim = rlim.rlim_max;
1553 re_max_failures = newlim / (2 * 20 * sizeof (char *));
1555 if (rlim.rlim_cur < newlim)
1557 rlim.rlim_cur = newlim;
1558 setrlimit (RLIMIT_STACK, &rlim);
1564 /* Find the white-space-separated options specified by OPTIONS, and
1565 using BUF to store copies of these options, set ARGV[0], ARGV[1],
1566 etc. to the option copies. Return the number N of options found.
1567 Do not set ARGV[N] to NULL. If ARGV is NULL, do not store ARGV[0]
1568 etc. Backslash can be used to escape whitespace (and backslashes). */
1570 prepend_args (char const *options, char *buf, char **argv)
1572 char const *o = options;
1578 while (c_isspace ((unsigned char) *o))
1587 if ((*b++ = *o++) == '\\' && *o)
1589 while (*o && ! c_isspace ((unsigned char) *o));
1595 /* Prepend the whitespace-separated options in OPTIONS to the argument
1596 vector of a main program with argument count *PARGC and argument
1599 prepend_default_options (char const *options, int *pargc, char ***pargv)
1601 if (options && *options)
1603 char *buf = xmalloc (strlen (options) + 1);
1604 int prepended = prepend_args (options, buf, (char **) NULL);
1606 char * const *argv = *pargv;
1607 char **pp = xmalloc ((prepended + argc + 1) * sizeof *pp);
1608 *pargc = prepended + argc;
1611 pp += prepend_args (options, buf, pp);
1612 while ((*pp++ = *argv++))
1617 /* Get the next non-digit option from ARGC and ARGV.
1618 Return -1 if there are no more options.
1619 Process any digit options that were encountered on the way,
1620 and store the resulting integer into *DEFAULT_CONTEXT. */
1622 get_nondigit_option (int argc, char *const *argv, int *default_context)
1624 static int prev_digit_optind = -1;
1625 int opt, this_digit_optind, was_digit;
1626 char buf[sizeof (uintmax_t) * CHAR_BIT + 4];
1630 this_digit_optind = optind;
1631 while (opt = getopt_long (argc, (char **) argv, short_options, long_options,
1633 '0' <= opt && opt <= '9')
1635 if (prev_digit_optind != this_digit_optind || !was_digit)
1637 /* Reset to start another context length argument. */
1642 /* Suppress trivial leading zeros, to avoid incorrect
1643 diagnostic on strings like 00000000000. */
1647 if (p == buf + sizeof buf - 4)
1649 /* Too many digits. Append "..." to make context_length_arg
1650 complain about "X...", where X contains the digits seen
1659 prev_digit_optind = this_digit_optind;
1660 this_digit_optind = optind;
1665 context_length_arg (buf, default_context);
1671 /* Parse GREP_COLORS. The default would look like:
1672 GREP_COLORS='ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36'
1673 with boolean capabilities (ne and rv) unset (i.e., omitted).
1674 No character escaping is needed or supported. */
1676 parse_grep_colors (void)
1683 p = getenv("GREP_COLORS"); /* Plural! */
1684 if (p == NULL || *p == '\0')
1687 /* Work off a writable copy. */
1688 q = xmalloc(strlen(p) + 1);
1695 /* From now on, be well-formed or you're gone. */
1697 if (*q == ':' || *q == '\0')
1700 struct color_cap *cap;
1702 *q++ = '\0'; /* Terminate name or val. */
1703 /* Empty name without val (empty cap)
1704 * won't match and will be ignored. */
1705 for (cap = color_dict; cap->name; cap++)
1706 if (STREQ (cap->name, name))
1708 /* If name unknown, go on for forward compatibility. */
1716 error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1717 "needs a value (\"=...\"); skipped"), p, name);
1720 error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1721 "is boolean and cannot take a value (\"=%s\"); skipped"),
1726 const char *err_str = cap->fct();
1729 error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity %s"),
1739 if (q == name || val)
1741 *q++ = '\0'; /* Terminate name. */
1742 val = q; /* Can be the empty string. */
1744 else if (val == NULL)
1745 q++; /* Accumulate name. */
1746 else if (*q == ';' || (*q >= '0' && *q <= '9'))
1747 q++; /* Accumulate val. Protect the terminal from being sent crap. */
1752 error(0, 0, _("stopped processing of ill-formed GREP_COLORS=\"%s\" "
1753 "at remaining substring \"%s\""), p, q);
1757 main (int argc, char **argv)
1760 size_t keycc, oldcc, keyalloc;
1762 int opt, cc, status;
1763 int default_context;
1766 initialize_main (&argc, &argv);
1767 set_program_name (argv[0]);
1768 program_name = argv[0];
1776 max_count = TYPE_MAXIMUM (off_t);
1778 /* The value -1 means to use DEFAULT_CONTEXT. */
1779 out_after = out_before = -1;
1780 /* Default before/after context: chaged by -C/-NUM options */
1781 default_context = 0;
1782 /* Changed by -o option */
1785 /* Internationalization. */
1786 #if defined HAVE_SETLOCALE
1787 setlocale (LC_ALL, "");
1789 #if defined ENABLE_NLS
1790 bindtextdomain (PACKAGE, LOCALEDIR);
1791 textdomain (PACKAGE);
1794 exit_failure = EXIT_TROUBLE;
1795 atexit (close_stdout);
1797 prepend_default_options (getenv ("GREP_OPTIONS"), &argc, &argv);
1800 while ((opt = get_nondigit_option (argc, argv, &default_context)) != -1)
1804 context_length_arg (optarg, &out_after);
1808 context_length_arg (optarg, &out_before);
1812 /* Set output match context, but let any explicit leading or
1813 trailing amount specified with -A or -B stand. */
1814 context_length_arg (optarg, &default_context);
1818 if (STREQ (optarg, "read"))
1819 devices = READ_DEVICES;
1820 else if (STREQ (optarg, "skip"))
1821 devices = SKIP_DEVICES;
1823 error (EXIT_TROUBLE, 0, _("unknown devices method"));
1827 setmatcher ("egrep");
1831 setmatcher ("fgrep");
1835 setmatcher ("perl");
1839 setmatcher ("grep");
1842 case 'X': /* undocumented on purpose */
1843 setmatcher (optarg);
1852 binary_files = WITHOUT_MATCH_BINARY_FILES;
1860 #if defined HAVE_DOS_FILE_CONTENTS
1861 dos_use_file_type = DOS_BINARY;
1866 #if defined HAVE_DOS_FILE_CONTENTS
1867 dos_report_unix_offset = 1;
1876 binary_files = TEXT_BINARY_FILES;
1888 directories = XARGMATCH ("--directories", optarg,
1889 directories_args, directories_types);
1893 cc = strlen (optarg);
1894 keys = xrealloc (keys, keycc + cc + 1);
1895 strcpy (&keys[keycc], optarg);
1897 keys[keycc++] = '\n';
1901 fp = STREQ (optarg, "-") ? stdin : fopen (optarg, "r");
1903 error (EXIT_TROUBLE, errno, "%s", optarg);
1904 for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
1906 keys = xrealloc (keys, keyalloc);
1909 && (cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) > 0)
1912 if (keycc == keyalloc - 1)
1913 keys = xrealloc (keys, keyalloc *= 2);
1917 /* Append final newline if file ended in non-newline. */
1918 if (oldcc != keycc && keys[keycc - 1] != '\n')
1919 keys[keycc++] = '\n';
1928 case 'y': /* For old-timers . . . */
1933 /* Like -l, except list files that don't contain matches.
1934 Inspired by the same option in Hume's gre. */
1945 switch (xstrtoumax (optarg, 0, 10, &value, ""))
1949 if (0 <= max_count && max_count == value)
1952 case LONGINT_OVERFLOW:
1953 max_count = TYPE_MAXIMUM (off_t);
1957 error (EXIT_TROUBLE, 0, _("invalid max count"));
1977 directories = RECURSE_DIRECTORIES;
1981 suppress_errors = 1;
2004 case BINARY_FILES_OPTION:
2005 if (STREQ (optarg, "binary"))
2006 binary_files = BINARY_BINARY_FILES;
2007 else if (STREQ (optarg, "text"))
2008 binary_files = TEXT_BINARY_FILES;
2009 else if (STREQ (optarg, "without-match"))
2010 binary_files = WITHOUT_MATCH_BINARY_FILES;
2012 error (EXIT_TROUBLE, 0, _("unknown binary-files type"));
2017 if(!strcasecmp(optarg, "always") || !strcasecmp(optarg, "yes") ||
2018 !strcasecmp(optarg, "force"))
2020 else if(!strcasecmp(optarg, "never") || !strcasecmp(optarg, "no") ||
2021 !strcasecmp(optarg, "none"))
2023 else if(!strcasecmp(optarg, "auto") || !strcasecmp(optarg, "tty") ||
2024 !strcasecmp(optarg, "if-tty"))
2030 if (color_option == 2)
2033 if (isatty (STDOUT_FILENO) && (t = getenv ("TERM"))
2034 && !STREQ (t, "dumb"))
2041 case EXCLUDE_OPTION:
2042 if (!excluded_patterns)
2043 excluded_patterns = new_exclude ();
2044 add_exclude (excluded_patterns, optarg, EXCLUDE_WILDCARDS);
2046 case EXCLUDE_FROM_OPTION:
2047 if (!excluded_patterns)
2048 excluded_patterns = new_exclude ();
2049 if (add_exclude_file (add_exclude, excluded_patterns, optarg,
2050 EXCLUDE_WILDCARDS, '\n') != 0)
2052 error (EXIT_TROUBLE, errno, "%s", optarg);
2056 case EXCLUDE_DIRECTORY_OPTION:
2057 if (!excluded_directory_patterns)
2058 excluded_directory_patterns = new_exclude ();
2059 add_exclude (excluded_directory_patterns, optarg, EXCLUDE_WILDCARDS);
2062 case INCLUDE_OPTION:
2063 if (!included_patterns)
2064 included_patterns = new_exclude ();
2065 add_exclude (included_patterns, optarg,
2066 EXCLUDE_WILDCARDS | EXCLUDE_INCLUDE);
2069 case GROUP_SEPARATOR_OPTION:
2070 group_separator = optarg;
2073 case LINE_BUFFERED_OPTION:
2087 usage (EXIT_TROUBLE);
2092 /* POSIX.2 says that -q overrides -l, which in turn overrides the
2093 other output options. */
2096 if (exit_on_match | list_files)
2101 out_quiet = count_matches | done_on_match;
2104 out_after = default_context;
2106 out_before = default_context;
2111 char *userval = getenv ("GREP_COLOR");
2112 if (userval != NULL && *userval != '\0')
2113 selected_match_color = context_match_color = userval;
2115 /* New GREP_COLORS has priority. */
2116 parse_grep_colors();
2121 version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, \
2123 exit (EXIT_SUCCESS); \
2127 usage (EXIT_SUCCESS);
2133 /* No keys were specified (e.g. -f /dev/null). Match nothing. */
2135 match_lines = match_words = 0;
2138 /* Strip trailing newline. */
2144 /* A copy must be made in case of an xrealloc() or free() later. */
2145 keycc = strlen(argv[optind]);
2146 keys = xmalloc(keycc + 1);
2147 strcpy(keys, argv[optind++]);
2150 usage (EXIT_TROUBLE);
2153 compile(keys, keycc);
2156 if ((argc - optind > 1 && !no_filenames) || with_filenames)
2160 /* Output is set to binary mode because we shouldn't convert
2161 NL to CR-LF pairs, especially when grepping binary files. */
2167 exit (EXIT_FAILURE);
2174 char *file = argv[optind];
2175 if ((included_patterns || excluded_patterns)
2178 if (included_patterns
2179 && excluded_file_name (included_patterns, file))
2181 if (excluded_patterns
2182 && excluded_file_name (excluded_patterns, file))
2185 status &= grepfile (STREQ (file, "-") ? (char *) NULL : file,
2188 while ( ++optind < argc);
2191 status = grepfile ((char *) NULL, &stats_base);
2193 /* We register via atexit() to test stdout. */
2194 exit (errseen ? EXIT_TROUBLE : status);
2196 /* vim:set shiftwidth=2: */