Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the cursor shape in the interactive IPython consle depending on vi-mode

I can change from emacs to vi bindings in the interactive IPython console, by adding the following to ~/.ipython/profile_deafult/ipython_config.py:

c.TerminalInteractiveShell.editing_mode = 'vi'

Currently, the cursor is always an I-beam (|). Is there a way that I can make the cursor change shape to a block when in vi's normal mode and then back to an I-beam when in insert mode?


My terminal emulator (terminator, based on gnome-terminal) supports switching between cursor formats, as I can enable the behavior in zsh, by adding the following to my ~./zshrc (from the Unix SE):

bindkey -v
# Remove delay when entering normal mode (vi)
KEYTIMEOUT=5
# Change cursor shape for different vi modes.
function zle-keymap-select {
  if [[ $KEYMAP == vicmd ]] || [[ $1 = 'block' ]]; then
    echo -ne '\e[1 q'
  elif [[ $KEYMAP == main ]] || [[ $KEYMAP == viins ]] || [[ $KEYMAP = '' ]] || [[ $1 = 'beam' ]]; then
    echo -ne '\e[5 q'
  fi
}
zle -N zle-keymap-select
# Start with beam shape cursor on zsh startup and after every command.
zle-line-init() { zle-keymap-select 'beam'}
like image 998
joelostblom Avatar asked May 25 '17 23:05

joelostblom


1 Answers

As per this comment in the GitHub issue (and this update), you can add the following snippet to ~/.ipython/profile_default/ipython_config.py to make the cursor change shape when switching between insert and normal mode.

import sys
from prompt_toolkit.key_binding.vi_state import InputMode, ViState


def get_input_mode(self):
    return self._input_mode


def set_input_mode(self, mode):
    shape = {InputMode.NAVIGATION: 1, InputMode.REPLACE: 3}.get(mode, 5)
    raw = u'\x1b[{} q'.format(shape)
    if hasattr(sys.stdout, '_cli'):
        out = sys.stdout._cli.output.write_raw
    else:
        out = sys.stdout.write
    out(raw)
    sys.stdout.flush()
    self._input_mode = mode


ViState._input_mode = InputMode.INSERT
ViState.input_mode = property(get_input_mode, set_input_mode)
c.TerminalInteractiveShell.editing_mode = 'vi'
like image 98
joelostblom Avatar answered Nov 18 '22 20:11

joelostblom