nimgrep: count the number of matches

This commit is contained in:
Andreas Rumpf 2018-04-24 20:12:13 +02:00
commit e50f69bc87

View file

@ -128,7 +128,7 @@ proc highlight(s, match, repl: string, t: tuple[first, last: int],
stdout.write("\n") stdout.write("\n")
stdout.flushFile() stdout.flushFile()
proc processFile(pattern; filename: string) = proc processFile(pattern; filename: string; counter: var int) =
var filenameShown = false var filenameShown = false
template beforeHighlight = template beforeHighlight =
if not filenameShown and optVerbose notin options and not oneline: if not filenameShown and optVerbose notin options and not oneline:
@ -166,6 +166,7 @@ proc processFile(pattern; filename: string) =
var wholeMatch = buffer.substr(t.first, t.last) var wholeMatch = buffer.substr(t.first, t.last)
beforeHighlight() beforeHighlight()
inc counter
if optReplace notin options: if optReplace notin options:
highlight(buffer, wholeMatch, "", t, filename, line, showRepl=false) highlight(buffer, wholeMatch, "", t, filename, line, showRepl=false)
else: else:
@ -241,17 +242,17 @@ proc styleInsensitive(s: string): string =
addx() addx()
else: addx() else: addx()
proc walker(pattern; dir: string) = proc walker(pattern; dir: string; counter: var int) =
for kind, path in walkDir(dir): for kind, path in walkDir(dir):
case kind case kind
of pcFile: of pcFile:
if extensions.len == 0 or path.hasRightExt(extensions): if extensions.len == 0 or path.hasRightExt(extensions):
processFile(pattern, path) processFile(pattern, path, counter)
of pcDir: of pcDir:
if optRecursive in options: if optRecursive in options:
walker(pattern, path) walker(pattern, path, counter)
else: discard else: discard
if existsFile(dir): processFile(pattern, dir) if existsFile(dir): processFile(pattern, dir, counter)
proc writeHelp() = proc writeHelp() =
stdout.write(Usage) stdout.write(Usage)
@ -321,6 +322,7 @@ if optStdin in options:
if pattern.len == 0: if pattern.len == 0:
writeHelp() writeHelp()
else: else:
var counter = 0
if filenames.len == 0: if filenames.len == 0:
filenames.add(os.getCurrentDir()) filenames.add(os.getCurrentDir())
if optRegex notin options: if optRegex notin options:
@ -332,7 +334,7 @@ else:
pattern = "\\i " & pattern pattern = "\\i " & pattern
let pegp = peg(pattern) let pegp = peg(pattern)
for f in items(filenames): for f in items(filenames):
walker(pegp, f) walker(pegp, f, counter)
else: else:
var reflags = {reStudy, reExtended} var reflags = {reStudy, reExtended}
if optIgnoreStyle in options: if optIgnoreStyle in options:
@ -343,5 +345,6 @@ else:
reflags.incl reIgnoreCase reflags.incl reIgnoreCase
let rep = re(pattern, reflags) let rep = re(pattern, reflags)
for f in items(filenames): for f in items(filenames):
walker(rep, f) walker(rep, f, counter)
if not oneline:
stdout.write($counter & " matches\n")