Beispiel #1
0
Datei: sql.py Projekt: mnms/share
 def _(event):
     t = event.app.current_buffer.text.strip()
     if t.endswith(';') or len(t) == 0 or \
             t.startswith('exit') or t.startswith('help'):
         get_by_name('accept-line')(event)
     else:
         event.current_buffer.newline()
Beispiel #2
0
    def __init__(self, show_message, **kwargs):
        self.show_message = show_message
        super().__init__(**kwargs)
        key_bindings = KeyBindings()
        handle = key_bindings.add

        # Readline-style bindings.
        handle("home")(get_by_name("beginning-of-line"))
        handle("end")(get_by_name("end-of-line"))
        handle("left")(get_by_name("backward-char"))
        handle("right")(get_by_name("forward-char"))

        @handle("up")
        def _(event: KeyPressEvent) -> None:
            event.current_buffer.auto_up(count=event.arg)

        @handle("down")
        def _(event: KeyPressEvent) -> None:
            event.current_buffer.auto_down(count=event.arg)

        self._default_bindings = merge_key_bindings(
            [
                key_bindings,
                load_emacs_shift_selection_bindings()
            ])
Beispiel #3
0
    def handle_binding(name):
        try:
            binding = get_by_name(name)
        except KeyError:
            print_warning(
                f"Failed to disable clipboard for ptk action {name!r}")
            return

        if getattr(binding, "xonsh_disabled_clipboard", False):
            # binding's clipboard has already been disabled
            return

        binding.xonsh_disabled_clipboard = True
        original_handler = binding.handler

        # this needs to be defined inside a function so that ``binding`` will be the correct one
        @wraps(original_handler)
        def wrapped_handler(event):
            app = event.app
            prev = app.clipboard
            app.clipboard = dummy_clipboard
            try:
                return original_handler(event)
            finally:
                app.clipboard = prev

        binding.handler = wrapped_handler
def bind(action,*keys):
    if isinstance(action,string_types):
        action = get_by_name(action)
    if getattr(ip, 'pt_cli'):
        registry = ip.pt_cli.application.key_bindings_registry
        registry.add_binding(*keys,filter=(HasFocus(DEFAULT_BUFFER)
                                           & ~HasSelection()
                                           & insert_mode))(action)
Beispiel #5
0
def register(registry):
    handle = registry.add_binding

    handle(Keys.ControlA, filter=insert_mode)(get_by_name('beginning-of-line'))
    handle(Keys.ControlE, filter=insert_mode)(get_by_name('end-of-line'))
    handle(Keys.ControlB, filter=insert_mode)(get_by_name('backward-char'))
    handle(Keys.ControlF, filter=insert_mode)(get_by_name('forward-char'))
    #  handle(Keys.Escape, 'b', filter=insert_mode)(get_by_name('backward-word'))
    #  handle(Keys.Escape, 'f', filter=insert_mode)(get_by_name('forward-word'))
    handle(Keys.ControlK, filter=insert_mode)(get_by_name('kill-line'))
    handle(Keys.ControlY, filter=insert_mode)(get_by_name('yank'))
    handle(Keys.ControlW,
           filter=insert_mode)(get_by_name('backward-kill-word'))

    handle(Keys.ControlP)(get_by_name('previous-history'))
    handle(Keys.ControlN)(get_by_name('next-history'))
Beispiel #6
0
 def _yank(event):
     """Paste selected text."""
     buff = event.current_buffer
     if buff.selection_state:
         buff.cut_selection()
     get_by_name("yank").call(event)
Beispiel #7
0
 def delete_word(event):
     """Delete a single word (like ALT-backspace)"""
     get_by_name("backward-kill-word").call(event)
Beispiel #8
0
from prompt_toolkit.filters import HasFocus, ViInsertMode, ViNavigationMode
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.key_binding.bindings.utils import create_handle_decorator
from prompt_toolkit.key_binding.bindings.named_commands import get_by_name



def switch_to_navigation_mode(event):
    vi_state = event.cli.vi_state
    vi_state.reset(InputMode.NAVIGATION)


ip = get_ipython()

# Register keybindings if IPython is using prompt_toolkit
if getattr(ip, 'pt_cli'):
    registry = ip.pt_cli.application.key_bindings_registry

    # Either this to go to normal mode by pressing 'jj' (like from ipython's docs)
    # http://ipython.readthedocs.io/en/stable/config/details.html#keyboard-shortcuts
    # registry.add_binding(u'j', u'j',
                         # filter=(HasFocus(DEFAULT_BUFFER) & ViInsertMode()))(switch_to_navigation_mode)
    # Or this
    handle_in_mode = create_handle_decorator(registry, ViInsertMode())
    handle_in_mode(u'j', u'j')(switch_to_navigation_mode)

    # get_by_name looks for a readline cmd (like ~/.inputrc); not all cmds supported
    handle_nav_mode = create_handle_decorator(registry, ViNavigationMode())
    handle_nav_mode(u'H')(get_by_name('beginning-of-line'))
    handle_nav_mode(u'L')(get_by_name('end-of-line'))
