Skip to content

Instantly share code, notes, and snippets.

@carlsmith
Last active August 11, 2016 20:24
Show Gist options
  • Save carlsmith/3cb2340bbfbdfcbdd579a948717af997 to your computer and use it in GitHub Desktop.
Save carlsmith/3cb2340bbfbdfcbdd579a948717af997 to your computer and use it in GitHub Desktop.
IPython 5 startup file that makes the cursor wrap around lines when editing multiline input.
def set_terminal_keybindings():
"""If IPython is running in the classic terminal mode, this function
is called once, and is not called otherwise. We could have just used
an if-block, but this way also keeps the variables local."""
from prompt_toolkit.keys import Keys
from prompt_toolkit.filters import Filter
class StartOfLine(Filter):
"""Filter for checking whether the cursor is at the start of a
line (other than the first line) in a multiline input."""
def __call__(self, cli):
document = cli.current_buffer.document
offset = len(document.current_line_before_cursor)
at_top = document.on_first_line
return bool(offset == 0 and not at_top)
class EndOfLine(Filter):
"""Filter for checking whether the cursor is at the end of a
line (other than the last line) in a multiline input."""
def __call__(self, cli):
document = cli.current_buffer.document
at_end = document.is_cursor_at_the_end_of_line
at_bottom = document.is_cursor_at_the_end
return bool(at_end and not at_bottom)
def wrap_cursor_forwards(event):
"""Move the cursor to the start of the next line."""
buff = event.cli.current_buffer
relative_start_index = buff.document.get_start_of_line_position()
buff.cursor_left(count=abs(relative_start_index))
buff.cursor_down(count=1)
def wrap_cursor_backwards(event):
"""Move the cursor to the end of the previous line."""
buff = event.cli.current_buffer
buff.cursor_up(count=1)
relative_end_index = buff.document.get_end_of_line_position()
buff.cursor_right(count=relative_end_index)
bind_key = ip.pt_cli.application.key_bindings_registry.add_binding
bind_key(Keys.Right, filter=EndOfLine())(wrap_cursor_forwards)
bind_key(Keys.Left, filter=StartOfLine())(wrap_cursor_backwards)
ip = get_ipython()
if getattr(ip, "pt_cli"): set_terminal_keybindings()
del set_terminal_keybindings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment