builtin-grep: support -w (--word-regexp).
Signed-off-by: Junio C Hamano <junkio@cox.net>
Junio C Hamano committed
May 2, 2006 at 15:40 UTC
7839a25eab7177024b809fbb3796907e3eed17c1
1 file changed
+30
builtin-grep.c
+30
@@ -89,6 +89,7 @@ struct grep_opt {
89
unsigned invert:1;
90
unsigned name_only:1;
91
unsigned count:1;
92
+ unsigned word_regexp:1;
93
int regflags;
94
unsigned pre_context;
95
unsigned post_context;
@@ -128,6 +129,11 @@ static char *end_of_line(char *cp, unsigned long *left)
129
return cp;
130
}
131
132
+static int word_char(char ch)
133
+{
134
+ return isalnum(ch) || ch == '_';
135
+}
136
+
137
static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
138
const char *name, unsigned lno, char sign)
139
{
@@ -171,6 +177,25 @@ static int grep_buffer(struct grep_opt *opt, const char *name,
177
regex_t *exp = &p->regexp;
178
hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
179
pmatch, 0);
180
+
181
+ if (hit && opt->word_regexp) {
182
+ /* Match beginning must be either
183
+ * beginning of the line, or at word
184
+ * boundary (i.e. the last char must
185
+ * not be alnum or underscore).
186
+ */
187
+ if ((pmatch[0].rm_so < 0) ||
188
+ (eol - bol) <= pmatch[0].rm_so ||
189
+ (pmatch[0].rm_eo < 0) ||
190
+ (eol - bol) < pmatch[0].rm_eo)
191
+ die("regexp returned nonsense");
192
+ if (pmatch[0].rm_so != 0 &&
193
+ word_char(bol[pmatch[0].rm_so-1]))
194
+ continue; /* not a word boundary */
195
+ if ((eol-bol) < pmatch[0].rm_eo &&
196
+ word_char(bol[pmatch[0].rm_eo]))
197
+ continue; /* not a word boundary */
198
+ }
199
if (hit)
200
break;
201
}
@@ -461,6 +486,11 @@ int cmd_grep(int argc, const char **argv, char **envp)
486
opt.count = 1;
487
continue;
488
}
489
+ if (!strcmp("-w", arg) ||
490
+ !strcmp("--word-regexp", arg)) {
491
+ opt.word_regexp = 1;
492
+ continue;
493
+ }
494
if (!strncmp("-A", arg, 2) ||
495
!strncmp("-B", arg, 2) ||
496
!strncmp("-C", arg, 2) ||