Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect Vim with Python REPL session

I have two terminal sessions, one running Vim and the other running a Python (or iPython) REPL.

I'm looking for a way to make Vim dynamically interoperate with the REPL session.

As an example of desired behaviour, say I have this Python file open in Vim:

 1  x = 40
 2  y = 2
 3  z = x + y
 4  print('The answer is {}'.format(z))
 5  print('The product of {} and {} is {}'.format(x, y, x*y))

And I type these entries in the iPython REPL session:

In [1]: x = 10
In [2]: y = 26

Now I'd like to be able to send lines 3-5 from Vim to be executed in the REPL session, starting with the variables previously defined in the session, and producing the following result:

# these are lines typed in the REPL
In [1]: x = 10
In [2]: y = 26

# lines from Vim are silently inserted here and executed, which prints...
The answer is 36
The product of 10 and 26 is 260

# because of Vim export, z is now part of the current scope
In [3]: z
Out[3]: 36

Emacs can do such stuff quite easily, but despite searching for quite a long time I never found a way to get similar behaviour with Vim.

Edit: Maybe the answer would depend on the specifics (Tmux, etc) so in this case, I'm specifically using two iTerm2 panes on MacOS, one running Vim and the other running iPython.

like image 659
Jivan Avatar asked Aug 23 '17 15:08

Jivan


People also ask

How do I start Python REPL?

To start the REPL in VS code, open the command palette and search for and select “Start REPL”. The advantage to starting the REPL from inside VS Code is that it respects the environment you already set up, that is the version of Python you chose earlier.

Which of the following is a Python REPL environment?

Python interpreter shells such as IDLE, IPython, Jupyter notebook are REPL environments.


2 Answers

In Emacs world, this is referred to as "Slime", and it usually used to connect Emacs with a REPL, such as Lisp REPL.

The closest thing in Vim, that supports Python is vim-slime

This plugin requires you to use either GNU Screen or Tmux, so you cannot expect it to work if you continue running in two separate terminals.

Another option is to use Iron.Nvim which works on Neovim only. It makes use of Neovim term support so you don't need Tmux/Screen.

like image 198
Meitham Avatar answered Sep 28 '22 16:09

Meitham


Maybe you can try my plugin vim-repl. It provides a convince repl environment for vim using the vim8 terminal feature.

here is the github homepage: vim-repl

To open the repl environment, just run :REPLToggle or you can even bind it witk key like:

nnoremap <leader>r :REPLToggle<Cr>

To interact with repl, you just select the code and press ww. And the code will be transmitted to the repl environment.

Look into the github homepage for more details, it will worth your time.

like image 42
eric Avatar answered Sep 28 '22 15:09

eric