GithubHelp home page GithubHelp logo

jmcantrell / vim-virtualenv Goto Github PK

View Code? Open in Web Editor NEW
599.0 599.0 51.0 48 KB

Vim plugin for working with python virtualenvs

Home Page: http://www.vim.org/scripts/script.php?script_id=3486

License: Do What The F*ck You Want To Public License

Python 25.53% Vim Script 74.47%

vim-virtualenv's Introduction

virtualenv.vim

When using :python or :!python, it will only have access to the environment outside of any virtualenvs. If you're working with packages that are only installed in a virtualenv, they will not be available to Vim.

Until now! The virtualenv.vim plugin will modify python's sys.path and the $PATH environment variable so that anything done with :python or :!python will behave like you would expect for the chosen virtualenv.

If compiled with python support, Vim will have a :python command, but this will be tied to whatever version is the default on your system. If this is the version of python that you use, or you're using a Linux distribution with a sensible package manager (like Debian or Ubuntu), you likely will not have to do anything more than install the plugin. If not, then you will likely have to recompile vim with your version of python.

Usage examples

Deactivate the current virtualenv

:VirtualEnvDeactivate

List all virtualenvs

:VirtualEnvList

Activate the 'spam' virtualenv

:VirtualEnvActivate spam

If you're unsure which one to activate, you could always use tab completion

:VirtualEnvActivate <tab>

If the shell that started vim had $VIRTUAL_ENV set, omitting the name will imply usage of this value.

If you're a virtualenvwrapper user and have $PROJECT_HOME set, omitting the name will try to guess which virtualenv to activate based on the current filename.

You can even show the current virtualenv in the statusline with the included function.

Or, for those with a properly configured Powerline (the virtualenv segment is not enabled by default), your virtualenv indicator will toggle on or off accordingly.

For more detailed help

:help virtualenv

vim-virtualenv's People

Contributors

ayemeng avatar blueyed avatar brianclements avatar folti avatar jmcantrell avatar jtriley avatar laxtiz avatar lki avatar m42e avatar ryanpineo avatar zzelle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vim-virtualenv's Issues

Relative virtualenv directories not recognized

Hi,

I am not sure if this is exactly virtualenv-vim related, but I have problems when the path to the virtualenv directory is relative instead of absolute.
When I start Vim with the virtualenv-vim plugin - it recognizes my virtualenv directory and sets the virtualenv_directory variable ( to '~/envs' in my case) , but when I try to execute 'VirtualEnvList' is says 'g:virtualenv_directory is not set or is not a directory'

if isdirectory('/home/username/envs')
echo 'absolute directory working as expected'
endif

if isdirectory('~/envs')
echo 'relative directory not working'
endif

I am using Ubuntu 11.04

The g:virtualenv_directory could use some additional documentation.

Hi, I am using vim-virtualenv via vim-pipenv and I kept getting the error:

    if !isdirectory(env_dir)
        if !silent
            echoerr "No virtualenv could be auto-detected and activated."
        endif
        return
    endif

in virtualenv#activate(...).

Some debugging revealed that this was because my virtualenv directory is not handled by the following conditional:

if !exists("g:virtualenv_directory")
    if isdirectory($WORKON_HOME)
        let g:virtualenv_directory = $WORKON_HOME
    else
        let g:virtualenv_directory = '~/.virtualenvs'
    endif
endif

in virtualenv.vim.

By setting the g:virtualenv_directory explicitly in my Neovim dotfile, I got the plugin working. I'm not sure how common this problem is but I'm hoping that some additional documentation about the variable would help others not have to debug the issue.

Thanks!

Editing a file from PROJECT_HOME dir throws exeption

If I define PORJECT_HOME environment variable and there is no activated virtualenv, doing cd $PROJECT_HOME ; vim test.py throws:

Error detected while processing function virtualenv#activate:
line   33:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/calind/dotfiles/vim/bundle/vim-virtualenv/autoload/pyvenv.py", line 9, in activate
    with open(activate) as f:
IOError: [Errno 2] No such file or directory: '/Users/calind/.virtualenvs/./bin/activate_this.py'
Press ENTER or type command to continue

The problem seems to be in this if branch https://github.com/jmcantrell/vim-virtualenv/blob/master/autoload/virtualenv.vim#L18-L25 because fnamemodify(substitute(fn, pat, '', ''), ':h') returns . when the current directory is PORJECT_HOME.

How to install vim-virtualenv in linux?

