Index: usr.bin/grep/grep.h =================================================================== --- usr.bin/grep/grep.h +++ usr.bin/grep/grep.h @@ -51,6 +51,10 @@ #define VERSION "2.5.1-FreeBSD" +#define COLOR_NONE 0 +#define COLOR_AUTO 1 +#define COLOR_ALWAYS 2 + #define GREP_FIXED 0 #define GREP_BASIC 1 #define GREP_EXTENDED 2 @@ -118,7 +122,7 @@ extern long long mlimit; extern char *label; extern const char *color; -extern int binbehave, devbehave, dirbehave, filebehave, grepbehave, linkbehave; +extern int binbehave, colorbehave, devbehave, dirbehave, filebehave, grepbehave, linkbehave; extern bool file_err, first, matchall, prev; extern int tail; Index: usr.bin/grep/grep.c =================================================================== --- usr.bin/grep/grep.c +++ usr.bin/grep/grep.c @@ -120,6 +120,7 @@ bool nullflag; /* --null */ char *label; /* --label */ const char *color; /* --color */ +int colorbehave = COLOR_NONE; /* --color=when: when to color */ int grepbehave = GREP_BASIC; /* -EFGP: type of the regex */ int binbehave = BINFILE_BIN; /* -aIU: handling of binary files */ int filebehave = FILE_STDIO; /* -JZ: normal, gzip or bzip2 file */ @@ -620,12 +621,15 @@ term = getenv("TERM"); if (isatty(STDOUT_FILENO) && term != NULL && - strcasecmp(term, "dumb") != 0) + strcasecmp(term, "dumb") != 0) { color = init_color("01;31"); + colorbehave = COLOR_AUTO; + } } else if (strcasecmp("always", optarg) == 0 || strcasecmp("yes", optarg) == 0 || strcasecmp("force", optarg) == 0) { color = init_color("01;31"); + colorbehave = COLOR_ALWAYS; } else if (strcasecmp("never", optarg) != 0 && strcasecmp("none", optarg) != 0 && strcasecmp("no", optarg) != 0) Index: usr.bin/grep/util.c =================================================================== --- usr.bin/grep/util.c +++ usr.bin/grep/util.c @@ -443,6 +443,7 @@ { size_t a = 0; int i, n = 0; + bool docolor = false; if (!hflag) { if (!nullflag) { @@ -470,16 +471,20 @@ /* --color and -o */ if ((oflag || color) && m > 0) { for (i = 0; i < m; i++) { + if(color && (colorbehave == COLOR_ALWAYS || + (!oflag && (matches[i].rm_so != 0 || (size_t)matches[i].rm_eo != line->len)))) + docolor = true; + if (!oflag) fwrite(line->dat + a, matches[i].rm_so - a, 1, stdout); - if (color) + if (docolor) fprintf(stdout, "\33[%sm\33[K", color); fwrite(line->dat + matches[i].rm_so, matches[i].rm_eo - matches[i].rm_so, 1, stdout); - if (color) + if (docolor) fprintf(stdout, "\33[m\33[K"); a = matches[i].rm_eo; if (oflag)