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:EFGHIOPTUVX: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-files", no_argument, NULL, 'O'},
335 {"only-matching", no_argument, NULL, 'o'},
336 {"quiet", no_argument, NULL, 'q'},
337 {"recursive", no_argument, NULL, 'r'},
338 {"recursive", no_argument, NULL, 'R'},
339 {"regexp", required_argument, NULL, 'e'},
340 {"invert-match", no_argument, NULL, 'v'},
341 {"silent", no_argument, NULL, 'q'},
342 {"text", no_argument, NULL, 'a'},
343 {"binary", no_argument, NULL, 'U'},
344 {"unix-byte-offsets", no_argument, NULL, 'u'},
345 {"version", no_argument, NULL, 'V'},
346 {"with-filename", no_argument, NULL, 'H'},
347 {"word-regexp", no_argument, NULL, 'w'},
351 /* Define flags declared in grep.h. */
355 unsigned char eolbyte;
357 /* For error messages. */
358 /* The name the program was run with, stripped of any leading path. */
359 static char const *filename;
362 enum directories_type
364 READ_DIRECTORIES = 2,
369 /* How to handle directories. */
370 static char const *const directories_args[] =
372 "read", "recurse", "skip", NULL
374 static enum directories_type const directories_types[] =
376 READ_DIRECTORIES, RECURSE_DIRECTORIES, SKIP_DIRECTORIES
378 ARGMATCH_VERIFY (directories_args, directories_types);
380 static enum directories_type directories = READ_DIRECTORIES;
382 /* How to handle dir/device/links */
383 static int only_files;
385 /* How to handle devices. */
390 } devices = READ_DEVICES;
392 static int grepdir (char const *, struct stats const *);
393 #if defined HAVE_DOS_FILE_CONTENTS
394 static inline int undossify_input (char *, size_t);
397 /* Functions we'll use to search. */
398 static compile_fp_t compile;
399 static execute_fp_t execute;
401 /* Like error, but suppress the diagnostic if requested. */
403 suppressible_error (char const *mesg, int errnum)
405 if (! suppress_errors)
406 error (0, errnum, "%s", mesg);
410 /* Convert STR to a positive integer, storing the result in *OUT.
411 STR must be a valid context length argument; report an error if it
414 context_length_arg (char const *str, int *out)
417 if (! (xstrtoumax (str, 0, 10, &value, "") == LONGINT_OK
418 && 0 <= (*out = value)
421 error (EXIT_TROUBLE, 0, "%s: %s", str,
422 _("invalid context length argument"));
427 /* Hairy buffering mechanism for grep. The intent is to keep
428 all reads aligned on a page boundary and multiples of the
429 page size, unless a read yields a partial page. */
431 static char *buffer; /* Base of buffer. */
432 static size_t bufalloc; /* Allocated buffer size, counting slop. */
433 #define INITIAL_BUFSIZE 32768 /* Initial buffer size, not counting slop. */
434 static int bufdesc; /* File descriptor. */
435 static char *bufbeg; /* Beginning of user-visible stuff. */
436 static char *buflim; /* Limit of user-visible stuff. */
437 static size_t pagesize; /* alignment of memory pages */
438 static off_t bufoffset; /* Read offset; defined on regular files. */
439 static off_t after_last_match; /* Pointer after last matching line that
440 would have been output if we were
441 outputting characters. */
443 /* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be
444 an integer or a pointer. Both args must be free of side effects. */
445 #define ALIGN_TO(val, alignment) \
446 ((size_t) (val) % (alignment) == 0 \
448 : (val) + ((alignment) - (size_t) (val) % (alignment)))
450 /* Reset the buffer for a new file, returning zero if we should skip it.
451 Initialize on the first time through. */
453 reset (int fd, char const *file, struct stats *stats)
457 pagesize = getpagesize ();
458 if (pagesize == 0 || 2 * pagesize + 1 <= pagesize)
460 bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1;
461 buffer = xmalloc (bufalloc);
464 bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize);
465 bufbeg[-1] = eolbyte;
468 if (S_ISREG (stats->stat.st_mode))
474 bufoffset = lseek (fd, 0, SEEK_CUR);
477 error (0, errno, _("lseek failed"));
485 /* Read new stuff into the buffer, saving the specified
486 amount of old stuff. When we're done, 'bufbeg' points
487 to the beginning of the buffer contents, and 'buflim'
488 points just after the end. Return zero if there's an error. */
490 fillbuf (size_t save, struct stats const *stats)
497 /* Offset from start of buffer to start of old stuff
498 that we want to save. */
499 size_t saved_offset = buflim - save - buffer;
501 if (pagesize <= buffer + bufalloc - buflim)
504 bufbeg = buflim - save;
508 size_t minsize = save + pagesize;
513 /* Grow newsize until it is at least as great as minsize. */
514 for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2)
515 if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2)
518 /* Try not to allocate more memory than the file size indicates,
519 as that might cause unnecessary memory exhaustion if the file
520 is large. However, do not use the original file size as a
521 heuristic if we've already read past the file end, as most
522 likely the file is growing. */
523 if (S_ISREG (stats->stat.st_mode))
525 off_t to_be_read = stats->stat.st_size - bufoffset;
526 off_t maxsize_off = save + to_be_read;
527 if (0 <= to_be_read && to_be_read <= maxsize_off
528 && maxsize_off == (size_t) maxsize_off
529 && minsize <= (size_t) maxsize_off
530 && (size_t) maxsize_off < newsize)
531 newsize = maxsize_off;
534 /* Add enough room so that the buffer is aligned and has room
535 for byte sentinels fore and aft. */
536 newalloc = newsize + pagesize + 1;
538 newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer;
539 readbuf = ALIGN_TO (newbuf + 1 + save, pagesize);
540 bufbeg = readbuf - save;
541 memmove (bufbeg, buffer + saved_offset, save);
542 bufbeg[-1] = eolbyte;
543 if (newbuf != buffer)
550 readsize = buffer + bufalloc - readbuf;
551 readsize -= readsize % pagesize;
556 while ((bytesread = read (bufdesc, readbuf, readsize)) < 0
562 fillsize = bytesread;
565 bufoffset += fillsize;
566 #if defined HAVE_DOS_FILE_CONTENTS
568 fillsize = undossify_input (readbuf, fillsize);
570 buflim = readbuf + fillsize;
574 /* Flags controlling the style of output. */
579 WITHOUT_MATCH_BINARY_FILES
580 } binary_files; /* How to handle binary files. */
582 static int filename_mask; /* If zero, output nulls after filenames. */
583 static int out_quiet; /* Suppress all normal output. */
584 static int out_invert; /* Print nonmatching stuff. */
585 static int out_file; /* Print filenames. */
586 static int out_line; /* Print line numbers. */
587 static int out_byte; /* Print byte offsets. */
588 static int out_before; /* Lines of leading context. */
589 static int out_after; /* Lines of trailing context. */
590 static int count_matches; /* Count matching lines. */
591 static int list_files; /* List matching files. */
592 static int no_filenames; /* Suppress file names. */
593 static off_t max_count; /* Stop after outputting this many
594 lines from an input file. */
595 static int line_buffered; /* If nonzero, use line buffering, i.e.
596 fflush everyline out. */
597 static char *label = NULL; /* Fake filename for stdin */
600 /* Internal variables to keep track of byte count, context, etc. */
601 static uintmax_t totalcc; /* Total character count before bufbeg. */
602 static char const *lastnl; /* Pointer after last newline counted. */
603 static char const *lastout; /* Pointer after last character output;
604 NULL if no character has been output
605 or if it's conceptually before bufbeg. */
606 static uintmax_t totalnl; /* Total newline count before lastnl. */
607 static off_t outleft; /* Maximum number of lines to be output. */
608 static int pending; /* Pending lines of output.
609 Always kept 0 if out_quiet is true. */
610 static int done_on_match; /* Stop scanning file on first match. */
611 static int exit_on_match; /* Exit on first match. */
613 #if defined HAVE_DOS_FILE_CONTENTS
617 /* Add two numbers that count input bytes or lines, and report an
618 error if the addition overflows. */
620 add_count (uintmax_t a, uintmax_t b)
622 uintmax_t sum = a + b;
624 error (EXIT_TROUBLE, 0, _("input is too large to count"));
629 nlscan (char const *lim)
633 for (beg = lastnl; beg < lim; beg++)
635 beg = memchr (beg, eolbyte, lim - beg);
640 totalnl = add_count (totalnl, newlines);
644 /* Print the current filename. */
646 print_filename (void)
648 PR_SGR_START_IF(filename_color);
649 fputs(filename, stdout);
650 PR_SGR_END_IF(filename_color);
653 /* Print a character separator. */
657 PR_SGR_START_IF(sep_color);
659 PR_SGR_END_IF(sep_color);
662 /* Print a line number or a byte offset. */
664 print_offset (uintmax_t pos, int min_width, const char *color)
666 /* Do not rely on printf to print pos, since uintmax_t may be longer
667 than long, and long long is not portable. */
669 char buf[sizeof pos * CHAR_BIT];
670 char *p = buf + sizeof buf;
674 *--p = '0' + pos % 10;
677 while ((pos /= 10) != 0);
679 /* Do this to maximize the probability of alignment across lines. */
681 while (--min_width >= 0)
684 PR_SGR_START_IF(color);
685 fwrite (p, 1, buf + sizeof buf - p, stdout);
686 PR_SGR_END_IF(color);
689 /* Print a whole line head (filename, line, byte). */
691 print_line_head (char const *beg, char const *lim, int sep)
709 totalnl = add_count (totalnl, 1);
714 print_offset (totalnl, 4, line_num_color);
720 uintmax_t pos = add_count (totalcc, beg - bufbeg);
721 #if defined HAVE_DOS_FILE_CONTENTS
722 pos = dossified_pos (pos);
726 print_offset (pos, 6, byte_num_color);
732 /* This assumes sep is one column wide.
733 Try doing this any other way with Unicode
734 (and its combining and wide characters)
735 filenames and you're wasting your efforts. */
737 fputs("\t\b", stdout);
744 print_line_middle (const char *beg, const char *lim,
745 const char *line_color, const char *match_color)
749 const char *cur = beg;
750 const char *mid = NULL;
753 && ((match_offset = execute(beg, lim - beg, &match_size,
754 beg + (cur - beg))) != (size_t) -1))
756 char const *b = beg + match_offset;
758 /* Avoid matching the empty line at the end of the buffer. */
762 /* Avoid hanging on grep --color "" foo */
765 /* Make minimal progress; there may be further non-empty matches. */
766 /* XXX - Could really advance by one whole multi-octet character. */
773 /* This function is called on a matching line only,
774 but is it selected or rejected/context? */
776 print_line_head(b, lim, out_invert ? SEP_CHAR_REJECTED
777 : SEP_CHAR_SELECTED);
780 PR_SGR_START(line_color);
786 fwrite (cur, sizeof (char), b - cur, stdout);
789 PR_SGR_START_IF(match_color);
790 fwrite (b, sizeof (char), match_size, stdout);
791 PR_SGR_END_IF(match_color);
795 cur = b + match_size;
807 print_line_tail (const char *beg, const char *lim, const char *line_color)
812 eol_size = (lim > beg && lim[-1] == eolbyte);
813 eol_size += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r');
814 tail_size = lim - eol_size - beg;
818 PR_SGR_START(line_color);
819 fwrite(beg, 1, tail_size, stdout);
821 PR_SGR_END(line_color);
828 prline (char const *beg, char const *lim, int sep)
831 const char *line_color;
832 const char *match_color;
835 print_line_head(beg, lim, sep);
837 matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert;
841 line_color = ( (sep == SEP_CHAR_SELECTED)
842 ^ (out_invert && (color_option < 0)))
843 ? selected_line_color : context_line_color;
844 match_color = (sep == SEP_CHAR_SELECTED)
845 ? selected_match_color : context_match_color;
848 line_color = match_color = NULL; /* Shouldn't be used. */
850 if ( (only_matching && matching)
851 || (color_option && (*line_color || *match_color)))
853 /* We already know that non-matching lines have no match (to colorize). */
854 if (matching && (only_matching || *match_color))
855 beg = print_line_middle(beg, lim, line_color, match_color);
857 /* FIXME: this test may be removable. */
858 if (!only_matching && *line_color)
859 beg = print_line_tail(beg, lim, line_color);
862 if (!only_matching && lim > beg)
863 fwrite (beg, 1, lim - beg, stdout);
866 error (0, errno, _("writing output"));
874 /* Print pending lines of trailing context prior to LIM. Trailing context ends
875 at the next matching line when OUTLEFT is 0. */
877 prpending (char const *lim)
881 while (pending > 0 && lastout < lim)
883 char const *nl = memchr (lastout, eolbyte, lim - lastout);
887 || ((execute(lastout, nl + 1 - lastout,
888 &match_size, NULL) == (size_t) -1)
890 prline (lastout, nl + 1, SEP_CHAR_REJECTED);
896 /* Print the lines between BEG and LIM. Deal with context crap.
897 If NLINESP is non-null, store a count of lines between BEG and LIM. */
899 prtext (char const *beg, char const *lim, int *nlinesp)
901 static int used; /* avoid printing SEP_STR_GROUP before any output */
906 if (!out_quiet && pending > 0)
913 /* Deal with leading context crap. */
915 bp = lastout ? lastout : bufbeg;
916 for (i = 0; i < out_before; ++i)
920 while (p[-1] != eol);
922 /* We print the SEP_STR_GROUP separator only if our output is
923 discontiguous from the last output in the file. */
924 if ((out_before || out_after) && used && p != lastout && group_separator)
926 PR_SGR_START_IF(sep_color);
927 fputs (group_separator, stdout);
928 PR_SGR_END_IF(sep_color);
934 char const *nl = memchr (p, eol, beg - p);
936 prline (p, nl, SEP_CHAR_REJECTED);
943 /* Caller wants a line count. */
944 for (n = 0; p < lim && n < outleft; n++)
946 char const *nl = memchr (p, eol, lim - p);
949 prline (p, nl, SEP_CHAR_SELECTED);
954 /* relying on it that this function is never called when outleft = 0. */
955 after_last_match = bufoffset - (buflim - p);
959 prline (beg, lim, SEP_CHAR_SELECTED);
961 pending = out_quiet ? 0 : out_after;
966 do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr)
969 const char *line_next;
971 /* With the current implementation, using --ignore-case with a multi-byte
972 character set is very inefficient when applied to a large buffer
973 containing many matches. We can avoid much of the wasted effort
974 by matching line-by-line.
976 FIXME: this is just an ugly workaround, and it doesn't really
977 belong here. Also, PCRE is always using this same per-line
978 matching algorithm. Either we fix -i, or we should refactor
979 this code---for example, we could add another function pointer
980 to struct matcher to split the buffer passed to execute. It would
981 perform the memchr if line-by-line matching is necessary, or just
982 return buf + size otherwise. */
983 if (MB_CUR_MAX == 1 || !match_icase)
984 return execute(buf, size, match_size, start_ptr);
986 for (line_next = buf; line_next < buf + size; )
988 const char *line_buf = line_next;
989 const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf);
990 if (line_end == NULL)
991 line_next = line_end = buf + size;
993 line_next = line_end + 1;
995 if (start_ptr && start_ptr >= line_end)
998 result = execute (line_buf, line_next - line_buf, match_size, start_ptr);
999 if (result != (size_t) -1)
1000 return (line_buf - buf) + result;
1006 /* Scan the specified portion of the buffer, matching lines (or
1007 between matching lines if OUT_INVERT is true). Return a count of
1010 grepbuf (char const *beg, char const *lim)
1014 size_t match_offset;
1019 while ((match_offset = do_execute(p, lim - p, &match_size,
1020 NULL)) != (size_t) -1)
1022 char const *b = p + match_offset;
1023 char const *endp = b + match_size;
1024 /* Avoid matching the empty line at the end of the buffer. */
1029 prtext (b, endp, (int *) 0);
1032 if (!outleft || done_on_match)
1035 exit (EXIT_SUCCESS);
1036 after_last_match = bufoffset - (buflim - endp);
1050 if (out_invert && p < lim)
1052 prtext (p, lim, &n);
1059 /* Search a given file. Normally, return a count of lines printed;
1060 but if the file is a directory and we search it recursively, then
1061 return -2 if there was a match, and -1 otherwise. */
1063 grep (int fd, char const *file, struct stats *stats)
1067 size_t residue, save;
1073 if (!reset (fd, file, stats))
1076 if (file && directories == RECURSE_DIRECTORIES
1077 && S_ISDIR (stats->stat.st_mode))
1079 /* Close fd now, so that we don't open a lot of file descriptors
1080 when we recurse deeply. */
1081 if (close (fd) != 0)
1082 error (0, errno, "%s", file);
1083 return grepdir (file, stats) - 2;
1089 outleft = max_count;
1090 after_last_match = 0;
1097 if (! fillbuf (save, stats))
1099 if (! is_EISDIR (errno, file))
1101 if (errno != EINVAL)
1102 suppressible_error (filename, errno);
1107 not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)
1108 || binary_files == WITHOUT_MATCH_BINARY_FILES)
1109 && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg));
1110 if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)
1112 done_on_match += not_text;
1113 out_quiet += not_text;
1121 beg = bufbeg + save;
1123 /* no more data to scan (eof) except for maybe a residue -> break */
1127 /* Determine new residue (the length of an incomplete line at the end of
1128 the buffer, 0 means there is no incomplete last line). */
1131 for (lim = buflim; lim[-1] != eol; lim--)
1135 lim = beg - residue;
1137 residue = buflim - lim;
1142 nlines += grepbuf (beg, lim);
1145 if((!outleft && !pending) || (nlines && done_on_match && !out_invert))
1149 /* The last OUT_BEFORE lines at the end of the buffer will be needed as
1150 leading context if there is a matching line at the begin of the
1151 next data. Make beg point to their begin. */
1154 while (i < out_before && beg > bufbeg && beg != lastout)
1159 while (beg[-1] != eol);
1162 /* detect if leading context is discontinuous from last printed line. */
1166 /* Handle some details and read more data to scan. */
1167 save = residue + lim - beg;
1169 totalcc = add_count (totalcc, buflim - bufbeg - save);
1172 if (! fillbuf (save, stats))
1174 if (! is_EISDIR (errno, file))
1175 suppressible_error (filename, errno);
1183 nlines += grepbuf (bufbeg + save - residue, buflim);
1189 done_on_match -= not_text;
1190 out_quiet -= not_text;
1191 if ((not_text & ~out_quiet) && nlines != 0)
1192 printf (_("Binary file %s matches\n"), filename);
1197 grepfile (char const *file, struct stats *stats)
1206 filename = label ? label : _("(standard input)");
1210 if (stat (file, &stats->stat) != 0)
1212 suppressible_error (file, errno);
1217 if (S_ISDIR (stats->stat.st_mode))
1219 if (directories != RECURSE_DIRECTORIES)
1221 if (lstat(file, &stats->stat) != 0)
1223 if (!S_ISDIR (stats->stat.st_mode))
1226 else if (!S_ISREG (stats->stat.st_mode))
1229 if (directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode))
1231 if (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode)
1232 || S_ISBLK (stats->stat.st_mode)
1233 || S_ISSOCK (stats->stat.st_mode)
1234 || S_ISFIFO (stats->stat.st_mode)))
1236 while ((desc = open (file, O_RDONLY)) < 0 && errno == EINTR)
1243 if (is_EISDIR (e, file) && directories == RECURSE_DIRECTORIES)
1245 #if 0 /* DISABLED by only-files local modification option */
1246 if (stat (file, &stats->stat) != 0)
1248 error (0, errno, "%s", file);
1253 return grepdir (file, stats);
1256 if (!suppress_errors)
1258 if (directories == SKIP_DIRECTORIES)
1266 /* When skipping directories, don't worry about
1267 directories that can't be opened. */
1274 suppressible_error (file, e);
1281 #if defined SET_BINARY
1282 /* Set input to binary mode. Pipes are simulated with files
1283 on DOS, so this includes the case of "foo | grep bar". */
1288 count = grep (desc, file, stats);
1299 print_sep(SEP_CHAR_SELECTED);
1303 printf ("%d\n", count);
1307 if (list_files == 1 - 2 * status)
1310 fputc('\n' & filename_mask, stdout);
1315 off_t required_offset = outleft ? bufoffset : after_last_match;
1316 if (required_offset != bufoffset
1317 && lseek (desc, required_offset, SEEK_SET) < 0
1318 && S_ISREG (stats->stat.st_mode))
1319 error (0, errno, "%s", filename);
1322 while (close (desc) != 0)
1325 error (0, errno, "%s", file);
1334 grepdir (char const *dir, struct stats const *stats)
1336 struct stats const *ancestor;
1339 if ( excluded_directory_patterns &&
1340 excluded_file_name (excluded_directory_patterns, dir) ) {
1345 /* Mingw32 does not support st_ino. No known working hosts use zero
1346 for st_ino, so assume that the Mingw32 bug applies if it's zero. */
1347 if (stats->stat.st_ino)
1348 for (ancestor = stats; (ancestor = ancestor->parent) != 0; )
1349 if (ancestor->stat.st_ino == stats->stat.st_ino
1350 && ancestor->stat.st_dev == stats->stat.st_dev)
1352 if (!suppress_errors)
1353 error (0, 0, _("warning: %s: %s"), dir,
1354 _("recursive directory loop"));
1358 name_space = savedir (dir, stats->stat.st_size, included_patterns,
1359 excluded_patterns, excluded_directory_patterns);
1364 suppressible_error (dir, errno);
1370 size_t dirlen = strlen (dir);
1371 int needs_slash = ! (dirlen == FILE_SYSTEM_PREFIX_LEN (dir)
1372 || ISSLASH (dir[dirlen - 1]));
1374 char const *namep = name_space;
1376 child.parent = stats;
1377 out_file += !no_filenames;
1380 size_t namelen = strlen (namep);
1381 file = xrealloc (file, dirlen + 1 + namelen + 1);
1384 strcpy (file + dirlen + needs_slash, namep);
1385 namep += namelen + 1;
1386 status &= grepfile (file, &child);
1388 out_file -= !no_filenames;
1396 void usage (int status) __attribute__ ((noreturn));
1402 fprintf (stderr, _("Usage: %s [OPTION]... PATTERN [FILE]...\n"),
1404 fprintf (stderr, _("Try `%s --help' for more information.\n"),
1409 printf (_("Usage: %s [OPTION]... PATTERN [FILE]...\n"), program_name);
1411 Search for PATTERN in each FILE or standard input.\n"));
1412 printf ("%s", gettext (before_options));
1414 Example: %s -i 'hello world' menu.h main.c\n\
1416 Regexp selection and interpretation:\n"), program_name);
1417 if (matchers[1].name)
1419 -E, --extended-regexp PATTERN is an extended regular expression (ERE)\n\
1420 -F, --fixed-strings PATTERN is a set of newline-separated fixed strings\n\
1421 -G, --basic-regexp PATTERN is a basic regular expression (BRE)\n\
1422 -P, --perl-regexp PATTERN is a Perl regular expression\n"));
1423 /* -X is undocumented on purpose. */
1425 -e, --regexp=PATTERN use PATTERN for matching\n\
1426 -f, --file=FILE obtain PATTERN from FILE\n\
1427 -i, --ignore-case ignore case distinctions\n\
1428 -w, --word-regexp force PATTERN to match only whole words\n\
1429 -x, --line-regexp force PATTERN to match only whole lines\n\
1430 -z, --null-data a data line ends in 0 byte, not newline\n"));
1434 -s, --no-messages suppress error messages\n\
1435 -v, --invert-match select non-matching lines\n\
1436 -V, --version print version information and exit\n\
1437 --help display this help and exit\n\
1438 --mmap ignored for backwards compatibility\n"));
1442 -m, --max-count=NUM stop after NUM matches\n\
1443 -b, --byte-offset print the byte offset with output lines\n\
1444 -n, --line-number print line number with output lines\n\
1445 --line-buffered flush output on every line\n\
1446 -H, --with-filename print the filename for each match\n\
1447 -h, --no-filename suppress the prefixing filename on output\n\
1448 --label=LABEL print LABEL as filename for standard input\n\
1451 -o, --only-matching show only the part of a line matching PATTERN\n\
1452 -q, --quiet, --silent suppress all normal output\n\
1453 --binary-files=TYPE assume that binary files are TYPE;\n\
1454 TYPE is `binary', `text', or `without-match'\n\
1455 -a, --text equivalent to --binary-files=text\n\
1458 -I equivalent to --binary-files=without-match\n\
1459 -d, --directories=ACTION how to handle directories;\n\
1460 ACTION is `read', `recurse', or `skip'\n\
1461 -D, --devices=ACTION how to handle devices, FIFOs and sockets;\n\
1462 ACTION is `read' or `skip'\n\
1463 -R, -r, --recursive equivalent to --directories=recurse\n\
1466 --include=FILE_PATTERN search only files that match FILE_PATTERN\n\
1467 --exclude=FILE_PATTERN skip files and directories matching FILE_PATTERN\n\
1468 --exclude-from=FILE skip files matching any file pattern from FILE\n\
1469 --exclude-dir=PATTERN directories that match PATTERN will be skipped.\n\
1472 -O, --only-files Ignore special files, except symlinks.\n\
1473 When recursing directories, ignore symlinked\n\
1474 directories as well.\n\
1475 -L, --files-without-match print only names of FILEs containing no match\n\
1476 -l, --files-with-matches print only names of FILEs containing matches\n\
1477 -c, --count print only a count of matching lines per FILE\n\
1478 -T, --initial-tab make tabs line up (if needed)\n\
1479 -Z, --null print 0 byte after FILE name\n"));
1483 -B, --before-context=NUM print NUM lines of leading context\n\
1484 -A, --after-context=NUM print NUM lines of trailing context\n\
1485 -C, --context=NUM print NUM lines of output context\n\
1488 -NUM same as --context=NUM\n\
1490 --colour[=WHEN] use markers to highlight the matching strings;\n\
1491 WHEN is `always', `never', or `auto'\n\
1492 -U, --binary do not strip CR characters at EOL (MSDOS)\n\
1493 -u, --unix-byte-offsets report offsets as if CRs were not there (MSDOS)\n\
1495 printf ("%s", _(after_options));
1497 With no FILE, or when FILE is -, read standard input. If less than two FILEs\n\
1498 are given, assume -h. Exit status is 0 if any line was selected, 1 otherwise;\n\
1499 if any error occurs and -q was not given, the exit status is 2.\n"));
1500 printf (_("\nReport bugs to: %s\n"), PACKAGE_BUGREPORT);
1501 printf (_("GNU Grep home page: <%s>\n"),
1502 "http://www.gnu.org/software/grep/");
1503 fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"),
1510 /* If M is NULL, initialize the matcher to the default. Otherwise set the
1511 matcher to M if available. Exit in case of conflicts or if M is not
1514 setmatcher (char const *m)
1516 static char const *matcher;
1521 compile = matchers[0].compile;
1522 execute = matchers[0].execute;
1523 if (!matchers[1].name)
1524 matcher = matchers[0].name;
1529 if (matcher && STREQ (matcher, m))
1532 else if (!matchers[1].name)
1533 error (EXIT_TROUBLE, 0, _("%s can only use the %s pattern syntax"),
1534 program_name, matcher);
1536 error (EXIT_TROUBLE, 0, _("conflicting matchers specified"));
1541 for (i = 0; matchers[i].name; i++)
1542 if (STREQ (m, matchers[i].name))
1544 compile = matchers[i].compile;
1545 execute = matchers[i].execute;
1550 error (EXIT_TROUBLE, 0, _("invalid matcher %s"), m);
1557 #if defined HAVE_SETRLIMIT && defined RLIMIT_STACK
1560 /* I think every platform needs to do this, so that regex.c
1561 doesn't oveflow the stack. The default value of
1562 `re_max_failures' is too large for some platforms: it needs
1563 more than 3MB-large stack.
1565 The test for HAVE_SETRLIMIT should go into `configure'. */
1566 if (!getrlimit (RLIMIT_STACK, &rlim))
1569 extern long int re_max_failures; /* from regex.c */
1571 /* Approximate the amount regex.c needs, plus some more. */
1572 newlim = re_max_failures * 2 * 20 * sizeof (char *);
1573 if (newlim > rlim.rlim_max)
1575 newlim = rlim.rlim_max;
1576 re_max_failures = newlim / (2 * 20 * sizeof (char *));
1578 if (rlim.rlim_cur < newlim)
1580 rlim.rlim_cur = newlim;
1581 setrlimit (RLIMIT_STACK, &rlim);
1587 /* Find the white-space-separated options specified by OPTIONS, and
1588 using BUF to store copies of these options, set ARGV[0], ARGV[1],
1589 etc. to the option copies. Return the number N of options found.
1590 Do not set ARGV[N] to NULL. If ARGV is NULL, do not store ARGV[0]
1591 etc. Backslash can be used to escape whitespace (and backslashes). */
1593 prepend_args (char const *options, char *buf, char **argv)
1595 char const *o = options;
1601 while (c_isspace ((unsigned char) *o))
1610 if ((*b++ = *o++) == '\\' && *o)
1612 while (*o && ! c_isspace ((unsigned char) *o));
1618 /* Prepend the whitespace-separated options in OPTIONS to the argument
1619 vector of a main program with argument count *PARGC and argument
1622 prepend_default_options (char const *options, int *pargc, char ***pargv)
1624 if (options && *options)
1626 char *buf = xmalloc (strlen (options) + 1);
1627 int prepended = prepend_args (options, buf, (char **) NULL);
1629 char * const *argv = *pargv;
1630 char **pp = xmalloc ((prepended + argc + 1) * sizeof *pp);
1631 *pargc = prepended + argc;
1634 pp += prepend_args (options, buf, pp);
1635 while ((*pp++ = *argv++))
1640 /* Get the next non-digit option from ARGC and ARGV.
1641 Return -1 if there are no more options.
1642 Process any digit options that were encountered on the way,
1643 and store the resulting integer into *DEFAULT_CONTEXT. */
1645 get_nondigit_option (int argc, char *const *argv, int *default_context)
1647 static int prev_digit_optind = -1;
1648 int opt, this_digit_optind, was_digit;
1649 char buf[sizeof (uintmax_t) * CHAR_BIT + 4];
1653 this_digit_optind = optind;
1654 while (opt = getopt_long (argc, (char **) argv, short_options, long_options,
1656 '0' <= opt && opt <= '9')
1658 if (prev_digit_optind != this_digit_optind || !was_digit)
1660 /* Reset to start another context length argument. */
1665 /* Suppress trivial leading zeros, to avoid incorrect
1666 diagnostic on strings like 00000000000. */
1670 if (p == buf + sizeof buf - 4)
1672 /* Too many digits. Append "..." to make context_length_arg
1673 complain about "X...", where X contains the digits seen
1682 prev_digit_optind = this_digit_optind;
1683 this_digit_optind = optind;
1688 context_length_arg (buf, default_context);
1694 /* Parse GREP_COLORS. The default would look like:
1695 GREP_COLORS='ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36'
1696 with boolean capabilities (ne and rv) unset (i.e., omitted).
1697 No character escaping is needed or supported. */
1699 parse_grep_colors (void)
1706 p = getenv("GREP_COLORS"); /* Plural! */
1707 if (p == NULL || *p == '\0')
1710 /* Work off a writable copy. */
1711 q = xmalloc(strlen(p) + 1);
1718 /* From now on, be well-formed or you're gone. */
1720 if (*q == ':' || *q == '\0')
1723 struct color_cap *cap;
1725 *q++ = '\0'; /* Terminate name or val. */
1726 /* Empty name without val (empty cap)
1727 * won't match and will be ignored. */
1728 for (cap = color_dict; cap->name; cap++)
1729 if (STREQ (cap->name, name))
1731 /* If name unknown, go on for forward compatibility. */
1739 error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1740 "needs a value (\"=...\"); skipped"), p, name);
1743 error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1744 "is boolean and cannot take a value (\"=%s\"); skipped"),
1749 const char *err_str = cap->fct();
1752 error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity %s"),
1762 if (q == name || val)
1764 *q++ = '\0'; /* Terminate name. */
1765 val = q; /* Can be the empty string. */
1767 else if (val == NULL)
1768 q++; /* Accumulate name. */
1769 else if (*q == ';' || (*q >= '0' && *q <= '9'))
1770 q++; /* Accumulate val. Protect the terminal from being sent crap. */
1775 error(0, 0, _("stopped processing of ill-formed GREP_COLORS=\"%s\" "
1776 "at remaining substring \"%s\""), p, q);
1780 main (int argc, char **argv)
1783 size_t keycc, oldcc, keyalloc;
1785 int opt, cc, status;
1786 int default_context;
1789 initialize_main (&argc, &argv);
1790 set_program_name (argv[0]);
1791 program_name = argv[0];
1799 max_count = TYPE_MAXIMUM (off_t);
1801 /* The value -1 means to use DEFAULT_CONTEXT. */
1802 out_after = out_before = -1;
1803 /* Default before/after context: chaged by -C/-NUM options */
1804 default_context = 0;
1805 /* Changed by -o option */
1808 /* Internationalization. */
1809 #if defined HAVE_SETLOCALE
1810 setlocale (LC_ALL, "");
1812 #if defined ENABLE_NLS
1813 bindtextdomain (PACKAGE, LOCALEDIR);
1814 textdomain (PACKAGE);
1817 exit_failure = EXIT_TROUBLE;
1818 atexit (close_stdout);
1820 prepend_default_options (getenv ("GREP_OPTIONS"), &argc, &argv);
1823 while ((opt = get_nondigit_option (argc, argv, &default_context)) != -1)
1827 context_length_arg (optarg, &out_after);
1831 context_length_arg (optarg, &out_before);
1835 /* Set output match context, but let any explicit leading or
1836 trailing amount specified with -A or -B stand. */
1837 context_length_arg (optarg, &default_context);
1841 if (STREQ (optarg, "read"))
1842 devices = READ_DEVICES;
1843 else if (STREQ (optarg, "skip"))
1844 devices = SKIP_DEVICES;
1846 error (EXIT_TROUBLE, 0, _("unknown devices method"));
1850 setmatcher ("egrep");
1854 setmatcher ("fgrep");
1858 setmatcher ("perl");
1862 setmatcher ("grep");
1865 case 'X': /* undocumented on purpose */
1866 setmatcher (optarg);
1875 binary_files = WITHOUT_MATCH_BINARY_FILES;
1887 #if defined HAVE_DOS_FILE_CONTENTS
1888 dos_use_file_type = DOS_BINARY;
1893 #if defined HAVE_DOS_FILE_CONTENTS
1894 dos_report_unix_offset = 1;
1903 binary_files = TEXT_BINARY_FILES;
1915 directories = XARGMATCH ("--directories", optarg,
1916 directories_args, directories_types);
1920 cc = strlen (optarg);
1921 keys = xrealloc (keys, keycc + cc + 1);
1922 strcpy (&keys[keycc], optarg);
1924 keys[keycc++] = '\n';
1928 fp = STREQ (optarg, "-") ? stdin : fopen (optarg, "r");
1930 error (EXIT_TROUBLE, errno, "%s", optarg);
1931 for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
1933 keys = xrealloc (keys, keyalloc);
1936 && (cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) > 0)
1939 if (keycc == keyalloc - 1)
1940 keys = xrealloc (keys, keyalloc *= 2);
1944 /* Append final newline if file ended in non-newline. */
1945 if (oldcc != keycc && keys[keycc - 1] != '\n')
1946 keys[keycc++] = '\n';
1955 case 'y': /* For old-timers . . . */
1960 /* Like -l, except list files that don't contain matches.
1961 Inspired by the same option in Hume's gre. */
1972 switch (xstrtoumax (optarg, 0, 10, &value, ""))
1976 if (0 <= max_count && max_count == value)
1979 case LONGINT_OVERFLOW:
1980 max_count = TYPE_MAXIMUM (off_t);
1984 error (EXIT_TROUBLE, 0, _("invalid max count"));
2004 directories = RECURSE_DIRECTORIES;
2008 suppress_errors = 1;
2031 case BINARY_FILES_OPTION:
2032 if (STREQ (optarg, "binary"))
2033 binary_files = BINARY_BINARY_FILES;
2034 else if (STREQ (optarg, "text"))
2035 binary_files = TEXT_BINARY_FILES;
2036 else if (STREQ (optarg, "without-match"))
2037 binary_files = WITHOUT_MATCH_BINARY_FILES;
2039 error (EXIT_TROUBLE, 0, _("unknown binary-files type"));
2044 if(!strcasecmp(optarg, "always") || !strcasecmp(optarg, "yes") ||
2045 !strcasecmp(optarg, "force"))
2047 else if(!strcasecmp(optarg, "never") || !strcasecmp(optarg, "no") ||
2048 !strcasecmp(optarg, "none"))
2050 else if(!strcasecmp(optarg, "auto") || !strcasecmp(optarg, "tty") ||
2051 !strcasecmp(optarg, "if-tty"))
2057 if (color_option == 2)
2060 if (isatty (STDOUT_FILENO) && (t = getenv ("TERM"))
2061 && !STREQ (t, "dumb"))
2068 case EXCLUDE_OPTION:
2069 if (!excluded_patterns)
2070 excluded_patterns = new_exclude ();
2071 add_exclude (excluded_patterns, optarg, EXCLUDE_WILDCARDS);
2073 case EXCLUDE_FROM_OPTION:
2074 if (!excluded_patterns)
2075 excluded_patterns = new_exclude ();
2076 if (add_exclude_file (add_exclude, excluded_patterns, optarg,
2077 EXCLUDE_WILDCARDS, '\n') != 0)
2079 error (EXIT_TROUBLE, errno, "%s", optarg);
2083 case EXCLUDE_DIRECTORY_OPTION:
2084 if (!excluded_directory_patterns)
2085 excluded_directory_patterns = new_exclude ();
2086 add_exclude (excluded_directory_patterns, optarg, EXCLUDE_WILDCARDS);
2089 case INCLUDE_OPTION:
2090 if (!included_patterns)
2091 included_patterns = new_exclude ();
2092 add_exclude (included_patterns, optarg,
2093 EXCLUDE_WILDCARDS | EXCLUDE_INCLUDE);
2096 case GROUP_SEPARATOR_OPTION:
2097 group_separator = optarg;
2100 case LINE_BUFFERED_OPTION:
2114 usage (EXIT_TROUBLE);
2119 /* POSIX.2 says that -q overrides -l, which in turn overrides the
2120 other output options. */
2123 if (exit_on_match | list_files)
2128 out_quiet = count_matches | done_on_match;
2131 out_after = default_context;
2133 out_before = default_context;
2138 char *userval = getenv ("GREP_COLOR");
2139 if (userval != NULL && *userval != '\0')
2140 selected_match_color = context_match_color = userval;
2142 /* New GREP_COLORS has priority. */
2143 parse_grep_colors();
2148 version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, \
2150 exit (EXIT_SUCCESS); \
2154 usage (EXIT_SUCCESS);
2160 /* No keys were specified (e.g. -f /dev/null). Match nothing. */
2162 match_lines = match_words = 0;
2165 /* Strip trailing newline. */
2171 /* A copy must be made in case of an xrealloc() or free() later. */
2172 keycc = strlen(argv[optind]);
2173 keys = xmalloc(keycc + 1);
2174 strcpy(keys, argv[optind++]);
2177 usage (EXIT_TROUBLE);
2180 compile(keys, keycc);
2183 if ((argc - optind > 1 && !no_filenames) || with_filenames)
2187 /* Output is set to binary mode because we shouldn't convert
2188 NL to CR-LF pairs, especially when grepping binary files. */
2194 exit (EXIT_FAILURE);
2201 char *file = argv[optind];
2202 if ((included_patterns || excluded_patterns)
2205 if (included_patterns
2206 && excluded_file_name (included_patterns, file))
2208 if (excluded_patterns
2209 && excluded_file_name (excluded_patterns, file))
2212 status &= grepfile (STREQ (file, "-") ? (char *) NULL : file,
2215 while ( ++optind < argc);
2218 status = grepfile ((char *) NULL, &stats_base);
2220 /* We register via atexit() to test stdout. */
2221 exit (errseen ? EXIT_TROUBLE : status);
2223 /* vim:set shiftwidth=2: */