Ipython configuration

From wikinotes

Documentation

key bindings docs https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/docs/pages/advanced_topics/key_bindings.rst
vi keybindings

https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/key_binding/bindings/vi.py

default keybindings https://ipython.readthedocs.io/en/stable/config/shortcuts/index.html

Profile

IPython lets you define/load configuration profiles.

Find active profile

import IPython
IPython.utils.path.get_ipython_dir()

Interactive Config

import IPython
ip = IPython.get_ipython()
ip.alias_manager.aliases  # print current aliases

Sample Config

#!/usr/bin/env python

import IPython
import logging

ipy_version = IPython.version_info
if ipy_version[0] < 5:
    c = get_config()

# Autoreload
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')

# Default LogLevel
logging.root.level = logging.INFO

if ipy_version[0] >= 5:
    c.TerminalInteractiveShell.editing_mode = 'vi'
    c.TerminalInteractiveShell.display_completions = 'column'
    c.TerminalInteractiveShell.highlighting_style = 'legacy'

Keyboard Shortcuts

Set keybindings using prompt_toolkit.

import IPython
from prompt_toolkit import keys
from prompt_toolkit import filters
from prompt_toolkit.key_binding import vi_state


def get_key_registry():
    ip = IPython.get_ipython()
    if not getattr(ip, 'pt_app', None):
        return None
    return ip.pt_app.key_bindings


def set_normal_mode(event):
   vi_state_ = event.cli.vi_state
   vi_state_.input_mode = vi_state.InputMode.NAVIGATION


def bind_jk_to_normal_mode(key_registry):
    filters = filters.HasFocus(enums.DEFAULT_BUFFER) \
        & filters.ViInsertMode()

    key_registry.add_binding(u'j', u'k', filter=filters)\
        (set_normal_mode)


registry = get_key_registry()
if registry:
    bind_jk_to_normal_mode(registry)