diff --git a/plugins/python/README.md b/plugins/python/README.md index c99697b22..b990a26b9 100644 --- a/plugins/python/README.md +++ b/plugins/python/README.md @@ -32,8 +32,9 @@ virtual environments: `venv`) in the current directory. - `auto_vrun`: Automatically activate the venv virtual environment when entering a directory containing - `/bin/activate`, and automatically deactivate it when navigating out of it (including - subdirectories!). + `/bin/activate`, and automatically deactivate it when navigating out of it (keeps venv activated + in subdirectories). - To enable the feature, set `export PYTHON_AUTO_VRUN=true` before sourcing oh-my-zsh. - - The default virtual environment name is `venv`. To use a different name, set + - Plugin activates first virtual environment in lexicographic order whose name begins with ``. + The default virtual environment name is `venv`. To use a different name, set `export PYTHON_VENV_NAME=`. For example: `export PYTHON_VENV_NAME=".venv"` diff --git a/plugins/python/python.plugin.zsh b/plugins/python/python.plugin.zsh index f6ea85027..7256aa04f 100644 --- a/plugins/python/python.plugin.zsh +++ b/plugins/python/python.plugin.zsh @@ -86,11 +86,20 @@ function mkv() { if [[ "$PYTHON_AUTO_VRUN" == "true" ]]; then # Automatically activate venv when changing dir - auto_vrun() { - if [[ -f "${PYTHON_VENV_NAME}/bin/activate" ]]; then - source "${PYTHON_VENV_NAME}/bin/activate" > /dev/null 2>&1 - else - (( $+functions[deactivate] )) && deactivate > /dev/null 2>&1 + function auto_vrun() { + # deactivate if we're on a different dir than VIRTUAL_ENV states + # we don't deactivate subdirectories! + if (( $+functions[deactivate] )) && [[ $PWD != ${VIRTUAL_ENV:h}* ]]; then + deactivate > /dev/null 2>&1 + fi + + if [[ $PWD != ${VIRTUAL_ENV:h} ]]; then + for _file in "${PYTHON_VENV_NAME}"*/bin/activate(N.); do + # make sure we're not in a venv already + (( $+functions[deactivate] )) && deactivate > /dev/null 2>&1 + source $_file > /dev/null 2>&1 + break + done fi } add-zsh-hook chpwd auto_vrun