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 <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))
1096 suppressible_error (filename, errno);
1100 not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)
1101 || binary_files == WITHOUT_MATCH_BINARY_FILES)
1102 && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg));
1103 if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)
1105 done_on_match += not_text;
1106 out_quiet += not_text;
1114 beg = bufbeg + save;
1116 /* no more data to scan (eof) except for maybe a residue -> break */
1120 /* Determine new residue (the length of an incomplete line at the end of
1121 the buffer, 0 means there is no incomplete last line). */
1124 for (lim = buflim; lim[-1] != eol; lim--)
1128 lim = beg - residue;
1130 residue = buflim - lim;
1135 nlines += grepbuf (beg, lim);
1138 if((!outleft && !pending) || (nlines && done_on_match && !out_invert))
1142 /* The last OUT_BEFORE lines at the end of the buffer will be needed as
1143 leading context if there is a matching line at the begin of the
1144 next data. Make beg point to their begin. */
1147 while (i < out_before && beg > bufbeg && beg != lastout)
1152 while (beg[-1] != eol);
1155 /* detect if leading context is discontinuous from last printed line. */
1159 /* Handle some details and read more data to scan. */
1160 save = residue + lim - beg;
1162 totalcc = add_count (totalcc, buflim - bufbeg - save);
1165 if (! fillbuf (save, stats))
1167 if (! is_EISDIR (errno, file))
1168 suppressible_error (filename, errno);
1176 nlines += grepbuf (bufbeg + save - residue, buflim);
1182 done_on_match -= not_text;
1183 out_quiet -= not_text;
1184 if ((not_text & ~out_quiet) && nlines != 0)
1185 printf (_("Binary file %s matches\n"), filename);
1190 grepfile (char const *file, struct stats *stats)
1199 filename = label ? label : _("(standard input)");
1203 if (stat (file, &stats->stat) != 0)
1205 suppressible_error (file, errno);
1208 if (directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode))
1210 if (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode)
1211 || S_ISBLK (stats->stat.st_mode)
1212 || S_ISSOCK (stats->stat.st_mode)
1213 || S_ISFIFO (stats->stat.st_mode)))
1215 while ((desc = open (file, O_RDONLY)) < 0 && errno == EINTR)
1222 if (is_EISDIR (e, file) && directories == RECURSE_DIRECTORIES)
1224 if (stat (file, &stats->stat) != 0)
1226 error (0, errno, "%s", file);
1230 return grepdir (file, stats);
1233 if (!suppress_errors)
1235 if (directories == SKIP_DIRECTORIES)
1243 /* When skipping directories, don't worry about
1244 directories that can't be opened. */
1251 suppressible_error (file, e);
1258 #if defined SET_BINARY
1259 /* Set input to binary mode. Pipes are simulated with files
1260 on DOS, so this includes the case of "foo | grep bar". */
1265 count = grep (desc, file, stats);
1276 print_sep(SEP_CHAR_SELECTED);
1280 printf ("%d\n", count);
1284 if (list_files == 1 - 2 * status)
1287 fputc('\n' & filename_mask, stdout);
1292 off_t required_offset = outleft ? bufoffset : after_last_match;
1293 if (required_offset != bufoffset
1294 && lseek (desc, required_offset, SEEK_SET) < 0
1295 && S_ISREG (stats->stat.st_mode))
1296 error (0, errno, "%s", filename);
1299 while (close (desc) != 0)
1302 error (0, errno, "%s", file);
1311 grepdir (char const *dir, struct stats const *stats)
1313 struct stats const *ancestor;
1316 if ( excluded_directory_patterns &&
1317 excluded_file_name (excluded_directory_patterns, dir) ) {
1322 /* Mingw32 does not support st_ino. No known working hosts use zero
1323 for st_ino, so assume that the Mingw32 bug applies if it's zero. */
1324 if (stats->stat.st_ino)
1325 for (ancestor = stats; (ancestor = ancestor->parent) != 0; )
1326 if (ancestor->stat.st_ino == stats->stat.st_ino
1327 && ancestor->stat.st_dev == stats->stat.st_dev)
1329 if (!suppress_errors)
1330 error (0, 0, _("warning: %s: %s"), dir,
1331 _("recursive directory loop"));
1335 name_space = savedir (dir, stats->stat.st_size, included_patterns,
1336 excluded_patterns, excluded_directory_patterns);
1341 suppressible_error (dir, errno);
1347 size_t dirlen = strlen (dir);
1348 int needs_slash = ! (dirlen == FILE_SYSTEM_PREFIX_LEN (dir)
1349 || ISSLASH (dir[dirlen - 1]));
1351 char const *namep = name_space;
1353 child.parent = stats;
1354 out_file += !no_filenames;
1357 size_t namelen = strlen (namep);
1358 file = xrealloc (file, dirlen + 1 + namelen + 1);
1361 strcpy (file + dirlen + needs_slash, namep);
1362 namep += namelen + 1;
1363 status &= grepfile (file, &child);
1365 out_file -= !no_filenames;
1373 void usage (int status) __attribute__ ((noreturn));
1379 fprintf (stderr, _("Usage: %s [OPTION]... PATTERN [FILE]...\n"),
1381 fprintf (stderr, _("Try `%s --help' for more information.\n"),
1386 printf (_("Usage: %s [OPTION]... PATTERN [FILE]...\n"), program_name);
1388 Search for PATTERN in each FILE or standard input.\n"));
1389 printf ("%s", gettext (before_options));
1391 Example: %s -i 'hello world' menu.h main.c\n\
1393 Regexp selection and interpretation:\n"), program_name);
1394 if (matchers[1].name)
1396 -E, --extended-regexp PATTERN is an extended regular expression (ERE)\n\
1397 -F, --fixed-strings PATTERN is a set of newline-separated fixed strings\n\
1398 -G, --basic-regexp PATTERN is a basic regular expression (BRE)\n\
1399 -P, --perl-regexp PATTERN is a Perl regular expression\n"));
1400 /* -X is undocumented on purpose. */
1402 -e, --regexp=PATTERN use PATTERN for matching\n\
1403 -f, --file=FILE obtain PATTERN from FILE\n\
1404 -i, --ignore-case ignore case distinctions\n\
1405 -w, --word-regexp force PATTERN to match only whole words\n\
1406 -x, --line-regexp force PATTERN to match only whole lines\n\
1407 -z, --null-data a data line ends in 0 byte, not newline\n"));
1411 -s, --no-messages suppress error messages\n\
1412 -v, --invert-match select non-matching lines\n\
1413 -V, --version print version information and exit\n\
1414 --help display this help and exit\n\
1415 --mmap ignored for backwards compatibility\n"));
1419 -m, --max-count=NUM stop after NUM matches\n\
1420 -b, --byte-offset print the byte offset with output lines\n\
1421 -n, --line-number print line number with output lines\n\
1422 --line-buffered flush output on every line\n\
1423 -H, --with-filename print the filename for each match\n\
1424 -h, --no-filename suppress the prefixing filename on output\n\
1425 --label=LABEL print LABEL as filename for standard input\n\
1428 -o, --only-matching show only the part of a line matching PATTERN\n\
1429 -q, --quiet, --silent suppress all normal output\n\
1430 --binary-files=TYPE assume that binary files are TYPE;\n\
1431 TYPE is `binary', `text', or `without-match'\n\
1432 -a, --text equivalent to --binary-files=text\n\
1435 -I equivalent to --binary-files=without-match\n\
1436 -d, --directories=ACTION how to handle directories;\n\
1437 ACTION is `read', `recurse', or `skip'\n\
1438 -D, --devices=ACTION how to handle devices, FIFOs and sockets;\n\
1439 ACTION is `read' or `skip'\n\
1440 -R, -r, --recursive equivalent to --directories=recurse\n\
1443 --include=FILE_PATTERN search only files that match FILE_PATTERN\n\
1444 --exclude=FILE_PATTERN skip files and directories matching FILE_PATTERN\n\
1445 --exclude-from=FILE skip files matching any file pattern from FILE\n\
1446 --exclude-dir=PATTERN directories that match PATTERN will be skipped.\n\
1449 -L, --files-without-match print only names of FILEs containing no match\n\
1450 -l, --files-with-matches print only names of FILEs containing matches\n\
1451 -c, --count print only a count of matching lines per FILE\n\
1452 -T, --initial-tab make tabs line up (if needed)\n\
1453 -Z, --null print 0 byte after FILE name\n"));
1457 -B, --before-context=NUM print NUM lines of leading context\n\
1458 -A, --after-context=NUM print NUM lines of trailing context\n\
1459 -C, --context=NUM print NUM lines of output context\n\
1462 -NUM same as --context=NUM\n\
1464 --colour[=WHEN] use markers to highlight the matching strings;\n\
1465 WHEN is `always', `never', or `auto'\n\
1466 -U, --binary do not strip CR characters at EOL (MSDOS)\n\
1467 -u, --unix-byte-offsets report offsets as if CRs were not there (MSDOS)\n\
1469 printf ("%s", _(after_options));
1471 With no FILE, or when FILE is -, read standard input. If less than two FILEs\n\
1472 are given, assume -h. Exit status is 0 if any line was selected, 1 otherwise;\n\
1473 if any error occurs and -q was not given, the exit status is 2.\n"));
1474 printf (_("\nReport bugs to: %s\n"), PACKAGE_BUGREPORT);
1475 printf (_("GNU Grep home page: <%s>\n"),
1476 "http://www.gnu.org/software/grep/");
1477 fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
1484 /* If M is NULL, initialize the matcher to the default. Otherwise set the
1485 matcher to M if available. Exit in case of conflicts or if M is not
1488 setmatcher (char const *m)
1490 static char const *matcher;
1495 compile = matchers[0].compile;
1496 execute = matchers[0].execute;
1497 if (!matchers[1].name)
1498 matcher = matchers[0].name;
1503 if (matcher && STREQ (matcher, m))
1506 else if (!matchers[1].name)
1507 error (EXIT_TROUBLE, 0, _("%s can only use the %s pattern syntax"),
1508 program_name, matcher);
1510 error (EXIT_TROUBLE, 0, _("conflicting matchers specified"));
1515 for (i = 0; matchers[i].name; i++)
1516 if (STREQ (m, matchers[i].name))
1518 compile = matchers[i].compile;
1519 execute = matchers[i].execute;
1524 error (EXIT_TROUBLE, 0, _("invalid matcher %s"), m);
1531 #if defined HAVE_SETRLIMIT && defined RLIMIT_STACK
1534 /* I think every platform needs to do this, so that regex.c
1535 doesn't oveflow the stack. The default value of
1536 `re_max_failures' is too large for some platforms: it needs
1537 more than 3MB-large stack.
1539 The test for HAVE_SETRLIMIT should go into `configure'. */
1540 if (!getrlimit (RLIMIT_STACK, &rlim))
1543 extern long int re_max_failures; /* from regex.c */
1545 /* Approximate the amount regex.c needs, plus some more. */
1546 newlim = re_max_failures * 2 * 20 * sizeof (char *);
1547 if (newlim > rlim.rlim_max)
1549 newlim = rlim.rlim_max;
1550 re_max_failures = newlim / (2 * 20 * sizeof (char *));
1552 if (rlim.rlim_cur < newlim)
1554 rlim.rlim_cur = newlim;
1555 setrlimit (RLIMIT_STACK, &rlim);
1561 /* Find the white-space-separated options specified by OPTIONS, and
1562 using BUF to store copies of these options, set ARGV[0], ARGV[1],
1563 etc. to the option copies. Return the number N of options found.
1564 Do not set ARGV[N] to NULL. If ARGV is NULL, do not store ARGV[0]
1565 etc. Backslash can be used to escape whitespace (and backslashes). */
1567 prepend_args (char const *options, char *buf, char **argv)
1569 char const *o = options;
1575 while (c_isspace ((unsigned char) *o))
1584 if ((*b++ = *o++) == '\\' && *o)
1586 while (*o && ! c_isspace ((unsigned char) *o));
1592 /* Prepend the whitespace-separated options in OPTIONS to the argument
1593 vector of a main program with argument count *PARGC and argument
1596 prepend_default_options (char const *options, int *pargc, char ***pargv)
1598 if (options && *options)
1600 char *buf = xmalloc (strlen (options) + 1);
1601 int prepended = prepend_args (options, buf, (char **) NULL);
1603 char * const *argv = *pargv;
1604 char **pp = xmalloc ((prepended + argc + 1) * sizeof *pp);
1605 *pargc = prepended + argc;
1608 pp += prepend_args (options, buf, pp);
1609 while ((*pp++ = *argv++))
1614 /* Get the next non-digit option from ARGC and ARGV.
1615 Return -1 if there are no more options.
1616 Process any digit options that were encountered on the way,
1617 and store the resulting integer into *DEFAULT_CONTEXT. */
1619 get_nondigit_option (int argc, char *const *argv, int *default_context)
1621 static int prev_digit_optind = -1;
1622 int opt, this_digit_optind, was_digit;
1623 char buf[sizeof (uintmax_t) * CHAR_BIT + 4];
1627 this_digit_optind = optind;
1628 while (opt = getopt_long (argc, (char **) argv, short_options, long_options,
1630 '0' <= opt && opt <= '9')
1632 if (prev_digit_optind != this_digit_optind || !was_digit)
1634 /* Reset to start another context length argument. */
1639 /* Suppress trivial leading zeros, to avoid incorrect
1640 diagnostic on strings like 00000000000. */
1644 if (p == buf + sizeof buf - 4)
1646 /* Too many digits. Append "..." to make context_length_arg
1647 complain about "X...", where X contains the digits seen
1656 prev_digit_optind = this_digit_optind;
1657 this_digit_optind = optind;
1662 context_length_arg (buf, default_context);
1668 /* Parse GREP_COLORS. The default would look like:
1669 GREP_COLORS='ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36'
1670 with boolean capabilities (ne and rv) unset (i.e., omitted).
1671 No character escaping is needed or supported. */
1673 parse_grep_colors (void)
1680 p = getenv("GREP_COLORS"); /* Plural! */
1681 if (p == NULL || *p == '\0')
1684 /* Work off a writable copy. */
1685 q = xmalloc(strlen(p) + 1);
1692 /* From now on, be well-formed or you're gone. */
1694 if (*q == ':' || *q == '\0')
1697 struct color_cap *cap;
1699 *q++ = '\0'; /* Terminate name or val. */
1700 /* Empty name without val (empty cap)
1701 * won't match and will be ignored. */
1702 for (cap = color_dict; cap->name; cap++)
1703 if (STREQ (cap->name, name))
1705 /* If name unknown, go on for forward compatibility. */
1713 error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1714 "needs a value (\"=...\"); skipped"), p, name);
1717 error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1718 "is boolean and cannot take a value (\"=%s\"); skipped"),
1723 const char *err_str = cap->fct();
1726 error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity %s"),
1736 if (q == name || val)
1738 *q++ = '\0'; /* Terminate name. */
1739 val = q; /* Can be the empty string. */
1741 else if (val == NULL)
1742 q++; /* Accumulate name. */
1743 else if (*q == ';' || (*q >= '0' && *q <= '9'))
1744 q++; /* Accumulate val. Protect the terminal from being sent crap. */
1749 error(0, 0, _("stopped processing of ill-formed GREP_COLORS=\"%s\" "
1750 "at remaining substring \"%s\""), p, q);
1754 main (int argc, char **argv)
1757 size_t keycc, oldcc, keyalloc;
1759 int opt, cc, status;
1760 int default_context;
1763 initialize_main (&argc, &argv);
1764 set_program_name (argv[0]);
1765 program_name = argv[0];
1773 max_count = TYPE_MAXIMUM (off_t);
1775 /* The value -1 means to use DEFAULT_CONTEXT. */
1776 out_after = out_before = -1;
1777 /* Default before/after context: chaged by -C/-NUM options */
1778 default_context = 0;
1779 /* Changed by -o option */
1782 /* Internationalization. */
1783 #if defined HAVE_SETLOCALE
1784 setlocale (LC_ALL, "");
1786 #if defined ENABLE_NLS
1787 bindtextdomain (PACKAGE, LOCALEDIR);
1788 textdomain (PACKAGE);
1791 exit_failure = EXIT_TROUBLE;
1792 atexit (close_stdout);
1794 prepend_default_options (getenv ("GREP_OPTIONS"), &argc, &argv);
1797 while ((opt = get_nondigit_option (argc, argv, &default_context)) != -1)
1801 context_length_arg (optarg, &out_after);
1805 context_length_arg (optarg, &out_before);
1809 /* Set output match context, but let any explicit leading or
1810 trailing amount specified with -A or -B stand. */
1811 context_length_arg (optarg, &default_context);
1815 if (STREQ (optarg, "read"))
1816 devices = READ_DEVICES;
1817 else if (STREQ (optarg, "skip"))
1818 devices = SKIP_DEVICES;
1820 error (EXIT_TROUBLE, 0, _("unknown devices method"));
1824 setmatcher ("egrep");
1828 setmatcher ("fgrep");
1832 setmatcher ("perl");
1836 setmatcher ("grep");
1839 case 'X': /* undocumented on purpose */
1840 setmatcher (optarg);
1849 binary_files = WITHOUT_MATCH_BINARY_FILES;
1857 #if defined HAVE_DOS_FILE_CONTENTS
1858 dos_use_file_type = DOS_BINARY;
1863 #if defined HAVE_DOS_FILE_CONTENTS
1864 dos_report_unix_offset = 1;
1873 binary_files = TEXT_BINARY_FILES;
1885 directories = XARGMATCH ("--directories", optarg,
1886 directories_args, directories_types);
1890 cc = strlen (optarg);
1891 keys = xrealloc (keys, keycc + cc + 1);
1892 strcpy (&keys[keycc], optarg);
1894 keys[keycc++] = '\n';
1898 fp = STREQ (optarg, "-") ? stdin : fopen (optarg, "r");
1900 error (EXIT_TROUBLE, errno, "%s", optarg);
1901 for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
1903 keys = xrealloc (keys, keyalloc);
1906 && (cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) > 0)
1909 if (keycc == keyalloc - 1)
1910 keys = xrealloc (keys, keyalloc *= 2);
1914 /* Append final newline if file ended in non-newline. */
1915 if (oldcc != keycc && keys[keycc - 1] != '\n')
1916 keys[keycc++] = '\n';
1925 case 'y': /* For old-timers . . . */
1930 /* Like -l, except list files that don't contain matches.
1931 Inspired by the same option in Hume's gre. */
1942 switch (xstrtoumax (optarg, 0, 10, &value, ""))
1946 if (0 <= max_count && max_count == value)
1949 case LONGINT_OVERFLOW:
1950 max_count = TYPE_MAXIMUM (off_t);
1954 error (EXIT_TROUBLE, 0, _("invalid max count"));
1974 directories = RECURSE_DIRECTORIES;
1978 suppress_errors = 1;
2001 case BINARY_FILES_OPTION:
2002 if (STREQ (optarg, "binary"))
2003 binary_files = BINARY_BINARY_FILES;
2004 else if (STREQ (optarg, "text"))
2005 binary_files = TEXT_BINARY_FILES;
2006 else if (STREQ (optarg, "without-match"))
2007 binary_files = WITHOUT_MATCH_BINARY_FILES;
2009 error (EXIT_TROUBLE, 0, _("unknown binary-files type"));
2014 if(!strcasecmp(optarg, "always") || !strcasecmp(optarg, "yes") ||
2015 !strcasecmp(optarg, "force"))
2017 else if(!strcasecmp(optarg, "never") || !strcasecmp(optarg, "no") ||
2018 !strcasecmp(optarg, "none"))
2020 else if(!strcasecmp(optarg, "auto") || !strcasecmp(optarg, "tty") ||
2021 !strcasecmp(optarg, "if-tty"))
2027 if (color_option == 2)
2030 if (isatty (STDOUT_FILENO) && (t = getenv ("TERM"))
2031 && !STREQ (t, "dumb"))
2038 case EXCLUDE_OPTION:
2039 if (!excluded_patterns)
2040 excluded_patterns = new_exclude ();
2041 add_exclude (excluded_patterns, optarg, EXCLUDE_WILDCARDS);
2043 case EXCLUDE_FROM_OPTION:
2044 if (!excluded_patterns)
2045 excluded_patterns = new_exclude ();
2046 if (add_exclude_file (add_exclude, excluded_patterns, optarg,
2047 EXCLUDE_WILDCARDS, '\n') != 0)
2049 error (EXIT_TROUBLE, errno, "%s", optarg);
2053 case EXCLUDE_DIRECTORY_OPTION:
2054 if (!excluded_directory_patterns)
2055 excluded_directory_patterns = new_exclude ();
2056 add_exclude (excluded_directory_patterns, optarg, EXCLUDE_WILDCARDS);
2059 case INCLUDE_OPTION:
2060 if (!included_patterns)
2061 included_patterns = new_exclude ();
2062 add_exclude (included_patterns, optarg,
2063 EXCLUDE_WILDCARDS | EXCLUDE_INCLUDE);
2066 case GROUP_SEPARATOR_OPTION:
2067 group_separator = optarg;
2070 case LINE_BUFFERED_OPTION:
2084 usage (EXIT_TROUBLE);
2089 /* POSIX.2 says that -q overrides -l, which in turn overrides the
2090 other output options. */
2093 if (exit_on_match | list_files)
2098 out_quiet = count_matches | done_on_match;
2101 out_after = default_context;
2103 out_before = default_context;
2108 char *userval = getenv ("GREP_COLOR");
2109 if (userval != NULL && *userval != '\0')
2110 selected_match_color = context_match_color = userval;
2112 /* New GREP_COLORS has priority. */
2113 parse_grep_colors();
2118 version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, \
2120 exit (EXIT_SUCCESS); \
2124 usage (EXIT_SUCCESS);
2130 /* No keys were specified (e.g. -f /dev/null). Match nothing. */
2132 match_lines = match_words = 0;
2135 /* Strip trailing newline. */
2141 /* A copy must be made in case of an xrealloc() or free() later. */
2142 keycc = strlen(argv[optind]);
2143 keys = xmalloc(keycc + 1);
2144 strcpy(keys, argv[optind++]);
2147 usage (EXIT_TROUBLE);
2150 compile(keys, keycc);
2153 if ((argc - optind > 1 && !no_filenames) || with_filenames)
2157 /* Output is set to binary mode because we shouldn't convert
2158 NL to CR-LF pairs, especially when grepping binary files. */
2164 exit (EXIT_FAILURE);
2171 char *file = argv[optind];
2172 if ((included_patterns || excluded_patterns)
2175 if (included_patterns
2176 && excluded_file_name (included_patterns, file))
2178 if (excluded_patterns
2179 && excluded_file_name (excluded_patterns, file))
2182 status &= grepfile (STREQ (file, "-") ? (char *) NULL : file,
2185 while ( ++optind < argc);
2188 status = grepfile ((char *) NULL, &stats_base);
2190 /* We register via atexit() to test stdout. */
2191 exit (errseen ? EXIT_TROUBLE : status);
2193 /* vim:set shiftwidth=2: */