pythonvimeditor

python in vim: 'gf' on import line


In vim pressing gf opens the file under the cursor. In python, modules are imported with '.' between the file names where the path name would contain '/'. So suffixesadd alone does not suffice. What is the best solution to get the gf functionality in Vim on import lines in python, such as

import hwut.auxiliary.file_system as fs

I would like to set the cursor on 'auxiliary', type 'gf' and get the file opened.


Solution

  • make sure you have

    filetype plugin on
    

    in your vimrc. Then the gf on python import should work automatically.

    update for OP's comment

    If you enabled filetype plugin and the default python.vim ftplugin is gonna be loaded. There the dot . in fname will be replaced by /.

    setlocal include=^\\s*\\(from\\\|import\\)
    setlocal includeexpr=substitute(v:fname,'\\.','/','g')
    

    You can check if your python file hasn't set ft correctly, or you didn't enable filetype in vim.

    On my Archlinux distribution with vim80, the python.vim is located at:

    /usr/share/vim/vim80/ftplugin
    

    You can get your path by checking $VIMRUNTIME var in vim.