2

Let's say I need reverse function in my newly created hello_world.py file and I have not imported it yet:

url = reverse('hell-world')

I would love to go onto the reverse name, press VIM binding and get from django.urls import reverse line inserted in the beginning of the file, e.g.:

from django.urls import reverse

url = reverse('hello-world')

I have heard about ropevim, python-mode VIM plugins, however I have not managed to make them work as I described above.

2
  • What if another module implements a reverse function as well? Or you want to limit yourself to django?
    – tejasvi88
    Feb 11, 2021 at 12:15
  • A list of import options should be provided to choose from.
    – niekas
    Feb 11, 2021 at 14:23

1 Answer 1

1

You can create a function for that (easier with python :h if_pyth).

# intial setup
import inspect`
potential_modules = ['django', 'sys', 'os']
for module_name in potential_modules:
    exec(f"from {module_name} import *")
def add_import_on_trigger()
    func_name = get_the_word_under_cursor();
    module_name = inspect.getmodule(func_name)
    import_statement = f"from {module_name} import {func_name}"
    add_import_statement_at_the_buffer_top()
1
  • 2
    word under cursor will be expand('<cword>'). Can use vim.eval(). Adding the import statement in the right spot is harder, but something like execute '$?^import\|^from? put ='.import_statement might do it
    – D. Ben Knoble
    Feb 11, 2021 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.