Navigating Python modules using ctags in Vim?

I use Vim with ctags for Python, and it works very well for classes, fields, etc., but what does not seem to include are Python file names or module names. Is it possible? I would rather type ta <module>in to go to the module, rather than navigate through the levels using a file browser such as NERDtree, and I'm very used to doing this in Java, which works because class names are file names.

+4
source share
2 answers

If you are creating a tag file using violent ctags (is there any other way?), Try adding a parameter --extra=+f. See the Help page at http://ctags.sourceforge.net/ctags.html#OPTIONS for more details .

+6
source

Exuberant tags (c --extra=+f) generates tags for python file names (e.g. my_module.py), but not for module name (e.g. my_module). I ended up creating a modified version of the ptags script. Save the following in a file with a name ptagssomewhere in your path and make it executable:

#! /usr/bin/env python

# ptags
#
# Create a tags file for Python programs, usable with vi.
# Tagged are:
# - functions (even inside other defs or classes)
# - classes
# - filenames
# Warns about files it cannot open.
# No warnings about duplicate tags.

import sys, re, os
import argparse

tags = []    # Modified global variable!

def main():
    for root, folders, files in os.walk(args.folder_to_index):
        for filename in files:
            if filename.endswith('.py'):
                full_path = os.path.join(root, filename)
                treat_file(full_path)
        if not args.recursive:
            break

    if tags:
        fp = open(args.ctags_filename, 'w')
        tags.sort()
        for s in tags: fp.write(s)

expr = '^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
matcher = re.compile(expr)

def treat_file(filename):
    try:
        fp = open(filename, 'r')
    except:
        sys.stderr.write('Cannot open %s\n' % filename)
        return
    base = os.path.basename(filename)
    if base[-3:] == '.py':
        base = base[:-3]
    s = base + '\t' + filename + '\t' + '1\n'
    tags.append(s)
    while 1:
        line = fp.readline()
        if not line:
            break
        m = matcher.match(line)
        if m:
            content = m.group(0)
            name = m.group(2)
            s = name + '\t' + filename + '\t/^' + content + '/\n'
            tags.append(s)

if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('-f', '--ctags-filename', type=str, default='tags')
    p.add_argument('-R', '--recursive', action='store_true')
    p.add_argument('folder_to_index', type=str, default='.')
    args = p.parse_args()
    main()

Now run the following command to create the tag file by recursively processing the current directory:

ptags -R -f tags_file_to_create /path/to/index

0
source

Source: https://habr.com/ru/post/1542353/


All Articles