I want to install the plugin
But I do not see that explain the steps or in which route should clone the plugin?
This plugin depends on Pathogen
I already have it installed and configured in my .vimrc

do not support py3.8?

Error detected while processing function virtualenv#activate:
line 44:
Traceback (most recent call last):
File "", line 1, in
File "/Users/xxx/.vim/plugged/vim-virtualenv/autoload/pyvenv.py", line 47, in activate
code = compile(f, activate, 'exec')
File "/Users/xxx/Library/Caches/pypoetry/virtualenvs/xxx-zz-py3.8/bin/activate_this.py", line 18
raise AssertionError(msg) from exc
^
SyntaxError: invalid syntax

virtualenv_auto_activate doesn't try very hard

Not sure this is really an issue, but I wanted to share an approach I used to make auto activate try a little harder.

I don't have a $VIRTUAL_ENV or $PROJECT_HOME, I just have a single virtual env with the specific python version my vim was compiled with.

I was hoping that setting g:virtualenv_auto_activate would detect and load the single virtual environment I have. It does not.

My suggestion is to add a third case to virtualenv#activate, so if there is no $VIRTUAL_ENV or $PROJECT_HOME, it will call virtualenv#names, and if there is a single environment, attempt to load it.

Like so (warning, script novice!)

 if len(name) == 0  "Figure out the name based on current file
    if isdirectory($VIRTUAL_ENV)
        [...]
    elseif isdirectory($PROJECT_HOME)
        [...]
    else
        let venv = virtualenv#names('')
        if len(venv) == 1
            let name = venv[0]
            let env_dir = g:virtualenv_directory.'/'.name
        endif
    endif
else
    [...]
endif

Thanks...

No commands in Vim 8.1.2104 (Git Bash) on Windows 10

