Commit | Line | Data |
---|---|---|
86530b38 AT |
1 | # 'grep' |
2 | ||
3 | import regex | |
4 | from regex_syntax import * | |
5 | ||
6 | opt_show_where = 0 | |
7 | opt_show_filename = 0 | |
8 | opt_show_lineno = 1 | |
9 | ||
10 | def grep(pat, *files): | |
11 | return ggrep(RE_SYNTAX_GREP, pat, files) | |
12 | ||
13 | def egrep(pat, *files): | |
14 | return ggrep(RE_SYNTAX_EGREP, pat, files) | |
15 | ||
16 | def emgrep(pat, *files): | |
17 | return ggrep(RE_SYNTAX_EMACS, pat, files) | |
18 | ||
19 | def ggrep(syntax, pat, files): | |
20 | if len(files) == 1 and type(files[0]) == type([]): | |
21 | files = files[0] | |
22 | global opt_show_filename | |
23 | opt_show_filename = (len(files) != 1) | |
24 | syntax = regex.set_syntax(syntax) | |
25 | try: | |
26 | prog = regex.compile(pat) | |
27 | finally: | |
28 | syntax = regex.set_syntax(syntax) | |
29 | for filename in files: | |
30 | fp = open(filename, 'r') | |
31 | lineno = 0 | |
32 | while 1: | |
33 | line = fp.readline() | |
34 | if not line: break | |
35 | lineno = lineno + 1 | |
36 | if prog.search(line) >= 0: | |
37 | showline(filename, lineno, line, prog) | |
38 | fp.close() | |
39 | ||
40 | def pgrep(pat, *files): | |
41 | if len(files) == 1 and type(files[0]) == type([]): | |
42 | files = files[0] | |
43 | global opt_show_filename | |
44 | opt_show_filename = (len(files) != 1) | |
45 | import re | |
46 | prog = re.compile(pat) | |
47 | for filename in files: | |
48 | fp = open(filename, 'r') | |
49 | lineno = 0 | |
50 | while 1: | |
51 | line = fp.readline() | |
52 | if not line: break | |
53 | lineno = lineno + 1 | |
54 | if prog.search(line): | |
55 | showline(filename, lineno, line, prog) | |
56 | fp.close() | |
57 | ||
58 | def showline(filename, lineno, line, prog): | |
59 | if line[-1:] == '\n': line = line[:-1] | |
60 | if opt_show_lineno: | |
61 | prefix = `lineno`.rjust(3) + ': ' | |
62 | else: | |
63 | prefix = '' | |
64 | if opt_show_filename: | |
65 | prefix = filename + ': ' + prefix | |
66 | print prefix + line | |
67 | if opt_show_where: | |
68 | start, end = prog.regs()[0] | |
69 | line = line[:start] | |
70 | if '\t' not in line: | |
71 | prefix = ' ' * (len(prefix) + start) | |
72 | else: | |
73 | prefix = ' ' * len(prefix) | |
74 | for c in line: | |
75 | if c != '\t': c = ' ' | |
76 | prefix = prefix + c | |
77 | if start == end: prefix = prefix + '\\' | |
78 | else: prefix = prefix + '^'*(end-start) | |
79 | print prefix |