Beispiel #9
0
def _():
    from prompt_toolkit.filters.cli import \
        ViDigraphMode, \
        ViInsertMode, \
        ViInsertMultipleMode, \
        ViNavigationMode, \
        ViReplaceMode, \
        ViSelectionMode, \
        ViWaitingForTextObjectMode

    from prompt_toolkit.key_binding.bindings.named_commands import get_by_name
    from prompt_toolkit.keys import Key, Keys

    digraph_mode = ViDigraphMode()
    insert_mode = ViInsertMode()
    insert_multiple_mode = ViInsertMultipleMode()
    navigation_mode = ViNavigationMode()
    operator_given = ViWaitingForTextObjectMode()
    replace_mode = ViReplaceMode()
    selection_mode = ViSelectionMode()

    ip = get_ipython()
    registry = ip.pt_cli.application.key_bindings_registry

    registry.add_binding(Keys.ControlB, filter=insert_mode)(
            get_by_name('beginning-of-line'))
    registry.add_binding(Keys.ControlE, filter=insert_mode)(
            get_by_name('end-of-line'))
    #registry.add_binding(Keys.Escape, 'h', filter=insert_mode)(
    #        get_by_name('backward-char'))
    #registry.add_binding(Keys.Escape, 'l', filter=insert_mode)(
    #        get_by_name('forward-char'))
    #registry.add_binding(Keys.Escape, 'b', filter=insert_mode)(
    #        get_by_name('backward-word'))
    #registry.add_binding(Keys.Escape, 'f', filter=insert_mode)(
    #        get_by_name('forward-word'))
    #registry.add_binding(Keys.Escape, 'w', filter=insert_mode)(
    #        get_by_name('forward-word'))

    # <C-U> - unix-line-rubout
    registry.add_binding(Keys.ControlK, filter=insert_mode)(
            get_by_name('kill-line'))
    registry.add_binding(Keys.ControlW, filter=insert_mode)(
            get_by_name('backward-kill-word'))
    #registry.add_binding(Keys.Escape, 'd', filter=insert_mode)(
    #        get_by_name('kill-word'))
    #registry.add_binding(Keys.Escape, 'x', filter=insert_mode)(
    #        get_by_name('delete-char'))

    #@registry.add_binding(Keys.Escape, 'j', filter=insert_mode)
    #def _(event):
    #    event.current_buffer.cursor_down(count=event.arg)
    #@registry.add_binding(Keys.Escape, 'k', filter=insert_mode)
    #def _(event):
    #    event.current_buffer.cursor_up(count=event.arg)

    # <C-I> - menu-complete
    registry.add_binding(Keys.ControlO, filter=insert_mode)(
            get_by_name('menu-complete-backward'))
    #registry.add_binding(Keys.Escape, '#', filter=insert_mode)(
    #        get_by_name('insert-comment'))

    @registry.add_binding(Keys.ControlX, Keys.ControlE,
            filter=insert_mode|navigation_mode)
    def _(event):
        event.current_buffer.open_in_editor(event.cli)
Beispiel #10
0
from IPython import get_ipython
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasFocus
from prompt_toolkit.filters import ViInsertMode
from prompt_toolkit.key_binding.bindings.named_commands import get_by_name
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.keys import Keys

ip = get_ipython()


def switch_to_navigation_mode(event):
    vi_state = event.cli.vi_state
    vi_state.input_mode = InputMode.NAVIGATION


if getattr(ip, 'pt_app', None):
    registry = ip.pt_app.key_bindings
    # use <C-o> as <esc> in vim mode
    registry.add_binding(Keys.ControlO,
                         filter=(HasFocus(DEFAULT_BUFFER)
                                 & ViInsertMode()))(switch_to_navigation_mode)
    # use <C-o><C-o> as clear screen
    registry.add_binding(Keys.ControlO,
                         Keys.ControlO,
                         filter=(HasFocus(DEFAULT_BUFFER)
                                 & ViInsertMode()))(
                                     get_by_name('clear-screen'))
Beispiel #11
0
        return [
            (Token.OutPrompt, '['),
            (Token.OutPromptNum, str(self.shell.execution_count)),
            (Token.OutPrompt, ']: '),
        ]


ip.prompts = MyPrompt(ip)

## Keyboard Shortcuts
registry = ip.pt_app.key_bindings
vi_ins = ViInsertMode()

# use emacs bindings in vi insert mode
registry.add_binding(Keys.ControlA,
                     filter=vi_ins)(get_by_name('beginning-of-line'))
registry.add_binding(Keys.ControlB,
                     filter=vi_ins)(get_by_name('backward-char'))
registry.add_binding(Keys.ControlE, filter=vi_ins)(get_by_name('end-of-line'))
registry.add_binding(Keys.ControlF, filter=vi_ins)(get_by_name('forward-char'))
registry.add_binding(Keys.ControlK, filter=vi_ins)(get_by_name('kill-line'))
registry.add_binding(Keys.ControlY, filter=vi_ins)(get_by_name('yank'))

##
## Util functions
##


def aw(future):
    '''Mock `await` keyword'''
    loop = asyncio.get_event_loop()
Beispiel #12
0
    buf.cursor_position += buf.document.get_start_of_line_position(
        after_whitespace=True)


def go_to_end_of_line(event):
    buf = event.current_buffer
    buf.cursor_position += buf.document.get_end_of_line_position()


ip = get_ipython()
ip.editing_mode = 'vi'  # make sure vi is set
insert_mode = ViInsertMode()
nav_mode = ViNavigationMode()

# better history navigation
prev_history = get_by_name('previous-history')
next_history = get_by_name('next-history')

python_version = sys.version_info.major
if python_version == 2:
    if getattr(ip, 'pt_cli', None):  # for python2.x
        registry = ip.pt_cli.application.key_bindings_registry
elif python_version == 3:
    if getattr(ip, 'pt_app', None):  # for python3.x
        registry = ip.pt_app.key_bindings

try:
    registry.add_binding(u'j',
                         u'j',
                         filter=(HasFocus(DEFAULT_BUFFER)
                                 & insert_mode))(switch_to_navigation_mode)
Beispiel #13
0
 def backward_delete_big_word(event):
     get_by_name("unix-word-rubout").call(event)
Beispiel #14
0
 def delete_small_word(event):
     get_by_name("kill-word").call(event)
Beispiel #15
0
# -*- coding: utf-8 -*-
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
from prompt_toolkit.key_binding.bindings.named_commands import get_by_name


ip = get_ipython()
insert_mode = ViInsertMode() | EmacsInsertMode()

cursor_left = lambda ev: ev.current_buffer.cursor_left()
cursor_right = lambda ev: ev.current_buffer.cursor_right()

default_filters = HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode

# Register the shortcut if IPython is using prompt_toolkit
if getattr(ip, 'pt_cli'):
    registry = ip.pt_cli.application.key_bindings_registry
    registry.add_binding(Keys.ControlH, filter=default_filters)(cursor_left)
    registry.add_binding(Keys.ControlL, filter=default_filters)(cursor_right)
    registry.add_binding(Keys.ControlB,
            filter=default_filters)(get_by_name('backward-word'))

