Skip to content

Instantly share code, notes, and snippets.

@sstirlin
Last active April 3, 2024 16:35
Show Gist options
  • Save sstirlin/c3c207b1052b613ab9554b4ebdfc3f35 to your computer and use it in GitHub Desktop.
Save sstirlin/c3c207b1052b613ab9554b4ebdfc3f35 to your computer and use it in GitHub Desktop.
vim bindings for IPython

As of IPython 5, readline is no longer used to interpret keystrokes.
Instead, the pure-python library prompt_toolkit is used.

Getting vim mode in IPython is straightforward. First, edit

~/.ipython/profile_default/ipython_config.py

and add the following line:

c.TerminalInteractiveShell.editing_mode = 'vi'

For custom keybindings, create a new file

~/.ipython/profile_default/startup/keybindings.py

and put this code in (this remaps jk to Esc):

from IPython import get_ipython
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasFocus, ViInsertMode
from prompt_toolkit.key_binding.vi_state import InputMode


ip = get_ipython()

def switch_to_navigation_mode(event):
    vi_state = event.cli.vi_state
    vi_state.reset(InputMode.NAVIGATION)

if getattr(ip, 'pt_cli'):
    registry = ip.pt_cli.application.key_bindings_registry
    registry.add_binding(u'j',u'k',
                         filter=(HasFocus(DEFAULT_BUFFER)
                                 & ViInsertMode()))(switch_to_navigation_mode)

For notebooks, you can enable vim mode by installing this plugin https://github.com/lambdalisue/jupyter-vim-binding

@Paul-Aime
Copy link

@dvths I do have the same but it's just a linter warning. It says type None because the actual upstream warning is "get_ipython" is not exported from module IPython.

Does it raise an error for you?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment