yungchin
yungchin

Reputation: 1599

Standard python interpreter has a vi command mode?

I was working a bit in the python interpreter (python 2.4 on RHEL 5.3), and suddenly found myself in what seems to be a 'vi command mode'. That is, I can edit previous commands with typical vi key bindings, going left with h, deleting with x...

I love it - the only thing is, I don't know how I got here (perhaps it's through one of the modules I've imported: pylab/matplotlib?).

Can anyone shed some light on how to enable this mode in the interpreter?

Upvotes: 36

Views: 13267

Answers (5)

Harsh Verma
Harsh Verma

Reputation: 933

On macOS Monterey(12.5) with Python 3.10, I got vi bindings to work in the python interpreter by adding set editing-mode vi to ~/.inputrc(which I also created).

Upvotes: -1

Mark Beckner
Mark Beckner

Reputation: 111

For Mac OS X 10.10.3, python2.7, vi mode can be configured by placing bind -v in ~/.editrc. The last few paragraphs of the man page hint at this.

Upvotes: 11

Iacchus
Iacchus

Reputation: 2837

Use readline.parse_and_bind method. For example, try on python interactive console:

import readline
readline.parse_and_bind("set editing-mode vi")

It seems any command you can set in .inputrc you can set via this method too. I tried it in Python 2.7 and 3.5.1.

See also man readline


EDIT (Dec 21th, 2019): or maybe, to have a true vim you can manage to patch the python's readline with Athame. I did it with bash and it is very cool.

Upvotes: 5

Philip Reynolds
Philip Reynolds

Reputation: 9402

This kind of all depends on a few things.

First of all, the python shell uses readline, and as such, your ~/.inputrc is important here. That's the same with psql the PostgreSQL command-line interpreter and mysql the MySQL shell. All of those can be configured to use vi-style command bindings, with history etc.

<ESC> will put you into vi mode at the python shell once you've got your editing mode set to vi

You may need the following definition in your ~/.inputrc

set editing-mode vi

OSX info

OSX uses libedit which uses ~/.editrc. You can man editrc for more information.

For example, to mimick a popular key combination which searches in your history, you can add the following to your .editrc

bind "^R" em-inc-search-prev

Upvotes: 36

arcanex
arcanex

Reputation:

Ctrl-Alt-J switches from Emacs mode to Vi mode in readline programs.

Alternatively add "set editing-mode vi" to your ~/.inputrc

Upvotes: 43

Related Questions