kassio / neoterm

Wrapper of some vim/neovim's :terminal functions.
Other
1.32k stars 117 forks source link

How to run current Python file in neoterm with current Conda environment? #341

Open AniAggarwal opened 2 years ago

AniAggarwal commented 2 years ago

I am using Anaconda to manage Python venvs.

Before entering Neovim I activate the conda env I am using for the current project (i.e. conda activate my-env ; nvim)

However, when I create a new neoterm instance (using Tnew), the base conda env is activated again, losing my env. This means I have to reactivate the env manually in the terminal (conda activate my-env) before running they python file.

One possible work around is running :T conda activate my-env ; python %. As I use different envs for different projects, I would need my-env to be dynamically updated. The env variable $CONDA_DEFAULT_ENV would work here but I'm not sure how to get it to evaluate and then be used in place of my-env. Something like this would work if I could substitute $CONDA_DEFAULT_ENV for its value before the command is sent to terminal (as after its sent, $CONDA_DEFAULT_ENV evaluates to base, not my desired env). :T conda activate $CONDA_DEFAULT_ENV ; python %

To be clear, the conda env is not activated for running Python files like normal (non interactive mode, python my-file.py) and for interactive model (running via TREPLSendFile).

I've tried setting the following, but it doesn't seem to work let g:neoterm_repl_python_venv = 'conda activate my-env' let g:neoterm_repl_python = 'conda activate my-env' let g:neoterm_repl_python_venv = 'my-env' let g:neoterm_repl_python = 'my-env'

AniAggarwal commented 2 years ago

I figured out how to make this work, but its a hacky solution. Would be cool if there was official support for this in neoterm This is what I have in my init.vim. Feel free to leave suggestions on how to improve it (I know very little vimscript).

" Mapping for activating conda env
nnoremap <leader>tc :call CopyCondaEnvName()<CR>"cp A<CR>
" Open new terminal, move cursor to it, and activate conda env
nmap <leader>tn :Tnew <bar> :wincmd w<CR><leader>tc
" Clear given terminal
nnoremap <leader>tl :<c-u>exec v:count.'Tclear'<CR>
" Toggle given terminal and move cursor to it
nmap <leader>tt :Ttoggle <bar> :wincmd w<CR><leader>tc
" Run current file as python file
nmap <leader>trp <leader>tt<C-n><C-w>W :T python %<CR>

function CopyCondaEnvName()
    let @c = "conda activate ". $CONDA_DEFAULT_ENV
endfunction
linusbiostat commented 2 years ago

For me it ipython is run in the conda env I went before starting nvim if I set let g:neoterm_direct_open_repl = 1 in my init.vim