#!/usr/bin/python ## GPL by Peter Bengtsson, www.peterbe.com ## April 2005 __version__='1.5' import sys import re, os def string_center(s, width, padding): # only python2.4 has 'hej'.center(80, '+') # python2.3 can only do 'hej'.center(80) try: return s.center(width, padding) except TypeError: pad_space = (width - len(s)) / 2 return padding * pad_space + s + padding * pad_space semicompiled_regex = re.compile("\.(py|cpy|vpy)c", re.I) semicompiled = lambda line: semicompiled_regex.findall(line) junk_regex = re.compile(r"\btags:", re.I) isJunk = lambda line: junk_regex.findall(line) backupfile_regex = re.compile("\.\w+~|\.bak:|\.bak\d:|\.svn|/\.#\w+", re.I) backupfile = lambda line: backupfile_regex.findall(line) result = sys.stdin.read() try: LINES_EITHER_SIDE = open(os.path.expanduser('~/.Grepexpansion')).read() LINES_EITHER_SIDE = int(LINES_EITHER_SIDE.strip()) assert LINES_EITHER_SIDE >= 0 and LINES_EITHER_SIDE < 100 except: LINES_EITHER_SIDE = 0 try: arged_lines_either_side = int(sys.argv[1]) assert arged_lines_either_side >0 if arged_lines_either_side != LINES_EITHER_SIDE: try: f=open(os.path.expanduser('~/.Grepexpansion'), 'w') f.write(str(arged_lines_either_side)) f.close() except: pass LINES_EITHER_SIDE = arged_lines_either_side except IndexError: pass except: print >>sys.stderr, "First argument must be a positive integer" previous_filename = None for line in result.splitlines(): if semicompiled(line): continue if backupfile(line): continue if isJunk(line): continue if line.startswith('Binary file'): continue _either_side = LINES_EITHER_SIDE + 1 try: file, lineno = line.split(':')[:2] except: print line continue try: lineno = int(lineno) except ValueError: print >>sys.stderr, "Lineno not an int: %r" % lineno raise if previous_filename == file: print "" else: print string_center(" %s " % file, 80, '-') previous_filename = file content = open(file).read().splitlines() for i in range(max(lineno-_either_side,0)+1, min(lineno+_either_side, len(content)-1), 1): # print i, lineno star = " " if i == lineno: star = "*" print "%s%s| %s" % (i, star, content[i-1])