From bf71ea8fba18f91dea3651c669e768d9b9b6acce Mon Sep 17 00:00:00 2001 From: Stefan Friese Date: Wed, 26 Feb 2025 10:04:38 +0100 Subject: [PATCH] added function to activate a virtualenv if there is any in the directory of the python files --- vim/.vim/after/ftplugin/python.vim | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/vim/.vim/after/ftplugin/python.vim b/vim/.vim/after/ftplugin/python.vim index 5f3480b..af0112f 100644 --- a/vim/.vim/after/ftplugin/python.vim +++ b/vim/.vim/after/ftplugin/python.vim @@ -38,3 +38,26 @@ let g:ale_fixers = { \ '*': ['remove_trailing_lines', 'trim_whitespace'], \ 'python': ['black', 'add_blank_lines_for_python_control_statements'], \} + +function! LoadVirtualEnv() + if filereadable('./.venv/bin/activate') + let g:virtualenv_path = getcwd() . '/.venv/bin/python' + let g:python3_host_prog = g:virtualenv_path + echo "Loaded virtual environment: " . g:virtualenv_path + elseif filereadable('./venv/bin/activate') + let g:virtualenv_path = getcwd() . '/venv/bin/python' + let g:python3_host_prog = g:virtualenv_path + echo "Loaded virtual environment: " . g:virtualenv_path + else + " If no virtualenv is found, fall back to the default Python + " Check if variables exist before unsetting them + if exists('g:virtualenv_path') + unlet g:virtualenv_path + endif + if exists('g:python3_host_prog') + unlet g:python3_host_prog + endif + endif +endfunction + +autocmd BufEnter * call LoadVirtualEnv()