Skip to content

Instantly share code, notes, and snippets.

Forked from konradkonrad/
Last active July 15, 2016 17:53
Show Gist options
  • Save haridsv/7b8ea0a6861582b1bc0b6997f075b980 to your computer and use it in GitHub Desktop.
Save haridsv/7b8ea0a6861582b1bc0b6997f075b980 to your computer and use it in GitHub Desktop.
restore yank-last-arg and yank-nth-arg in ipython 5
# ~/.ipython/profile_default/startup/
from IPython import get_ipython
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.keys import Keys
from prompt_toolkit.filters import HasFocus, HasSelection, ViInsertMode, EmacsInsertMode
ip = get_ipython()
insert_mode = ViInsertMode() | EmacsInsertMode()
class State(object):
def __init__(self):
def reset_state(self):
self.depth = 0
self.arg = None
state = State()
def yank_last_arg(event):
"""'readline'-style yank-last-arg:
Insert last argument to the previous command (the last word of the previous history entry).
Successive calls to yank-last-arg move back through the history list, inserting the last
word of each line in turn.
note: this doesn't support the numeric argument option of readline's yank-last-arg
b = event.current_buffer
hist = ip.history_manager.input_hist_raw
if state.depth == 0:
state.depth = 1
state.depth += 1
if not event._arg is None:
state.arg = event._arg
arg = state.arg is None and -1 or state.arg
if len(hist) and len(hist) >= state.depth:
lastline = hist[-state.depth]
if state.depth > 1:
if len(lastline.split()):
if getattr(ip, 'pt_cli'):
registry = ip.pt_cli.application.key_bindings_registry
registry.add_binding(Keys.Escape, u'.',
& ~HasSelection()
& insert_mode))(yank_last_arg)
registry.add_binding(Keys.Escape, u'_',
& ~HasSelection()
& insert_mode))(yank_last_arg)'post_execute', state.reset_state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment