Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making gf match python imports

Tags:

vim

I'd like the gf command to work with Python imports, but am having trouble with the from foo.bar import baz style of imports.

The basic problem is that I can't figure out how to make include or includexpr match the text between "from" and "import" and then add the text after "import". Vim seems to refuse to match past any whitespace, let alone allow backreferences to concat the two parts of the matched text.

Is this possible?

like image 806
Richard Levasseur Avatar asked May 13 '26 21:05

Richard Levasseur


1 Answers

Yes, it's not only possible but the built-in Python ftplugin already handles all that for you:

  • Find includes (irrelevant for gf):

    setlocal include=^\\s*\\(from\\\|import\\)
    
  • Turn includes into paths (relevant for gf):

    setlocal includeexpr=substitute(substitute(substitute(
          \v:fname,
          \b:grandparent_match,b:grandparent_sub,''),
          \b:parent_match,b:parent_sub,''),
          \b:child_match,b:child_sub,'g')
    
  • Add the correct extension (relevant for gf):

    setlocal suffixesadd=.py
    

Just make sure you have either of the following lines in your vimrc:

filetype plugin on
filetype plugin indent on
filetype indent plugin on

to enable the ftplugin mechanism.

like image 60
romainl Avatar answered May 17 '26 09:05

romainl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!