Guido van Rossum | f06ee5f | 1996-11-27 19:52:01 +0000 | [diff] [blame] | 1 | #! /usr/bin/env python |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 2 | |
| 3 | # ptags |
| 4 | # |
| 5 | # Create a tags file for Python programs, usable with vi. |
| 6 | # Tagged are: |
| 7 | # - functions (even inside other defs or classes) |
| 8 | # - classes |
| 9 | # - filenames |
| 10 | # Warns about files it cannot open. |
| 11 | # No warnings about duplicate tags. |
| 12 | |
| 13 | import sys |
Guido van Rossum | f2e1cfb | 1992-08-31 10:53:53 +0000 | [diff] [blame] | 14 | import regex |
| 15 | import os |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 16 | |
| 17 | tags = [] # Modified global variable! |
| 18 | |
| 19 | def main(): |
| 20 | args = sys.argv[1:] |
| 21 | for file in args: treat_file(file) |
| 22 | if tags: |
| 23 | fp = open('tags', 'w') |
| 24 | tags.sort() |
| 25 | for s in tags: fp.write(s) |
| 26 | |
Guido van Rossum | f2e1cfb | 1992-08-31 10:53:53 +0000 | [diff] [blame] | 27 | |
| 28 | expr = '^[ \t]*\(def\|class\)[ \t]+\([a-zA-Z0-9_]+\)[ \t]*[:(]' |
| 29 | matcher = regex.compile(expr) |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 30 | |
| 31 | def treat_file(file): |
| 32 | try: |
| 33 | fp = open(file, 'r') |
| 34 | except: |
| 35 | print 'Cannot open', file |
| 36 | return |
Guido van Rossum | f2e1cfb | 1992-08-31 10:53:53 +0000 | [diff] [blame] | 37 | base = os.path.basename(file) |
Guido van Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 38 | if base[-3:] == '.py': base = base[:-3] |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 39 | s = base + '\t' + file + '\t' + '1\n' |
| 40 | tags.append(s) |
| 41 | while 1: |
| 42 | line = fp.readline() |
| 43 | if not line: break |
Guido van Rossum | f2e1cfb | 1992-08-31 10:53:53 +0000 | [diff] [blame] | 44 | if matcher.search(line) >= 0: |
| 45 | (a, b), (a1, b1), (a2, b2) = matcher.regs[:3] |
Guido van Rossum | ec758ea | 1991-06-04 20:36:54 +0000 | [diff] [blame] | 46 | name = line[a2:b2] |
| 47 | s = name + '\t' + file + '\t/^' + line[a:b] + '/\n' |
| 48 | tags.append(s) |
| 49 | |
| 50 | main() |