I seem to be having issues with Vim included with GitBash, and also Vim for Windows (which doesn't have +python enabled) allowing me to run :VirtualEnvList or any of the other commands. With wildmenu turned on, I can tab through commands, but the VirtualEnv* commands are not available. I continually get:

E492: Not an editor command: VirtualEnvList

I also have the Plugin installed into: ~/.vim/pack/vendor/start/vim-virtualenv/, and it shows in my :scriptnames list of loaded scripts.

Is this plugin intended only to be used on Linux/MacOS machines?

How to update Powerline when activating?

I tend to use virtualenvwrapper in when in my shell, and your plugin when in vim. I've done a lot of stuff in the background with zsh to try and keep my env-vars updated when changing directories and make sure that your plugin looks at the same virtualenv as virtualenvwrapper.

So that said, when I activate a venv in zsh, then enter vim, powerline shows me the name of my virtualenv in a little indicator. The code it uses is here. And I have it working correctly for that particular situation. When I enter vim however without activating a venv first, and use your plugin to activate the same venv, the python path is modified correctly and works just fine, but powerline hasn't been notified that the venv was activated and my powerline indicator doesn't show up.

Any insight on how to modify your plugin to write the appropriate env-vars and announce to powerline to update that particular segment?

Slow load time

Is it possible to make it lazyload on vim startup using features vim-plug or maybe other plugin managers provide?
My Vim takes 1.3 sec to startup with this plugin activated, when I deactivate it, it startups in .8 sec.

using virtualenv_auto_activate can lead to annoying errors

This line in virtualenv.vim causes problems with virtualenv_auto_activate:

        call s:Error("No VirtualEnv name given")

The issue I'm running into is that opening vim for non-Python tasks (such as editing git commit messages) results in this error printing out on the screen. In my local copy, I simply commented out this line -- I can live without the error message when it fails, rather than the annoyance of having it when editing non-Python files. Not sure what you think should be done to fix this.

Relative virtualenv directories not recognized

Hi,

I am not sure if this is exactly virtualenv-vim related, but I have problems when the path to the virtualenv directory is relative instead of absolute.
When I start Vim with the virtualenv-vim plugin - it recognizes my virtualenv directory and sets the virtualenv_directory variable ( to '~/envs' in my case) , but when I try to execute 'VirtualEnvList' is says 'g:virtualenv_directory is not set or is not a directory'

if isdirectory('/home/username/envs')
    echo 'absolute directory working as expected' 
endif 

if isdirectory('~/envs')
    echo 'relative directory not working'  
endif 

I am using Ubuntu 11.04

vim-virtualEnv with MacVim seems not working

Hi,

I tried to load my env first then launch mvim, export VIRTUAL_ENV=~/src/my_project/env and then launch mvim without any result. Everytime there's no env activated or in the list. Anyone is using it with MacVim ?

MacVim version: - Vim patch 7.4.2196

Thanks for your help !

FileNotFoundError: activate_this.py

The virtualenv is created using python3 -m venv, where python3(3.4.3) is installed by homebrew in OSX: It's build-in venv module does not automatically create activate_this.py.

I then copied same file from other virtualenv, and found this activation file (might) could be generally used, could you add it as a backup plan for activating virtualenv?

here's the activate_this.py:

"""By using execfile(this_file, dict(__file__=this_file)) you will
activate this virtualenv environment.

This can be used when you must use an existing Python interpreter, not
the virtualenv bin/python
"""

try:
    __file__
except NameError:
    raise AssertionError(
        "You must run this like execfile('path/to/activate_this.py', dict(__file__='path/to/activate_this.py'))")
import sys
import os

old_os_path = os.environ['PATH']
os.environ['PATH'] = os.path.dirname(os.path.abspath(__file__)) + os.pathsep + old_os_path
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if sys.platform == 'win32':
    site_packages = os.path.join(base, 'Lib', 'site-packages')
else:
    site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')
prev_sys_path = list(sys.path)
import site
site.addsitedir(site_packages)
sys.real_prefix = sys.prefix
sys.prefix = base
# Move the added items to the front of the path:
new_sys_path = []
for item in list(sys.path):
    if item not in prev_sys_path:
        new_sys_path.append(item)
        sys.path.remove(item)
sys.path[:0] = new_sys_path

VirtualEnvActivate and othe commnads problem

Hi~
i installed virtualenv with Bundle.
From commnad line i used $workon myproject. Activated it Then used vim from command line to open myproject.py .Both $WORKON_HOME and $RPOJECT_HOME variables set in
advance.when i type
VirtualEnvList or wheatever command comes with plugin it is saying
Not an editor commnad although i can use
help virtualenv (opens the txt file)
Any idea?

On Windows, double slashes are used in the virtualenv folder.

On Windows 7, when you try to activate a virtual environment it uses double slashes for the path, rendering the plugin unable to load the right environment. This is the traceback:

Error detected while processing function virtualenv#activate:
line   34:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\maciej_szlosarczyk\vimfiles\bundle\vim-virtualenv\autoload\pyvenv.py", line 9, in activate
    with open(activate) as f:
IOError: [Errno 2] No such file or directory: 'C:\\Users\\maciej_szlosarczyk\\Virtualenvs/barbell\\Scripts\\activate_this.py'  

Default ~/.virtualenvs directory not working properly

The variable on line 21 should be let g:virtualenv_directory = expand('~/.virtualenvs') instead of
let g:virtualenv_directory ='~/.virtualenvs', because if the path is relative and you try to activate a virtualenv it fails here:

  let script = bin.'/activate_this.py'
      if !filereadable(script)
          call s:Error("'".name."' is not a valid virtualenv")

no way to notify virtualenv about local dir w/out virtualenvwrapper

I'm using virtualenv without virtualenvwrapper. That is, in my project's dir I manually virtualenv venv which set the working virtualenv directory to be ./venv/. I've no info on how to to activate virtualenv this way in vim. Setting let g:virtualenv_directory = 'venv' or to ./venv or anything similar didn't help.

In addition, if I manually source ./venv/bin/activate and then activate vim, the plugin doesn't recognise this.

What am I doing wrong? In any case the documentation is lacking regarding this issue.

it does not work for me :(

run :VirtualEnvActive myenv, and run script by key mappingautocmd BufRead,BufNewFile *.py nmap <F5> :!python %<CR> then it also tell me no thirds models

sys.path entries get erased by :VirtualEnvDeactivate in particular scenario

Note: I use pyvenv for virtual environments, I don't know if the same problem occurs for virtualenv users.

The issues is probably related to how the sys.path is handled for activation and deactivation of virtual environment. The vim-virtualenv plugin is not always run/initialized first relative to other plugins (that may also modify sys.path), but it looks like :VirtualEnvDeactivate command's code assumes, that the venv's site-packages entry is the first in sys.path. This leads to some entries being erased from the path, when the command is run. See example and actions to repeat the issue below.

Scenario 1 (starting vim when venv is already active, the path gets erased):

  1. I activate virtual environment in bash;
  2. Run vim somefile.py;
  3. In vim I check sys.path by running :python import sys; print(sys.path);
  4. The path is a long list, WITH directories for YouCompleteMe and my virtual environment site-packages somewhere in the middle;
  5. Then, in vim I run :VirtualEnvDeactivate;
  6. And I check sys.path again by running :python import sys; print(sys.path);
  7. The path is a very short list WITHOUT directories for YouCompleteMe, and, of course, without the directory for venv's site-packages;
  8. If I run :VirtualEnvActivate venv_name, and check sys.path again there're no directories for YouCompleteMe, and the directory for venv's site-packages is the first in the list.

Scenario 2 (manual virtual environment activation in vim, works as expected):

  1. No virtual environment is active, and I run vim somefile.py;
  2. In vim I check sys.path by running :python import sys; print(sys.path);
  3. The path is a long list WITH directories for YouCompleteMe, and, of course, without the directory for venv's site-packages;
  4. I run :VirtualEnvActivate venv_name, and check sys.path again;
  5. The path is a long list WITH directories for YouCompleteMe, and the directory for venv's site-packages is the first in the list;
  6. Then, in vim I run :VirtualEnvDeactivate, and check sys.path again;
  7. The path is a long list WITH directories for YouCompleteMe, and, of course, without the directory for venv's site-packages.

Stopped working

I've had this plugin work for me before, but it has since stopped. It's definitely being loaded, and I've tried to use various versions of the plugin (the 5 most recent commits) to no avail. Any tips on where to get more information to start debugging?

noteworthy: in the past when the plugin has worked, the notifications in powerline never actually let me know which venv I was using, but I was certain that the proper venv was loaded or else running the file I was working on would never have run. The tab auto-complete worked then too but does not now.

my vimrc setup for the plugin:

let g:pymode_virtualenv = 1
let g:virtualenv_directory = '../venv'

I've also tried absolute path as well to no avail.

Virtualenvwrapper problem

I have a virtualenvwrapper on my machine. I have the virtualenvwrapper variable in my .bashrc file export WORKON_HOME=$HOME/envs, but the vim-virtualenv plugin doesn't recognize that and falls back to the default path ( ~/.virtualenvs )

I tried to check the $WORKON_HOME variable with echo $WORKON_HOME, but vim didn't show anything.

Airline support doesn't work

I followed the directions in airline by putting the following in my vimrc file:

let g:airline#extensions#virtualenv#enabled = 1

but it doesn't update my statusline like it should. I only managed to get it to work when I add this:

let g:airline_section_x = airline#section#create('%{virtualenv#statusline()}')

However, it no longer adds filetypes like I want it to. Can you please tell me what I am doing wrong?

"cd" after VirtualEnvActivate

I think it might be a good idea to change to the projects directory after VirtualEnvActivate.

What do you think?
Should this be an optional feature?

Test Active Virtualenv

Hi

I have installed your plugin, but it doe not appear to be running. I ammended the statusline in my vimrc to try and get some feedback from vim that it had indeed activate the env.

This is my statusline
set statusline=%<%f\ %h%m%r%{virtualenv#statusline()}%=%-14.(%l,%c%V%)\ %P

However after selecting my VirtualEnvActivate test2
I have nothing showing in my statusline, is there anyway to test to provide useful feedback?

DeprecationWarning: imp module is deprecated in favor of importlib

I am experiencing a DeprecationWarning - after installing the vim-virtualenv bundle via Vundle - which is raised each time I open a file via vim - whether or not I have a virtualenv open. When I remove the bundle, everything words normal.

Here's the error:
Error detected while processing /Users/plutonium/.vim/bundle/vim-virtualenv/autoload/vir tualenv.vim: line 2: /must>not&exist/foo:1: DeprecationWarning: the imp module is deprecated in favour of imp ortlib; see the module's documentation for alternative uses

I found a seemingly similar issue with https://github.com/ARM-DOE/pyart/pull/675, but it's from August 2017. Not sure how much help it would be.

Not sure if it's my configuration or cwd. I do have vim and python installed via homebrew, and virtualenvwrapper inside my global pip3.

Anyone else ran into this issue?

Versions:
Python3 - 3.7.0
Vim - 8.1 (inside homebrew)

does not work for 'local' venvs

OK I have red the help and it seems that the plugin is looking for a ~/.virtualenvs dir.

However I have only created virtualenvs for each project independently, for ex: virtualenv -p /usr/local/bin/python2.7 venv. This command creates a virtual environment 'venv' in the directory where it is executed.

It seems that vim-virtualenv does not detect these local venvs

Not working in Vim8.

Ive installed the plugins where all the rest of my working plugins are.
If I :scriptnames then I can see the plugins .vim being listed.

When I open vim though, if I try to run any commands I get
E492: Not an editor command: VirtualEnvActivate env

Do I need to do anything else for the plugin to be functional?

PYTHONPATH mangling breaks `!supervisorctl`

The change from #15 breaks invoking supervisorctl for me.

:!supervisorctl update fails as follows:

Traceback (most recent call last):
  File "/home/user/.virtualenvs/project/bin/supervisorctl", line 9, in <module>
    load_entry_point('supervisor==3.0', 'console_scripts', 'supervisorctl')()
  File "/home/user/.virtualenvs/project/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/home/user/.virtualenvs/project/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
    return ep.load()
  File "/home/user/.virtualenvs/project/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
    entry = __import__(self.module_name, globals(),globals(), ['__name__'])
ImportError: No module named supervisor.supervisorctl

shell returned 1

Press ENTER or type command to continue

This does not happen when I remove the addition of sys.path to PYTHONPATH.

The reason for this is that /usr/lib/python2.7 gets added to PYTHONPATH. Removing it from the huge list (1394 chars), fixes it.

Apart from that, I think that copying the whole of sys.path into PYTHONPATH should be avoided.

I do not know which problem(s) @mtth tried to fix here, but it might just be necessary to install packages also inside of the virtualenv.

I will disable the PYTHONPATH mangling locally and see if I run into any problems.

@mtth: can you please elaborate on the intention behind this? After all the virtualenv activation scripts do not touch PYTHONPATH either.

Can't call funtion

Why after installing it, i can't call :VirtualEnvList
It shows command doesn't exist

Gvim with virtualenv_auto_activate and :VirtualEnvActivate without arguments

They are only working if:
1) gvim was opened from terminal: I have a unity launcher set for gvim and my usual workflow is to start gvim from there, and then start editing files, and this way the detection fails
2) the file lives inside the project's dir: Files that are inside other levels of the project's dir are not being detected

This way, I'm forced to explicitly call ':VirtualEnvActivate virtualenv-name' or change my workflow to opening a terminal typing 'workon project-name' and then launching gvim.

ubuntu 12.04
vim 7.3-429

Why am I seeing a pop-up dialog box asking for my "Secure Shell passphrase:"?

I am using the ziaste vimified framework. When I add the the vim-virtualenv bundle and run:
vim +BundleInstall +qall
It opens, starts installing all the bundles but when it gets to vim-virtualenv, I get a popup box with the title:
"Enter your Secure Shell passphrase:" then "Username for 'https://github.com" then a text box with the label: Password:

In the status line, I see "Processing 'vim-virtualenv" but it just is stuck there.

I can cancel out of the dialog box but then it tells me "Error processing vim-virtualenv.

If I remove this bundle, the same command processes all the other bundles without a problem.

Why am I getting a prompt to enter this information?

wrong filename-modifiers when getting basename of $VIRTUAL_ENV

Hi jmcantrell,

First of all, thanks for your work.

The VirtualEnvActivate('') is not working for me when I've activated the virtualenv, which gives me an error message just like this:
'/home/flisky/.virtualenvs' is not a valid virtualenv.

I notice that the old way is python code
os.path.basename(os.environ.get("VIRTUAL_ENV")),
and now it's changed into vim script
let name = fnamemodify($VIRTUAL_ENV, ':h').

I don't think we should use ':h' here, since ':h' gives us HEAD of the name. Instead, I think we should use ':t' (Tail of the file name), which should be the basename.

I'm a newbie in vimscript, and I'm a little surprised that no other people find this for more than three months.
Please correct me if anything wrong, and sorry for me poor English if any:)

Thanks,

Doesn't update $PATH under neovim

Running NVIM v0.2.0-485-g81525dc:

  • Create virtualenv: python3 -m venv $HOME/.virtualenvs/myvenv
  • Open Neovim
  • :VirtualEnvActivate myvenv
  • echo $PATH output doesn't include the myvenv/bin/ directory
  • :python import sys; print(sys.path) returns ['/Users/tpict/.virtualenvs/myvenv/lib/python2.7/site-packages', ...

that folder doesn't exist - Python 2.7 is the default installation on OS X, and the virtualenv uses 3.6

E117: unknown function : VirtualEnvStatusLine

after clone the module into my bundle folder, and start vim from terminal. then I get these two errors
E117 Unknown function: VirtualEnvStatusline and
E15 Invalid expression: VirtualEnvStatusline()

but I don't see it if I start my macvim. don't know why

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.