git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH] grep: fix colouring of matches with zero length

From
René Scharfe <rene.scharfe@lsrfire.ath.cx>
Date
Jun 1, 2009, 16:46 UTC
Message-ID
<4A2405DA.7010801@lsrfire.ath.cx>

The first hunk fixes match colouring if the patterns is the empty string. Such a pattern matches the whole line, but fixmatch() sets the end offset to the same value as the start offset. Special case the empty pattern in match_one_pattern() and thus avoid calling fixmatch().

The second hunk of the patch makes sure that grep match colouring doesn't get stuck in an infinite loop if the length of a match is zero. The rest of the line is simply printed without colouring. Even though the empty pattern string doesn't result in empty matches any more, this defensive measure catches unknown cases.

Signed-off-by: Rene Scharfe <rene.scharfe@lsrfire.ath.cx>
---
 grep.c |    8 +++++++-
 1 files changed, 7 insertions(+), 1 deletions(-)
diff --git a/grep.c b/grep.c
index cc6d5b0..745b3c0 100644
--- a/grep.c
+++ b/grep.c
@@ -324,7 +324,11 @@ static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
 	}
 
  again:
-	if (p->fixed)
+	if (p->pattern[0] == '\0') {
+		hit = 1;
+		pmatch[0].rm_so = 0;
+		pmatch[0].rm_eo = eol - bol;
+	} else if (p->fixed)
 		hit = !fixmatch(p->pattern, bol, pmatch);
 	else
 		hit = !regexec(&p->regexp, bol, 1, pmatch, eflags);
@@ -500,6 +504,8 @@ static void show_line(struct grep_opt *opt, char *bol, char *eol,
 
 		*eol = '\0';
 		while (next_match(opt, bol, eol, ctx, &match, eflags)) {
+			if (match.rm_so == match.rm_eo)
+				break;
 			printf("%.*s%s%.*s%s",
 			       (int)match.rm_so, bol,
 			       opt->color_match,
-- 
1.6.3.1
Next: Junio C Hamano
Message 1 of 3 in “grep: fix colouring of matches with zero length”
  1. grep: fix colouring of matches with zero lengthRené Scharfe, Jun 1, 2009
  2. Junio C HamanoJun 1, 2009
  3. René ScharfeJun 1, 2009

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.