Skip to content

Instantly share code, notes, and snippets.

@konradkonrad
Last active September 14, 2016 13:44
Show Gist options
  • Save konradkonrad/7143fa8407804e37132e4ea90175f2d8 to your computer and use it in GitHub Desktop.
Save konradkonrad/7143fa8407804e37132e4ea90175f2d8 to your computer and use it in GitHub Desktop.
restore yank-last-arg in ipython 5
# ~/.ipython/profile_default/startup/01-esc-dot.py
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):
self.depth = 0
state = State()
def reset_last_arg_depth():
state.depth = 0
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.
see: https://www.gnu.org/software/bash/manual/bashref.html#Commands-For-History
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
else:
state.depth += 1
if len(hist) and len(hist) >= state.depth:
lastline = hist[-state.depth]
if state.depth > 1:
b.undo()
b.save_to_undo_stack()
if len(lastline.split()):
b.insert_text(lastline.split()[-1])
if getattr(ip, 'pt_cli'):
registry = ip.pt_cli.application.key_bindings_registry
registry.add_binding(Keys.Escape, u'.',
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode))(yank_last_arg)
registry.add_binding(Keys.Escape, u'_',
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode))(yank_last_arg)
ip.events.register('post_execute', reset_last_arg_depth)
@haridsv
Copy link

haridsv commented Jul 15, 2016

Thanks a lot for sharing this! I forked it and quickly added support for repeat arg such that it will work like "yank-nth-arg": https://gist.github.com/haridsv/7b8ea0a6861582b1bc0b6997f075b980

There are cases when this stops working, but I think these are bugs in prompt-toolkit, but something is better than nothing :)

@sandroden
Copy link

Very interesting, do you know if one could also add operate-and-get-next (C-o)?

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