Beispiel #16
0
def load_python_bindings(python_input):
    """
    Custom key bindings.
    """
    bindings = KeyBindings()

    sidebar_visible = Condition(lambda: python_input.show_sidebar)
    handle = bindings.add

    @handle("c-l")
    def _(event):
        """
        Clear whole screen and render again -- also when the sidebar is visible.
        """
        event.app.renderer.clear()

    @handle("c-z")
    def _(event):
        """
        Suspend.
        """
        if python_input.enable_system_bindings:
            event.app.suspend_to_background()

    # Delete word before cursor, but use all Python symbols as separators
    # (WORD=False).
    handle("c-w")(get_by_name("backward-kill-word"))

    @handle("f2")
    def _(event):
        """
        Show/hide sidebar.
        """
        python_input.show_sidebar = not python_input.show_sidebar
        if python_input.show_sidebar:
            event.app.layout.focus(python_input.ptpython_layout.sidebar)
        else:
            event.app.layout.focus_last()

    @handle("f3")
    def _(event):
        """
        Select from the history.
        """
        python_input.enter_history()

    @handle("f4")
    def _(event):
        """
        Toggle between Vi and Emacs mode.
        """
        python_input.vi_mode = not python_input.vi_mode

    @handle("f6")
    def _(event):
        """
        Enable/Disable paste mode.
        """
        python_input.paste_mode = not python_input.paste_mode

    @handle("tab",
            filter=~sidebar_visible & ~has_selection
            & tab_should_insert_whitespace)
    def _(event):
        """
        When tab should insert whitespace, do that instead of completion.
        """
        event.app.current_buffer.insert_text("    ")

    @Condition
    def is_multiline():
        return document_is_multiline_python(
            python_input.default_buffer.document)

    @handle(
        "enter",
        filter=~sidebar_visible
        & ~has_selection
        & (vi_insert_mode | emacs_insert_mode)
        & has_focus(DEFAULT_BUFFER)
        & ~is_multiline,
    )
    @handle(Keys.Escape, Keys.Enter, filter=~sidebar_visible & emacs_mode)
    def _(event):
        """
        Accept input (for single line input).
        """
        b = event.current_buffer

        if b.validate():
            # When the cursor is at the end, and we have an empty line:
            # drop the empty lines, but return the value.
            b.document = Document(text=b.text.rstrip(),
                                  cursor_position=len(b.text.rstrip()))

            b.validate_and_handle()

    @handle(
        "enter",
        filter=~sidebar_visible
        & ~has_selection
        & (vi_insert_mode | emacs_insert_mode)
        & has_focus(DEFAULT_BUFFER)
        & is_multiline,
    )
    def _(event):
        """
        Behaviour of the Enter key.

        Auto indent after newline/Enter.
        (When not in Vi navigaton mode, and when multiline is enabled.)
        """
        b = event.current_buffer
        empty_lines_required = python_input.accept_input_on_enter or 10000

        def at_the_end(b):
            """we consider the cursor at the end when there is no text after
            the cursor, or only whitespace."""
            text = b.document.text_after_cursor
            return text == "" or (text.isspace() and not "\n" in text)

        if python_input.paste_mode:
            # In paste mode, always insert text.
            b.insert_text("\n")

        elif at_the_end(b) and b.document.text.replace(" ", "").endswith(
                "\n" * (empty_lines_required - 1)):
            # When the cursor is at the end, and we have an empty line:
            # drop the empty lines, but return the value.
            if b.validate():
                b.document = Document(text=b.text.rstrip(),
                                      cursor_position=len(b.text.rstrip()))

                b.validate_and_handle()
        else:
            auto_newline(b)

    @handle(
        "c-d",
        filter=~sidebar_visible
        & has_focus(python_input.default_buffer)
        & Condition(lambda:
                    # The current buffer is empty.
                    not get_app().current_buffer.text),
    )
    def _(event):
        """
        Override Control-D exit, to ask for confirmation.
        """
        if python_input.confirm_exit:
            # Show exit confirmation and focus it (focusing is important for
            # making sure the default buffer key bindings are not active).
            python_input.show_exit_confirmation = True
            python_input.app.layout.focus(
                python_input.ptpython_layout.exit_confirmation)
        else:
            event.app.exit(exception=EOFError)

    @handle("c-c", filter=has_focus(python_input.default_buffer))
    def _(event):
        "Abort when Control-C has been pressed."
        event.app.exit(exception=KeyboardInterrupt, style="class:aborting")

    return bindings
Beispiel #17
0
def _(event):
    "Accept input during multiline mode"
    get_by_name("accept-line")(event)
Beispiel #18
0
# -*- coding: utf-8 -*-
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
from prompt_toolkit.key_binding.bindings.named_commands import get_by_name


ip = get_ipython()
insert_mode = ViInsertMode() | EmacsInsertMode()

cursor_left = lambda ev: ev.current_buffer.cursor_left()
cursor_right = lambda ev: ev.current_buffer.cursor_right()

default_filters = HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode

# Register the shortcut if IPython is using prompt_toolkit
if hasattr(ip, 'pt_cli'):
    registry = ip.pt_cli.application.key_bindings_registry
    registry.add_binding(Keys.ControlH, filter=default_filters)(cursor_left)
    registry.add_binding(Keys.ControlL, filter=default_filters)(cursor_right)
    registry.add_binding(Keys.ControlB,
            filter=default_filters)(get_by_name('backward-word'))

from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasFocus, HasSelection
from prompt_toolkit.key_binding.bindings.named_commands import get_by_name

ip = get_ipython()

# Register the shortcut if IPython is using prompt_toolkit.
if getattr(ip, 'pt_app', None):
    registry = ip.pt_app.key_bindings

    # OSX: option-f
    registry.add_binding(
            "ƒ",
            #filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection())
            filter=HasFocus(DEFAULT_BUFFER)
    )(get_by_name('forward-word'))

    # OSX: option-b
    registry.add_binding(
            "∫",
            #filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection())
            filter=HasFocus(DEFAULT_BUFFER)
    )(get_by_name('backward-word'))

    # OSX: option-b
    registry.add_binding(
            "∂",
            #filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection())
            filter=HasFocus(DEFAULT_BUFFER)
    )(get_by_name('kill-word'))