A Vim mapping for opening virtualenv files

Here’s a useful command-mode mapping for Python development:

" ~/.vim/ftplugin/python.vim

function! VirtualEnvSitePackagesFolder()
    " Try a few candidate Pythons to see which this virtualenv uses.
    for python in ["python3.7", "python3.8", "python3.9"]
        let candidate = $VIRTUAL_ENV . "/lib/" . python
        if isdirectory(candidate)
            return candidate . "/site-packages/"

    return ""

cnoremap %v <C-R>=VirtualEnvSitePackagesFolder()<cr>

In command-mode, %v will expand to the path of your virtualenv’s site-packages folder in, which makes it easy to quickly open a third-party module.

For example, you type:

:e %v

and it expands to:

:e /Users/jimmy/.virtualenvs/myproject/lib/python3.8/site-packages/

from which it’s easy to open the third-party module you’re interested in.


Something wrong? Suggest an improvement or add a comment (see article history)
Tagged with: Vim
Filed in: tips

Previous: Setting up a 2020 MacBook Pro for Python development

Copyright © 2005-2021 David Winterbottom
Content licensed under CC BY-NC-SA 4.0.