blob: f4666512b70ea5fdd713a8518c376186f931e817 [file] [log] [blame]
Guido van Rossum217a5fa1990-12-26 15:40:07 +00001# 'grep'
2
Guido van Rossum5fca8a11991-12-31 00:00:35 +00003import regex
4from regex_syntax import *
Guido van Rossum217a5fa1990-12-26 15:40:07 +00005import string
6
Guido van Rossume9cde311992-01-12 23:33:52 +00007opt_show_where = 0
8opt_show_filename = 0
9opt_show_lineno = 1
Guido van Rossum5fca8a11991-12-31 00:00:35 +000010
Guido van Rossum6a1f0891992-04-06 14:03:53 +000011def grep(pat, *files):
Guido van Rossume9cde311992-01-12 23:33:52 +000012 return ggrep(RE_SYNTAX_GREP, pat, files)
Guido van Rossum5fca8a11991-12-31 00:00:35 +000013
Guido van Rossum6a1f0891992-04-06 14:03:53 +000014def egrep(pat, *files):
Guido van Rossume9cde311992-01-12 23:33:52 +000015 return ggrep(RE_SYNTAX_EGREP, pat, files)
Guido van Rossum5fca8a11991-12-31 00:00:35 +000016
Guido van Rossum6a1f0891992-04-06 14:03:53 +000017def emgrep(pat, *files):
Guido van Rossume9cde311992-01-12 23:33:52 +000018 return ggrep(RE_SYNTAX_EMACS, pat, files)
19
20def ggrep(syntax, pat, files):
21 if len(files) == 1 and type(files[0]) == type([]):
22 files = files[0]
23 global opt_show_filename
24 opt_show_filename = (len(files) != 1)
Guido van Rossum5fca8a11991-12-31 00:00:35 +000025 syntax = regex.set_syntax(syntax)
26 try:
27 prog = regex.compile(pat)
28 finally:
29 syntax = regex.set_syntax(syntax)
Guido van Rossume9cde311992-01-12 23:33:52 +000030 for filename in files:
31 fp = open(filename, 'r')
32 lineno = 0
33 while 1:
34 line = fp.readline()
35 if not line: break
36 lineno = lineno + 1
37 if prog.search(line) >= 0:
38 showline(filename, lineno, line, prog)
39 fp.close()
40
41def showline(filename, lineno, line, prog):
42 if line[-1:] == '\n': line = line[:-1]
43 if opt_show_lineno:
44 prefix = string.rjust(`lineno`, 3) + ': '
45 else:
46 prefix = ''
47 if opt_show_filename:
48 prefix = filename + ': ' + prefix
49 print prefix + line
50 if opt_show_where:
51 start, end = prog.regs()[0]
52 line = line[:start]
53 if '\t' not in line:
54 prefix = ' ' * (len(prefix) + start)
55 else:
56 prefix = ' ' * len(prefix)
57 for c in line:
58 if c <> '\t': c = ' '
59 prefix = prefix + c
60 if start == end: prefix = prefix + '\\'
61 else: prefix = prefix + '^'*(end-start)
62 print prefix