043a6b988ca5a53c0753d15584219901597b5d3a
[dragonfly.git] / contrib / grep / src / main.c
1 /* grep.c - main driver file for grep.
2    Copyright (C) 1992, 1997-2002, 2004-2011 Free Software Foundation, Inc.
3
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)
7    any later version.
8
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.
13
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
17    02110-1301, USA.  */
18
19 /* Written July 1992 by Mike Haertel.  */
20
21 #include <config.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #if defined HAVE_SETRLIMIT
25 # include <sys/time.h>
26 # include <sys/resource.h>
27 #endif
28 #include "mbsupport.h"
29 #include <wchar.h>
30 #include <wctype.h>
31 #include <fcntl.h>
32 #include <stdio.h>
33 #include "system.h"
34
35 #include "argmatch.h"
36 #include "c-ctype.h"
37 #include "closeout.h"
38 #include "error.h"
39 #include "exclude.h"
40 #include "exitfail.h"
41 #include "getopt.h"
42 #include "grep.h"
43 #include "intprops.h"
44 #include "isdir.h"
45 #include "progname.h"
46 #include "propername.h"
47 #include "savedir.h"
48 #include "version-etc.h"
49 #include "xalloc.h"
50 #include "xstrtol.h"
51
52 #define SEP_CHAR_SELECTED ':'
53 #define SEP_CHAR_REJECTED '-'
54 #define SEP_STR_GROUP    "--"
55
56 #define STREQ(a, b) (strcmp (a, b) == 0)
57
58 #define AUTHORS \
59   proper_name ("Mike Haertel"), \
60   _("others, see\n<http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>")
61
62 struct stats
63 {
64   struct stats const *parent;
65   struct stat stat;
66 };
67
68 /* base of chain of stat buffers, used to detect directory loops */
69 static struct stats stats_base;
70
71 /* if non-zero, display usage information and exit */
72 static int show_help;
73
74 /* If non-zero, print the version on standard output and exit.  */
75 static int show_version;
76
77 /* If nonzero, suppress diagnostics for nonexistent or unreadable files.  */
78 static int suppress_errors;
79
80 /* If nonzero, use color markers.  */
81 static int color_option;
82
83 /* If nonzero, show only the part of a line matching the expression. */
84 static int only_matching;
85
86 /* If nonzero, make sure first content char in a line is on a tab stop. */
87 static int align_tabs;
88
89 /* The group separator used when context is requested. */
90 static const char *group_separator = SEP_STR_GROUP;
91
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 */
139
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 */
147
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.
187
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
200       SGR END.
201
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
209
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))
218
219 struct color_cap
220   {
221     const char *name;
222     const char **var;
223     const char *(*fct)(void);
224   };
225
226 static const char *
227 color_cap_mt_fct(void)
228 {
229   /* Our caller just set selected_match_color.  */
230   context_match_color = selected_match_color;
231
232   return NULL;
233 }
234
235 static const char *
236 color_cap_rv_fct(void)
237 {
238   /* By this point, it was 1 (or already -1).  */
239   color_option = -1;  /* That's still != 0.  */
240
241   return NULL;
242 }
243
244 static const char *
245 color_cap_ne_fct(void)
246 {
247   sgr_start = "\33[%sm";
248   sgr_end   = "\33[m";
249
250   return NULL;
251 }
252
253 /* For GREP_COLORS.  */
254 static struct color_cap color_dict[] =
255   {
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_* */
267     { NULL, NULL,                  NULL }
268   };
269
270 static struct exclude *excluded_patterns;
271 static struct exclude *included_patterns;
272 static struct exclude *excluded_directory_patterns;
273 /* Short options.  */
274 static char const short_options[] =
275 "0123456789A:B:C:D:EFGHIOPTUVX:abcd:e:f:hiKLlm:noqRrsuvwxyZz";
276
277 /* Non-boolean long options that have no corresponding short equivalents.  */
278 enum
279 {
280   BINARY_FILES_OPTION = CHAR_MAX + 1,
281   COLOR_OPTION,
282   INCLUDE_OPTION,
283   EXCLUDE_OPTION,
284   EXCLUDE_FROM_OPTION,
285   LINE_BUFFERED_OPTION,
286   LABEL_OPTION,
287   EXCLUDE_DIRECTORY_OPTION,
288   GROUP_SEPARATOR_OPTION,
289   MMAP_OPTION
290 };
291
292 /* Long options equivalences. */
293 static struct option const long_options[] =
294 {
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'},
326
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'},
348   {0, 0, 0, 0}
349 };
350
351 /* Define flags declared in grep.h. */
352 int match_icase;
353 int match_words;
354 int match_lines;
355 unsigned char eolbyte;
356
357 /* For error messages. */
358 /* The name the program was run with, stripped of any leading path. */
359 static char const *filename;
360 static int errseen;
361
362 enum directories_type
363   {
364     READ_DIRECTORIES = 2,
365     RECURSE_DIRECTORIES,
366     SKIP_DIRECTORIES
367   };
368
369 /* How to handle directories.  */
370 static char const *const directories_args[] =
371 {
372   "read", "recurse", "skip", NULL
373 };
374 static enum directories_type const directories_types[] =
375 {
376   READ_DIRECTORIES, RECURSE_DIRECTORIES, SKIP_DIRECTORIES
377 };
378 ARGMATCH_VERIFY (directories_args, directories_types);
379
380 static enum directories_type directories = READ_DIRECTORIES;
381
382 /* How to handle dir/device/links */
383 static int only_files;
384
385 /* How to handle devices. */
386 static enum
387   {
388     READ_DEVICES,
389     SKIP_DEVICES
390   } devices = READ_DEVICES;
391
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);
395 #endif
396
397 /* Functions we'll use to search. */
398 static compile_fp_t compile;
399 static execute_fp_t execute;
400
401 /* Like error, but suppress the diagnostic if requested.  */
402 static void
403 suppressible_error (char const *mesg, int errnum)
404 {
405   if (! suppress_errors)
406     error (0, errnum, "%s", mesg);
407   errseen = 1;
408 }
409
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
412    isn't.  */
413 static void
414 context_length_arg (char const *str, int *out)
415 {
416   uintmax_t value;
417   if (! (xstrtoumax (str, 0, 10, &value, "") == LONGINT_OK
418          && 0 <= (*out = value)
419          && *out == value))
420     {
421       error (EXIT_TROUBLE, 0, "%s: %s", str,
422              _("invalid context length argument"));
423     }
424 }
425
426
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.  */
430
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. */
442
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 \
447    ? (val) \
448    : (val) + ((alignment) - (size_t) (val) % (alignment)))
449
450 /* Reset the buffer for a new file, returning zero if we should skip it.
451    Initialize on the first time through. */
452 static int
453 reset (int fd, char const *file, struct stats *stats)
454 {
455   if (! pagesize)
456     {
457       pagesize = getpagesize ();
458       if (pagesize == 0 || 2 * pagesize + 1 <= pagesize)
459         abort ();
460       bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1;
461       buffer = xmalloc (bufalloc);
462     }
463
464   bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize);
465   bufbeg[-1] = eolbyte;
466   bufdesc = fd;
467
468   if (S_ISREG (stats->stat.st_mode))
469     {
470       if (file)
471         bufoffset = 0;
472       else
473         {
474           bufoffset = lseek (fd, 0, SEEK_CUR);
475           if (bufoffset < 0)
476             {
477               error (0, errno, _("lseek failed"));
478               return 0;
479             }
480         }
481     }
482   return 1;
483 }
484
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.  */
489 static int
490 fillbuf (size_t save, struct stats const *stats)
491 {
492   size_t fillsize = 0;
493   int cc = 1;
494   char *readbuf;
495   size_t readsize;
496
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;
500
501   if (pagesize <= buffer + bufalloc - buflim)
502     {
503       readbuf = buflim;
504       bufbeg = buflim - save;
505     }
506   else
507     {
508       size_t minsize = save + pagesize;
509       size_t newsize;
510       size_t newalloc;
511       char *newbuf;
512
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)
516           xalloc_die ();
517
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))
524         {
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;
532         }
533
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;
537
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)
544         {
545           free (buffer);
546           buffer = newbuf;
547         }
548     }
549
550   readsize = buffer + bufalloc - readbuf;
551   readsize -= readsize % pagesize;
552
553   if (! fillsize)
554     {
555       ssize_t bytesread;
556       while ((bytesread = read (bufdesc, readbuf, readsize)) < 0
557              && errno == EINTR)
558         continue;
559       if (bytesread < 0)
560         cc = 0;
561       else
562         fillsize = bytesread;
563     }
564
565   bufoffset += fillsize;
566 #if defined HAVE_DOS_FILE_CONTENTS
567   if (fillsize)
568     fillsize = undossify_input (readbuf, fillsize);
569 #endif
570   buflim = readbuf + fillsize;
571   return cc;
572 }
573
574 /* Flags controlling the style of output. */
575 static enum
576 {
577   BINARY_BINARY_FILES,
578   TEXT_BINARY_FILES,
579   WITHOUT_MATCH_BINARY_FILES
580 } binary_files;         /* How to handle binary files.  */
581
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 */
598
599
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.  */
612
613 #if defined HAVE_DOS_FILE_CONTENTS
614 # include "dosbuf.c"
615 #endif
616
617 /* Add two numbers that count input bytes or lines, and report an
618    error if the addition overflows.  */
619 static uintmax_t
620 add_count (uintmax_t a, uintmax_t b)
621 {
622   uintmax_t sum = a + b;
623   if (sum < a)
624     error (EXIT_TROUBLE, 0, _("input is too large to count"));
625   return sum;
626 }
627
628 static void
629 nlscan (char const *lim)
630 {
631   size_t newlines = 0;
632   char const *beg;
633   for (beg = lastnl; beg < lim; beg++)
634     {
635       beg = memchr (beg, eolbyte, lim - beg);
636       if (!beg)
637         break;
638       newlines++;
639     }
640   totalnl = add_count (totalnl, newlines);
641   lastnl = lim;
642 }
643
644 /* Print the current filename.  */
645 static void
646 print_filename (void)
647 {
648   PR_SGR_START_IF(filename_color);
649   fputs(filename, stdout);
650   PR_SGR_END_IF(filename_color);
651 }
652
653 /* Print a character separator.  */
654 static void
655 print_sep (char sep)
656 {
657   PR_SGR_START_IF(sep_color);
658   fputc(sep, stdout);
659   PR_SGR_END_IF(sep_color);
660 }
661
662 /* Print a line number or a byte offset.  */
663 static void
664 print_offset (uintmax_t pos, int min_width, const char *color)
665 {
666   /* Do not rely on printf to print pos, since uintmax_t may be longer
667      than long, and long long is not portable.  */
668
669   char buf[sizeof pos * CHAR_BIT];
670   char *p = buf + sizeof buf;
671
672   do
673     {
674       *--p = '0' + pos % 10;
675       --min_width;
676     }
677   while ((pos /= 10) != 0);
678
679   /* Do this to maximize the probability of alignment across lines.  */
680   if (align_tabs)
681     while (--min_width >= 0)
682       *--p = ' ';
683
684   PR_SGR_START_IF(color);
685   fwrite (p, 1, buf + sizeof buf - p, stdout);
686   PR_SGR_END_IF(color);
687 }
688
689 /* Print a whole line head (filename, line, byte).  */
690 static void
691 print_line_head (char const *beg, char const *lim, int sep)
692 {
693   int pending_sep = 0;
694
695   if (out_file)
696     {
697       print_filename();
698       if (filename_mask)
699         pending_sep = 1;
700       else
701         fputc(0, stdout);
702     }
703
704   if (out_line)
705     {
706       if (lastnl < lim)
707         {
708           nlscan (beg);
709           totalnl = add_count (totalnl, 1);
710           lastnl = lim;
711         }
712       if (pending_sep)
713         print_sep(sep);
714       print_offset (totalnl, 4, line_num_color);
715       pending_sep = 1;
716     }
717
718   if (out_byte)
719     {
720       uintmax_t pos = add_count (totalcc, beg - bufbeg);
721 #if defined HAVE_DOS_FILE_CONTENTS
722       pos = dossified_pos (pos);
723 #endif
724       if (pending_sep)
725         print_sep(sep);
726       print_offset (pos, 6, byte_num_color);
727       pending_sep = 1;
728     }
729
730   if (pending_sep)
731     {
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.  */
736       if (align_tabs)
737         fputs("\t\b", stdout);
738
739       print_sep(sep);
740     }
741 }
742
743 static const char *
744 print_line_middle (const char *beg, const char *lim,
745                    const char *line_color, const char *match_color)
746 {
747   size_t match_size;
748   size_t match_offset;
749   const char *cur = beg;
750   const char *mid = NULL;
751
752   while (cur < lim
753          && ((match_offset = execute(beg, lim - beg, &match_size,
754                                      beg + (cur - beg))) != (size_t) -1))
755     {
756       char const *b = beg + match_offset;
757
758       /* Avoid matching the empty line at the end of the buffer. */
759       if (b == lim)
760         break;
761
762       /* Avoid hanging on grep --color "" foo */
763       if (match_size == 0)
764         {
765           /* Make minimal progress; there may be further non-empty matches.  */
766           /* XXX - Could really advance by one whole multi-octet character.  */
767           match_size = 1;
768           if (!mid)
769             mid = cur;
770         }
771       else
772         {
773           /* This function is called on a matching line only,
774              but is it selected or rejected/context?  */
775           if (only_matching)
776             print_line_head(b, lim, out_invert ? SEP_CHAR_REJECTED
777                                                : SEP_CHAR_SELECTED);
778           else
779             {
780               PR_SGR_START(line_color);
781               if (mid)
782                 {
783                   cur = mid;
784                   mid = NULL;
785                 }
786               fwrite (cur, sizeof (char), b - cur, stdout);
787             }
788
789           PR_SGR_START_IF(match_color);
790           fwrite (b, sizeof (char), match_size, stdout);
791           PR_SGR_END_IF(match_color);
792           if (only_matching)
793             fputs("\n", stdout);
794         }
795       cur = b + match_size;
796     }
797
798   if (only_matching)
799     cur = lim;
800   else if (mid)
801     cur = mid;
802
803   return cur;
804 }
805
806 static const char *
807 print_line_tail (const char *beg, const char *lim, const char *line_color)
808 {
809   size_t  eol_size;
810   size_t tail_size;
811
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;
815
816   if (tail_size > 0)
817     {
818       PR_SGR_START(line_color);
819       fwrite(beg, 1, tail_size, stdout);
820       beg += tail_size;
821       PR_SGR_END(line_color);
822     }
823
824   return beg;
825 }
826
827 static void
828 prline (char const *beg, char const *lim, int sep)
829 {
830   int matching;
831   const char *line_color;
832   const char *match_color;
833
834   if (!only_matching)
835     print_line_head(beg, lim, sep);
836
837   matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert;
838
839   if (color_option)
840     {
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;
846     }
847   else
848     line_color = match_color = NULL; /* Shouldn't be used.  */
849
850   if (   (only_matching && matching)
851       || (color_option  && (*line_color || *match_color)))
852     {
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);
856
857       /* FIXME: this test may be removable.  */
858       if (!only_matching && *line_color)
859         beg = print_line_tail(beg, lim, line_color);
860     }
861
862   if (!only_matching && lim > beg)
863     fwrite (beg, 1, lim - beg, stdout);
864
865   if (ferror (stdout))
866     error (0, errno, _("writing output"));
867
868   lastout = lim;
869
870   if (line_buffered)
871     fflush (stdout);
872 }
873
874 /* Print pending lines of trailing context prior to LIM. Trailing context ends
875    at the next matching line when OUTLEFT is 0.  */
876 static void
877 prpending (char const *lim)
878 {
879   if (!lastout)
880     lastout = bufbeg;
881   while (pending > 0 && lastout < lim)
882     {
883       char const *nl = memchr (lastout, eolbyte, lim - lastout);
884       size_t match_size;
885       --pending;
886       if (outleft
887           || ((execute(lastout, nl + 1 - lastout,
888                        &match_size, NULL) == (size_t) -1)
889               == !out_invert))
890         prline (lastout, nl + 1, SEP_CHAR_REJECTED);
891       else
892         pending = 0;
893     }
894 }
895
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.  */
898 static void
899 prtext (char const *beg, char const *lim, int *nlinesp)
900 {
901   static int used;      /* avoid printing SEP_STR_GROUP before any output */
902   char const *bp, *p;
903   char eol = eolbyte;
904   int i, n;
905
906   if (!out_quiet && pending > 0)
907     prpending (beg);
908
909   p = beg;
910
911   if (!out_quiet)
912     {
913       /* Deal with leading context crap. */
914
915       bp = lastout ? lastout : bufbeg;
916       for (i = 0; i < out_before; ++i)
917         if (p > bp)
918           do
919             --p;
920           while (p[-1] != eol);
921
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)
925         {
926           PR_SGR_START_IF(sep_color);
927           fputs (group_separator, stdout);
928           PR_SGR_END_IF(sep_color);
929           fputc('\n', stdout);
930         }
931
932       while (p < beg)
933         {
934           char const *nl = memchr (p, eol, beg - p);
935           nl++;
936           prline (p, nl, SEP_CHAR_REJECTED);
937           p = nl;
938         }
939     }
940
941   if (nlinesp)
942     {
943       /* Caller wants a line count. */
944       for (n = 0; p < lim && n < outleft; n++)
945         {
946           char const *nl = memchr (p, eol, lim - p);
947           nl++;
948           if (!out_quiet)
949             prline (p, nl, SEP_CHAR_SELECTED);
950           p = nl;
951         }
952       *nlinesp = n;
953
954       /* relying on it that this function is never called when outleft = 0.  */
955       after_last_match = bufoffset - (buflim - p);
956     }
957   else
958     if (!out_quiet)
959       prline (beg, lim, SEP_CHAR_SELECTED);
960
961   pending = out_quiet ? 0 : out_after;
962   used = 1;
963 }
964
965 static size_t
966 do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr)
967 {
968   size_t result;
969   const char *line_next;
970
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.
975
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);
985
986   for (line_next = buf; line_next < buf + size; )
987     {
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;
992       else
993         line_next = line_end + 1;
994
995       if (start_ptr && start_ptr >= line_end)
996         continue;
997
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;
1001     }
1002
1003   return (size_t) -1;
1004 }
1005
1006 /* Scan the specified portion of the buffer, matching lines (or
1007    between matching lines if OUT_INVERT is true).  Return a count of
1008    lines printed. */
1009 static int
1010 grepbuf (char const *beg, char const *lim)
1011 {
1012   int nlines, n;
1013   char const *p;
1014   size_t match_offset;
1015   size_t match_size;
1016
1017   nlines = 0;
1018   p = beg;
1019   while ((match_offset = do_execute(p, lim - p, &match_size,
1020                                     NULL)) != (size_t) -1)
1021     {
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. */
1025       if (b == lim)
1026         break;
1027       if (!out_invert)
1028         {
1029           prtext (b, endp, (int *) 0);
1030           nlines++;
1031           outleft--;
1032           if (!outleft || done_on_match)
1033             {
1034               if (exit_on_match)
1035                 exit (EXIT_SUCCESS);
1036               after_last_match = bufoffset - (buflim - endp);
1037               return nlines;
1038             }
1039         }
1040       else if (p < b)
1041         {
1042           prtext (p, b, &n);
1043           nlines += n;
1044           outleft -= n;
1045           if (!outleft)
1046             return nlines;
1047         }
1048       p = endp;
1049     }
1050   if (out_invert && p < lim)
1051     {
1052       prtext (p, lim, &n);
1053       nlines += n;
1054       outleft -= n;
1055     }
1056   return nlines;
1057 }
1058
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.  */
1062 static int
1063 grep (int fd, char const *file, struct stats *stats)
1064 {
1065   int nlines, i;
1066   int not_text;
1067   size_t residue, save;
1068   char oldc;
1069   char *beg;
1070   char *lim;
1071   char eol = eolbyte;
1072
1073   if (!reset (fd, file, stats))
1074     return 0;
1075
1076   if (file && directories == RECURSE_DIRECTORIES
1077       && S_ISDIR (stats->stat.st_mode))
1078     {
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;
1084     }
1085
1086   totalcc = 0;
1087   lastout = 0;
1088   totalnl = 0;
1089   outleft = max_count;
1090   after_last_match = 0;
1091   pending = 0;
1092
1093   nlines = 0;
1094   residue = 0;
1095   save = 0;
1096
1097   if (! fillbuf (save, stats))
1098     {
1099       if (! is_EISDIR (errno, file))
1100         {
1101           if (errno != EINVAL)
1102             suppressible_error (filename, errno);
1103         }
1104       return 0;
1105     }
1106
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)
1111     return 0;
1112   done_on_match += not_text;
1113   out_quiet += not_text;
1114
1115   for (;;)
1116     {
1117       lastnl = bufbeg;
1118       if (lastout)
1119         lastout = bufbeg;
1120
1121       beg = bufbeg + save;
1122
1123       /* no more data to scan (eof) except for maybe a residue -> break */
1124       if (beg == buflim)
1125         break;
1126
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).  */
1129       oldc = beg[-1];
1130       beg[-1] = eol;
1131       for (lim = buflim; lim[-1] != eol; lim--)
1132         continue;
1133       beg[-1] = oldc;
1134       if (lim == beg)
1135         lim = beg - residue;
1136       beg -= residue;
1137       residue = buflim - lim;
1138
1139       if (beg < lim)
1140         {
1141           if (outleft)
1142             nlines += grepbuf (beg, lim);
1143           if (pending)
1144             prpending (lim);
1145           if((!outleft && !pending) || (nlines && done_on_match && !out_invert))
1146             goto finish_grep;
1147         }
1148
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.  */
1152       i = 0;
1153       beg = lim;
1154       while (i < out_before && beg > bufbeg && beg != lastout)
1155         {
1156           ++i;
1157           do
1158             --beg;
1159           while (beg[-1] != eol);
1160         }
1161
1162       /* detect if leading context is discontinuous from last printed line.  */
1163       if (beg != lastout)
1164         lastout = 0;
1165
1166       /* Handle some details and read more data to scan.  */
1167       save = residue + lim - beg;
1168       if (out_byte)
1169         totalcc = add_count (totalcc, buflim - bufbeg - save);
1170       if (out_line)
1171         nlscan (beg);
1172       if (! fillbuf (save, stats))
1173         {
1174           if (! is_EISDIR (errno, file))
1175             suppressible_error (filename, errno);
1176           goto finish_grep;
1177         }
1178     }
1179   if (residue)
1180     {
1181       *buflim++ = eol;
1182       if (outleft)
1183         nlines += grepbuf (bufbeg + save - residue, buflim);
1184       if (pending)
1185         prpending (buflim);
1186     }
1187
1188  finish_grep:
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);
1193   return nlines;
1194 }
1195
1196 static int
1197 grepfile (char const *file, struct stats *stats)
1198 {
1199   int desc;
1200   int count;
1201   int status;
1202
1203   if (! file)
1204     {
1205       desc = 0;
1206       filename = label ? label : _("(standard input)");
1207     }
1208   else
1209     {
1210       if (stat (file, &stats->stat) != 0)
1211         {
1212           suppressible_error (file, errno);
1213           return 1;
1214         }
1215       if (only_files)
1216         {
1217           if (S_ISDIR (stats->stat.st_mode))
1218             {
1219               if (directories != RECURSE_DIRECTORIES)
1220                 return 1;
1221               if (lstat(file, &stats->stat) != 0)
1222                 return 1;
1223               if (!S_ISDIR (stats->stat.st_mode))
1224                 return 1;
1225             }
1226           else if (!S_ISREG (stats->stat.st_mode))
1227             return 1;
1228         }
1229       if (directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode))
1230         return 1;
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)))
1235         return 1;
1236       while ((desc = open (file, O_RDONLY)) < 0 && errno == EINTR)
1237         continue;
1238
1239       if (desc < 0)
1240         {
1241           int e = errno;
1242
1243           if (is_EISDIR (e, file) && directories == RECURSE_DIRECTORIES)
1244             {
1245 #if 0  /* DISABLED by only-files local modification option */
1246               if (stat (file, &stats->stat) != 0)
1247                 {
1248                   error (0, errno, "%s", file);
1249                   return 1;
1250                 }
1251 #endif
1252
1253               return grepdir (file, stats);
1254             }
1255
1256           if (!suppress_errors)
1257             {
1258               if (directories == SKIP_DIRECTORIES)
1259                 switch (e)
1260                   {
1261 #if defined EISDIR
1262                   case EISDIR:
1263                     return 1;
1264 #endif
1265                   case EACCES:
1266                     /* When skipping directories, don't worry about
1267                        directories that can't be opened.  */
1268                     if (isdir (file))
1269                       return 1;
1270                     break;
1271                   }
1272             }
1273
1274           suppressible_error (file, e);
1275           return 1;
1276         }
1277
1278       filename = file;
1279     }
1280
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".  */
1284   if (!isatty (desc))
1285     SET_BINARY (desc);
1286 #endif
1287
1288   count = grep (desc, file, stats);
1289   if (count < 0)
1290     status = count + 2;
1291   else
1292     {
1293       if (count_matches)
1294         {
1295           if (out_file)
1296             {
1297               print_filename();
1298               if (filename_mask)
1299                 print_sep(SEP_CHAR_SELECTED);
1300               else
1301                 fputc(0, stdout);
1302             }
1303           printf ("%d\n", count);
1304         }
1305
1306       status = !count;
1307       if (list_files == 1 - 2 * status)
1308         {
1309           print_filename();
1310           fputc('\n' & filename_mask, stdout);
1311         }
1312
1313       if (! file)
1314         {
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);
1320         }
1321       else
1322         while (close (desc) != 0)
1323           if (errno != EINTR)
1324             {
1325               error (0, errno, "%s", file);
1326               break;
1327             }
1328     }
1329
1330   return status;
1331 }
1332
1333 static int
1334 grepdir (char const *dir, struct stats const *stats)
1335 {
1336   struct stats const *ancestor;
1337   char *name_space;
1338   int status = 1;
1339   if ( excluded_directory_patterns &&
1340        excluded_file_name (excluded_directory_patterns, dir)  ) {
1341        return 1;
1342   }
1343
1344
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)
1351         {
1352           if (!suppress_errors)
1353             error (0, 0, _("warning: %s: %s"), dir,
1354                    _("recursive directory loop"));
1355           return 1;
1356         }
1357
1358   name_space = savedir (dir, stats->stat.st_size, included_patterns,
1359                         excluded_patterns, excluded_directory_patterns);
1360
1361   if (! name_space)
1362     {
1363       if (errno)
1364         suppressible_error (dir, errno);
1365       else
1366         xalloc_die ();
1367     }
1368   else
1369     {
1370       size_t dirlen = strlen (dir);
1371       int needs_slash = ! (dirlen == FILE_SYSTEM_PREFIX_LEN (dir)
1372                            || ISSLASH (dir[dirlen - 1]));
1373       char *file = NULL;
1374       char const *namep = name_space;
1375       struct stats child;
1376       child.parent = stats;
1377       out_file += !no_filenames;
1378       while (*namep)
1379         {
1380           size_t namelen = strlen (namep);
1381           file = xrealloc (file, dirlen + 1 + namelen + 1);
1382           strcpy (file, dir);
1383           file[dirlen] = '/';
1384           strcpy (file + dirlen + needs_slash, namep);
1385           namep += namelen + 1;
1386           status &= grepfile (file, &child);
1387         }
1388       out_file -= !no_filenames;
1389       free (file);
1390       free (name_space);
1391     }
1392
1393   return status;
1394 }
1395
1396 void usage (int status) __attribute__ ((noreturn));
1397 void
1398 usage (int status)
1399 {
1400   if (status != 0)
1401     {
1402       fprintf (stderr, _("Usage: %s [OPTION]... PATTERN [FILE]...\n"),
1403                program_name);
1404       fprintf (stderr, _("Try `%s --help' for more information.\n"),
1405                program_name);
1406     }
1407   else
1408     {
1409       printf (_("Usage: %s [OPTION]... PATTERN [FILE]...\n"), program_name);
1410       printf (_("\
1411 Search for PATTERN in each FILE or standard input.\n"));
1412       printf ("%s", gettext (before_options));
1413       printf (_("\
1414 Example: %s -i 'hello world' menu.h main.c\n\
1415 \n\
1416 Regexp selection and interpretation:\n"), program_name);
1417       if (matchers[1].name)
1418         printf (_("\
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. */
1424       printf (_("\
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"));
1431       printf (_("\
1432 \n\
1433 Miscellaneous:\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"));
1439       printf (_("\
1440 \n\
1441 Output control:\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\
1449 "));
1450       printf (_("\
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\
1456 "));
1457       printf (_("\
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\
1464 "));
1465       printf (_("\
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\
1470 "));
1471       printf (_("\
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"));
1480       printf (_("\
1481 \n\
1482 Context control:\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\
1486 "));
1487       printf (_("\
1488   -NUM                      same as --context=NUM\n\
1489       --color[=WHEN],\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\
1494 \n"));
1495       printf ("%s", _(after_options));
1496       printf (_("\
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"),
1504              stdout);
1505
1506     }
1507   exit (status);
1508 }
1509
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
1512    available.  */
1513 static void
1514 setmatcher (char const *m)
1515 {
1516   static char const *matcher;
1517   unsigned int i;
1518
1519   if (!m)
1520     {
1521       compile = matchers[0].compile;
1522       execute = matchers[0].execute;
1523       if (!matchers[1].name)
1524         matcher = matchers[0].name;
1525     }
1526
1527   else if (matcher)
1528     {
1529       if (matcher && STREQ (matcher, m))
1530         ;
1531
1532       else if (!matchers[1].name)
1533         error (EXIT_TROUBLE, 0, _("%s can only use the %s pattern syntax"),
1534                program_name, matcher);
1535       else
1536         error (EXIT_TROUBLE, 0, _("conflicting matchers specified"));
1537     }
1538
1539   else
1540     {
1541       for (i = 0; matchers[i].name; i++)
1542         if (STREQ (m, matchers[i].name))
1543           {
1544             compile = matchers[i].compile;
1545             execute = matchers[i].execute;
1546             matcher = m;
1547             return;
1548           }
1549
1550       error (EXIT_TROUBLE, 0, _("invalid matcher %s"), m);
1551     }
1552 }
1553
1554 static void
1555 set_limits(void)
1556 {
1557 #if defined HAVE_SETRLIMIT && defined RLIMIT_STACK
1558   struct rlimit rlim;
1559
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.
1564
1565      The test for HAVE_SETRLIMIT should go into `configure'.  */
1566   if (!getrlimit (RLIMIT_STACK, &rlim))
1567     {
1568       long newlim;
1569       extern long int re_max_failures; /* from regex.c */
1570
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)
1574         {
1575           newlim = rlim.rlim_max;
1576           re_max_failures = newlim / (2 * 20 * sizeof (char *));
1577         }
1578       if (rlim.rlim_cur < newlim)
1579         {
1580           rlim.rlim_cur = newlim;
1581           setrlimit (RLIMIT_STACK, &rlim);
1582         }
1583     }
1584 #endif
1585 }
1586
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).  */
1592 static int
1593 prepend_args (char const *options, char *buf, char **argv)
1594 {
1595   char const *o = options;
1596   char *b = buf;
1597   int n = 0;
1598
1599   for (;;)
1600     {
1601       while (c_isspace ((unsigned char) *o))
1602         o++;
1603       if (!*o)
1604         return n;
1605       if (argv)
1606         argv[n] = b;
1607       n++;
1608
1609       do
1610         if ((*b++ = *o++) == '\\' && *o)
1611           b[-1] = *o++;
1612       while (*o && ! c_isspace ((unsigned char) *o));
1613
1614       *b++ = '\0';
1615     }
1616 }
1617
1618 /* Prepend the whitespace-separated options in OPTIONS to the argument
1619    vector of a main program with argument count *PARGC and argument
1620    vector *PARGV.  */
1621 static void
1622 prepend_default_options (char const *options, int *pargc, char ***pargv)
1623 {
1624   if (options && *options)
1625     {
1626       char *buf = xmalloc (strlen (options) + 1);
1627       int prepended = prepend_args (options, buf, (char **) NULL);
1628       int argc = *pargc;
1629       char * const *argv = *pargv;
1630       char **pp = xmalloc ((prepended + argc + 1) * sizeof *pp);
1631       *pargc = prepended + argc;
1632       *pargv = pp;
1633       *pp++ = *argv++;
1634       pp += prepend_args (options, buf, pp);
1635       while ((*pp++ = *argv++))
1636         continue;
1637     }
1638 }
1639
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.  */
1644 static int
1645 get_nondigit_option (int argc, char *const *argv, int *default_context)
1646 {
1647   static int prev_digit_optind = -1;
1648   int opt, this_digit_optind, was_digit;
1649   char buf[sizeof (uintmax_t) * CHAR_BIT + 4];
1650   char *p = buf;
1651
1652   was_digit = 0;
1653   this_digit_optind = optind;
1654   while (opt = getopt_long (argc, (char **) argv, short_options, long_options,
1655                             NULL),
1656          '0' <= opt && opt <= '9')
1657     {
1658       if (prev_digit_optind != this_digit_optind || !was_digit)
1659         {
1660           /* Reset to start another context length argument.  */
1661           p = buf;
1662         }
1663       else
1664         {
1665           /* Suppress trivial leading zeros, to avoid incorrect
1666              diagnostic on strings like 00000000000.  */
1667           p -= buf[0] == '0';
1668         }
1669
1670       if (p == buf + sizeof buf - 4)
1671         {
1672           /* Too many digits.  Append "..." to make context_length_arg
1673              complain about "X...", where X contains the digits seen
1674              so far.  */
1675           strcpy (p, "...");
1676           p += 3;
1677           break;
1678         }
1679       *p++ = opt;
1680
1681       was_digit = 1;
1682       prev_digit_optind = this_digit_optind;
1683       this_digit_optind = optind;
1684     }
1685   if (p != buf)
1686     {
1687       *p = '\0';
1688       context_length_arg (buf, default_context);
1689     }
1690
1691   return opt;
1692 }
1693
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.  */
1698 static void
1699 parse_grep_colors (void)
1700 {
1701   const char *p;
1702   char *q;
1703   char *name;
1704   char *val;
1705
1706   p = getenv("GREP_COLORS"); /* Plural! */
1707   if (p == NULL || *p == '\0')
1708     return;
1709
1710   /* Work off a writable copy.  */
1711   q = xstrdup(p);
1712
1713   name = q;
1714   val = NULL;
1715   /* From now on, be well-formed or you're gone.  */
1716   for (;;)
1717     if (*q == ':' || *q == '\0')
1718       {
1719         char c = *q;
1720         struct color_cap *cap;
1721
1722         *q++ = '\0'; /* Terminate name or val.  */
1723         /* Empty name without val (empty cap)
1724          * won't match and will be ignored.  */
1725         for (cap = color_dict; cap->name; cap++)
1726           if (STREQ (cap->name, name))
1727             break;
1728         /* If name unknown, go on for forward compatibility.  */
1729         if (cap->name)
1730           {
1731             if (cap->var)
1732               {
1733                 if (val)
1734               *(cap->var) = val;
1735                 else
1736               error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1737                                 "needs a value (\"=...\"); skipped"), p, name);
1738           }
1739         else if (val)
1740           error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity "
1741                 "is boolean and cannot take a value (\"=%s\"); skipped"),
1742                 p, name, val);
1743       }
1744         if (cap->fct)
1745           {
1746             const char *err_str = cap->fct();
1747
1748             if (err_str)
1749               error(0, 0, _("in GREP_COLORS=\"%s\", the \"%s\" capacity %s"),
1750                     p, name, err_str);
1751           }
1752         if (c == '\0')
1753           return;
1754         name = q;
1755         val = NULL;
1756       }
1757     else if (*q == '=')
1758       {
1759         if (q == name || val)
1760           goto ill_formed;
1761         *q++ = '\0'; /* Terminate name.  */
1762         val = q; /* Can be the empty string.  */
1763       }
1764     else if (val == NULL)
1765       q++; /* Accumulate name.  */
1766     else if (*q == ';' || (*q >= '0' && *q <= '9'))
1767       q++; /* Accumulate val.  Protect the terminal from being sent crap.  */
1768     else
1769       goto ill_formed;
1770
1771  ill_formed:
1772   error(0, 0, _("stopped processing of ill-formed GREP_COLORS=\"%s\" "
1773                 "at remaining substring \"%s\""), p, q);
1774 }
1775
1776 int
1777 main (int argc, char **argv)
1778 {
1779   char *keys;
1780   size_t keycc, oldcc, keyalloc;
1781   int with_filenames;
1782   int opt, cc, status;
1783   int default_context;
1784   FILE *fp;
1785
1786   exit_failure = EXIT_TROUBLE;
1787   initialize_main (&argc, &argv);
1788   set_program_name (argv[0]);
1789   program_name = argv[0];
1790
1791   keys = NULL;
1792   keycc = 0;
1793   with_filenames = 0;
1794   eolbyte = '\n';
1795   filename_mask = ~0;
1796
1797   max_count = TYPE_MAXIMUM (off_t);
1798
1799   /* The value -1 means to use DEFAULT_CONTEXT. */
1800   out_after = out_before = -1;
1801   /* Default before/after context: chaged by -C/-NUM options */
1802   default_context = 0;
1803   /* Changed by -o option */
1804   only_matching = 0;
1805
1806   /* Internationalization. */
1807 #if defined HAVE_SETLOCALE
1808   setlocale (LC_ALL, "");
1809 #endif
1810 #if defined ENABLE_NLS
1811   bindtextdomain (PACKAGE, LOCALEDIR);
1812   textdomain (PACKAGE);
1813 #endif
1814
1815   exit_failure = EXIT_TROUBLE;
1816   atexit (close_stdout);
1817
1818   prepend_default_options (getenv ("GREP_OPTIONS"), &argc, &argv);
1819   setmatcher (NULL);
1820
1821   while ((opt = get_nondigit_option (argc, argv, &default_context)) != -1)
1822     switch (opt)
1823       {
1824       case 'A':
1825         context_length_arg (optarg, &out_after);
1826         break;
1827
1828       case 'B':
1829         context_length_arg (optarg, &out_before);
1830         break;
1831
1832       case 'C':
1833         /* Set output match context, but let any explicit leading or
1834            trailing amount specified with -A or -B stand. */
1835         context_length_arg (optarg, &default_context);
1836         break;
1837
1838       case 'D':
1839         if (STREQ (optarg, "read"))
1840           devices = READ_DEVICES;
1841         else if (STREQ (optarg, "skip"))
1842           devices = SKIP_DEVICES;
1843         else
1844           error (EXIT_TROUBLE, 0, _("unknown devices method"));
1845         break;
1846
1847       case 'E':
1848         setmatcher ("egrep");
1849         break;
1850
1851       case 'F':
1852         setmatcher ("fgrep");
1853         break;
1854
1855       case 'P':
1856         setmatcher ("perl");
1857         break;
1858
1859       case 'G':
1860         setmatcher ("grep");
1861         break;
1862
1863       case 'X': /* undocumented on purpose */
1864         setmatcher (optarg);
1865         break;
1866
1867       case 'H':
1868         with_filenames = 1;
1869         no_filenames = 0;
1870         break;
1871
1872       case 'I':
1873         binary_files = WITHOUT_MATCH_BINARY_FILES;
1874         break;
1875
1876       case 'O':
1877         only_files = 1;
1878         break;
1879
1880       case 'T':
1881         align_tabs = 1;
1882         break;
1883
1884       case 'U':
1885 #if defined HAVE_DOS_FILE_CONTENTS
1886         dos_use_file_type = DOS_BINARY;
1887 #endif
1888         break;
1889
1890       case 'u':
1891 #if defined HAVE_DOS_FILE_CONTENTS
1892         dos_report_unix_offset = 1;
1893 #endif
1894         break;
1895
1896       case 'V':
1897         show_version = 1;
1898         break;
1899
1900       case 'a':
1901         binary_files = TEXT_BINARY_FILES;
1902         break;
1903
1904       case 'b':
1905         out_byte = 1;
1906         break;
1907
1908       case 'c':
1909         count_matches = 1;
1910         break;
1911
1912       case 'd':
1913         directories = XARGMATCH ("--directories", optarg,
1914                                  directories_args, directories_types);
1915         break;
1916
1917       case 'e':
1918         cc = strlen (optarg);
1919         keys = xrealloc (keys, keycc + cc + 1);
1920         strcpy (&keys[keycc], optarg);
1921         keycc += cc;
1922         keys[keycc++] = '\n';
1923         break;
1924
1925       case 'f':
1926         fp = STREQ (optarg, "-") ? stdin : fopen (optarg, "r");
1927         if (!fp)
1928           error (EXIT_TROUBLE, errno, "%s", optarg);
1929         for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
1930           ;
1931         keys = xrealloc (keys, keyalloc);
1932         oldcc = keycc;
1933         while (!feof (fp)
1934                && (cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) > 0)
1935           {
1936             keycc += cc;
1937             if (keycc == keyalloc - 1)
1938               keys = xrealloc (keys, keyalloc *= 2);
1939           }
1940         if (fp != stdin)
1941           fclose(fp);
1942         /* Append final newline if file ended in non-newline. */
1943         if (oldcc != keycc && keys[keycc - 1] != '\n')
1944           keys[keycc++] = '\n';
1945         break;
1946
1947       case 'h':
1948         with_filenames = 0;
1949         no_filenames = 1;
1950         break;
1951
1952       case 'i':
1953       case 'y':                 /* For old-timers . . . */
1954         match_icase = 1;
1955         break;
1956
1957       case 'L':
1958         /* Like -l, except list files that don't contain matches.
1959            Inspired by the same option in Hume's gre. */
1960         list_files = -1;
1961         break;
1962
1963       case 'l':
1964         list_files = 1;
1965         break;
1966
1967       case 'm':
1968         {
1969           uintmax_t value;
1970           switch (xstrtoumax (optarg, 0, 10, &value, ""))
1971             {
1972             case LONGINT_OK:
1973               max_count = value;
1974               if (0 <= max_count && max_count == value)
1975                 break;
1976               /* Fall through.  */
1977             case LONGINT_OVERFLOW:
1978               max_count = TYPE_MAXIMUM (off_t);
1979               break;
1980
1981             default:
1982               error (EXIT_TROUBLE, 0, _("invalid max count"));
1983             }
1984         }
1985         break;
1986
1987       case 'n':
1988         out_line = 1;
1989         break;
1990
1991       case 'o':
1992         only_matching = 1;
1993         break;
1994
1995       case 'q':
1996         exit_on_match = 1;
1997         exit_failure = 0;
1998         break;
1999
2000       case 'R':
2001       case 'r':
2002         directories = RECURSE_DIRECTORIES;
2003         break;
2004
2005       case 's':
2006         suppress_errors = 1;
2007         break;
2008
2009       case 'v':
2010         out_invert = 1;
2011         break;
2012
2013       case 'w':
2014         match_words = 1;
2015         break;
2016
2017       case 'x':
2018         match_lines = 1;
2019         break;
2020
2021       case 'Z':
2022         filename_mask = 0;
2023         break;
2024
2025       case 'z':
2026         eolbyte = '\0';
2027         break;
2028
2029       case BINARY_FILES_OPTION:
2030         if (STREQ (optarg, "binary"))
2031           binary_files = BINARY_BINARY_FILES;
2032         else if (STREQ (optarg, "text"))
2033           binary_files = TEXT_BINARY_FILES;
2034         else if (STREQ (optarg, "without-match"))
2035           binary_files = WITHOUT_MATCH_BINARY_FILES;
2036         else
2037           error (EXIT_TROUBLE, 0, _("unknown binary-files type"));
2038         break;
2039
2040       case COLOR_OPTION:
2041         if(optarg) {
2042           if(!strcasecmp(optarg, "always") || !strcasecmp(optarg, "yes") ||
2043              !strcasecmp(optarg, "force"))
2044             color_option = 1;
2045           else if(!strcasecmp(optarg, "never") || !strcasecmp(optarg, "no") ||
2046                   !strcasecmp(optarg, "none"))
2047             color_option = 0;
2048           else if(!strcasecmp(optarg, "auto") || !strcasecmp(optarg, "tty") ||
2049                   !strcasecmp(optarg, "if-tty"))
2050             color_option = 2;
2051           else
2052             show_help = 1;
2053         } else
2054           color_option = 2;
2055         if (color_option == 2)
2056           {
2057             char const *t;
2058             if (isatty (STDOUT_FILENO) && (t = getenv ("TERM"))
2059                 && !STREQ (t, "dumb"))
2060               color_option = 1;
2061             else
2062               color_option = 0;
2063           }
2064         break;
2065
2066       case EXCLUDE_OPTION:
2067         if (!excluded_patterns)
2068           excluded_patterns = new_exclude ();
2069         add_exclude (excluded_patterns, optarg, EXCLUDE_WILDCARDS);
2070         break;
2071       case EXCLUDE_FROM_OPTION:
2072         if (!excluded_patterns)
2073           excluded_patterns = new_exclude ();
2074         if (add_exclude_file (add_exclude, excluded_patterns, optarg,
2075                               EXCLUDE_WILDCARDS, '\n') != 0)
2076           {
2077             error (EXIT_TROUBLE, errno, "%s", optarg);
2078           }
2079         break;
2080
2081       case EXCLUDE_DIRECTORY_OPTION:
2082         if (!excluded_directory_patterns)
2083           excluded_directory_patterns = new_exclude ();
2084         add_exclude (excluded_directory_patterns, optarg, EXCLUDE_WILDCARDS);
2085         break;
2086
2087       case INCLUDE_OPTION:
2088         if (!included_patterns)
2089           included_patterns = new_exclude ();
2090         add_exclude (included_patterns, optarg,
2091                      EXCLUDE_WILDCARDS | EXCLUDE_INCLUDE);
2092         break;
2093
2094       case GROUP_SEPARATOR_OPTION:
2095         group_separator = optarg;
2096         break;
2097
2098       case LINE_BUFFERED_OPTION:
2099         line_buffered = 1;
2100         break;
2101
2102       case LABEL_OPTION:
2103         label = optarg;
2104         break;
2105
2106       case MMAP_OPTION:
2107       case 0:
2108         /* long options */
2109         break;
2110
2111       default:
2112         usage (EXIT_TROUBLE);
2113         break;
2114
2115       }
2116
2117   /* POSIX.2 says that -q overrides -l, which in turn overrides the
2118      other output options.  */
2119   if (exit_on_match)
2120     list_files = 0;
2121   if (exit_on_match | list_files)
2122     {
2123       count_matches = 0;
2124       done_on_match = 1;
2125     }
2126   out_quiet = count_matches | done_on_match;
2127
2128   if (out_after < 0)
2129     out_after = default_context;
2130   if (out_before < 0)
2131     out_before = default_context;
2132
2133   if (color_option)
2134     {
2135       /* Legacy.  */
2136       char *userval = getenv ("GREP_COLOR");
2137       if (userval != NULL && *userval != '\0')
2138         selected_match_color = context_match_color = userval;
2139
2140       /* New GREP_COLORS has priority.  */
2141       parse_grep_colors();
2142     }
2143
2144   if (show_version)
2145     {
2146       version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, \
2147                    (char *) NULL);                                      \
2148       exit (EXIT_SUCCESS);                                              \
2149     }
2150
2151   if (show_help)
2152     usage (EXIT_SUCCESS);
2153
2154   if (keys)
2155     {
2156       if (keycc == 0)
2157         {
2158           /* No keys were specified (e.g. -f /dev/null).  Match nothing.  */
2159           out_invert ^= 1;
2160           match_lines = match_words = 0;
2161         }
2162       else
2163         /* Strip trailing newline. */
2164         --keycc;
2165     }
2166   else
2167     if (optind < argc)
2168       {
2169         /* A copy must be made in case of an xrealloc() or free() later.  */
2170         keycc = strlen(argv[optind]);
2171         keys = xmalloc(keycc + 1);
2172         strcpy(keys, argv[optind++]);
2173       }
2174     else
2175       usage (EXIT_TROUBLE);
2176
2177   set_limits();
2178   compile(keys, keycc);
2179   free (keys);
2180
2181   if ((argc - optind > 1 && !no_filenames) || with_filenames)
2182     out_file = 1;
2183
2184 #ifdef SET_BINARY
2185   /* Output is set to binary mode because we shouldn't convert
2186      NL to CR-LF pairs, especially when grepping binary files.  */
2187   if (!isatty (1))
2188     SET_BINARY (1);
2189 #endif
2190
2191   if (max_count == 0)
2192     exit (EXIT_FAILURE);
2193
2194   if (optind < argc)
2195     {
2196         status = 1;
2197         do
2198         {
2199           char *file = argv[optind];
2200           if ((included_patterns || excluded_patterns)
2201               && !isdir (file))
2202             {
2203               if (included_patterns
2204                   && excluded_file_name (included_patterns, file))
2205                 continue;
2206               if (excluded_patterns
2207                   && excluded_file_name (excluded_patterns, file))
2208                 continue;
2209             }
2210           status &= grepfile (STREQ (file, "-") ? (char *) NULL : file,
2211                               &stats_base);
2212         }
2213         while ( ++optind < argc);
2214     }
2215   else
2216     status = grepfile ((char *) NULL, &stats_base);
2217
2218   /* We register via atexit() to test stdout.  */
2219   exit (errseen ? EXIT_TROUBLE : status);
2220 }
2221 /* vim:set shiftwidth=2: */