I love Vim ❤️ , especially NeoVim. I can write pages about why you should love it too.
Python, being my daily driver makes the Vim Integration a match made in heaven ❤️
There is one thing that annoyed me when I was working with Vim and Python. The
Since I don't want my python environment to be like one of the infected monsters from The Last of Us, I use
venvs for my projects. You should use them too!
However, when if I boot my NeoVim from the Venv activated session, NeoVim did not recognize the Venv specific imports.
Some extensions also conflicted with the between the local and the global python config.
I tried looking for many extensions that would handle it automatically for me, but all of them wanted me to manually activate the
venvs from inside the Vim session.
I wouldn't have become a software developer if I wanted to do everything myself, right? *cries internally*
This is when I decided to write the plugin myself.
With all the learning curves associated with Vim, a plugin always felt like the magic package which only TPope curated.
But surprisingly, writing a plugin is a fairly simple process.
----Plugin-Folder/ --plugins/ --xyz.vim --README.md
Vim has certain predefined files/folders which it looks out for while executing a plugin. You need to have a
plugins folder and a
README file. Vim will automatically execute all the files ending with
*.vim in the
The goal of this plugin was to see add the venv configs in the vim session if the Virtual Environment was enabled for the terminal session.
This in theory is fairly simple.
- Check if the venv is activated.
- Update the venv config from the
While reading the vim plugin docs, I found out that we can write vim plugins in Python too. This made it even better. 🤤
Here is the code for the entire plugin:
python3 << EOF import os import subprocess if "VIRTUAL_ENV" in os.environ: project_base_dir = os.environ["VIRTUAL_ENV"] script = os.path.join(project_base_dir, "bin/activate") pipe = subprocess.Popen(". %s; env" % script, stdout=subprocess.PIPE, shell=True) output = pipe.communicate().decode('utf8').splitlines() env = dict((line.split("=", 1) for line in output)) os.environ.update(env) EOF
This code searches for the
activate shell script which is commonly found in the
venv/bin, executes it, and updates the config in the session.
- You can install the extension using Vim Plug or any other plugin manager, e.g.
- You can check out the plugin on GitHub through this link: https://github.com/sansyrox/vim-python-virtualenv
Any feedback is much appreciated! ✨
Connect with me on twitter :)
"If Life is a Search for Meaning, it better be Binary Search."— Sanskar Jethi (@sansyrox ) October 8, 2020