Python prompt_toolkit.filters.HasFocus() Examples

The following are 6 code examples of prompt_toolkit.filters.HasFocus(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module prompt_toolkit.filters , or try the search function .
Example #1
Source File: layout.py    From azure-cli-shell with MIT License 5 votes vote down vote up
def create_tutorial_layout(lex):
    """ layout for example tutorial """
    lexer, _, _ = get_lexers(lex, None, None)
    layout_full = HSplit([
        FloatContainer(
            Window(
                BufferControl(
                    input_processors=input_processors,
                    lexer=lexer,
                    preview_search=Always()),
                get_height=get_height),
            [
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(
                          max_height=MAX_COMPLETION,
                          scroll_offset=1,
                          extra_filter=(HasFocus(DEFAULT_BUFFER))))]),
        ConditionalContainer(
            HSplit([
                get_hline(),
                get_param(lexer),
                get_hline(),
                Window(
                    content=BufferControl(
                        buffer_name='example_line',
                        lexer=lexer
                    ),
                ),
                Window(
                    TokenListControl(
                        get_tutorial_tokens,
                        default_char=Char(' ', Token.Toolbar)),
                    height=D.exact(1)),
            ]),
            filter=~IsDone() & RendererHeightIsKnown()
        )
    ])
    return layout_full 
Example #2
Source File: emacs.py    From android_universal with MIT License 5 votes vote down vote up
def load_emacs_system_bindings():
    registry = ConditionalRegistry(Registry(), EmacsMode())
    handle = registry.add_binding

    has_focus = HasFocus(SYSTEM_BUFFER)

    @handle(Keys.Escape, '!', filter= ~has_focus)
    def _(event):
        """
        M-'!' opens the system prompt.
        """
        event.cli.push_focus(SYSTEM_BUFFER)

    @handle(Keys.Escape, filter=has_focus)
    @handle(Keys.ControlG, filter=has_focus)
    @handle(Keys.ControlC, filter=has_focus)
    def _(event):
        """
        Cancel system prompt.
        """
        event.cli.buffers[SYSTEM_BUFFER].reset()
        event.cli.pop_focus()

    @handle(Keys.ControlJ, filter=has_focus)
    def _(event):
        """
        Run system command.
        """
        system_line = event.cli.buffers[SYSTEM_BUFFER]
        event.cli.run_system_command(system_line.text)
        system_line.reset(append_to_history=True)

        # Focus previous buffer again.
        event.cli.pop_focus()

    return registry 
Example #3
Source File: vi.py    From android_universal with MIT License 5 votes vote down vote up
def load_vi_system_bindings():
    registry = ConditionalRegistry(Registry(), ViMode())
    handle = registry.add_binding

    has_focus = filters.HasFocus(SYSTEM_BUFFER)
    navigation_mode = ViNavigationMode()

    @handle('!', filter=~has_focus & navigation_mode)
    def _(event):
        """
        '!' opens the system prompt.
        """
        event.cli.push_focus(SYSTEM_BUFFER)
        event.cli.vi_state.input_mode = InputMode.INSERT

    @handle(Keys.Escape, filter=has_focus)
    @handle(Keys.ControlC, filter=has_focus)
    def _(event):
        """
        Cancel system prompt.
        """
        event.cli.vi_state.input_mode = InputMode.NAVIGATION
        event.cli.buffers[SYSTEM_BUFFER].reset()
        event.cli.pop_focus()

    @handle(Keys.ControlJ, filter=has_focus)
    def _(event):
        """
        Run system command.
        """
        event.cli.vi_state.input_mode = InputMode.NAVIGATION

        system_buffer = event.cli.buffers[SYSTEM_BUFFER]
        event.cli.run_system_command(system_buffer.text)
        system_buffer.reset(append_to_history=True)

        # Focus previous buffer again.
        event.cli.pop_focus()

    return registry 
Example #4
Source File: toolbars.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self):
        super(SystemToolbar, self).__init__(
            content=Window(
                SystemToolbarControl(),
                height=LayoutDimension.exact(1)),
            filter=HasFocus(SYSTEM_BUFFER) & ~IsDone()) 
Example #5
Source File: repl.py    From crash with Apache License 2.0 4 votes vote down vote up
def loop(cmd, history_file):
    buf = create_buffer(cmd, history_file)
    key_bindings = KeyBindings()
    bind_keys(buf, key_bindings)
    layout = create_layout(
        buffer=buf,
        multiline=True,
        lexer=PostgresLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ],
        get_bottom_toolbar_tokens=lambda: get_toolbar_tokens(cmd),
        get_prompt_tokens=lambda: [('class:prompt', 'cr> ')]
    )
    output = get_default_output()
    app = Application(
        layout=layout,
        style=style_from_pygments_cls(CrateStyle),
        key_bindings=merge_key_bindings([
            key_bindings,
            load_open_in_editor_bindings()
        ]),
        editing_mode=_get_editing_mode(),
        output=output
    )
    cmd.get_num_columns = lambda: output.get_size().columns

    while True:
        try:
            text = app.run()
            if text:
                cmd.process(text)
            buf.reset()
        except ProgrammingError as e:
            if '401' in e.message:
                username = cmd.username
                password = cmd.password
                cmd.username = input('Username: ')
                cmd.password = getpass()
                try:
                    cmd.process(text)
                except ProgrammingError as ex:
                    # fallback to existing user/pw
                    cmd.username = username
                    cmd.password = password
                    cmd.logger.warn(str(ex))
            else:
                cmd.logger.warn(str(e))
        except KeyboardInterrupt:
            if isinstance(app.layout.current_control, SearchBufferControl):
                app.layout.current_control = app.layout.previous_control
            else:
                cmd.logger.warn("Query not cancelled. Run KILL <jobId> to cancel it")
                buf.reset()
        except EOFError:
            cmd.logger.warn('Bye!')
            return 
Example #6
Source File: main.py    From athenacli with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _build_prompt_app(self, history):
        key_bindings = cli_bindings(self)

        def get_message():
            prompt = self.get_prompt(self.prompt)
            if len(prompt) > self.MAX_LEN_PROMPT:
                prompt = self.get_prompt('\\r:\\d> ')
            return [('class:prompt', prompt)]

        def get_continuation(width, line_number, is_soft_wrap):
            continuation = ' ' * (width -1) + ' '
            return [('class:continuation', continuation)]

        def show_suggestion_tip():
            return self.iterations < 2

        get_toolbar_tokens = create_toolbar_tokens_func(
            self, show_suggestion_tip)

        with self._completer_lock:
            if self.key_bindings == 'vi':
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS

            self.prompt_app = PromptSession(
                lexer=PygmentsLexer(Lexer),
                reserve_space_for_menu=self.get_reserved_space(),
                message=get_message,
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=CompleteStyle.COLUMN,
                input_processors=[ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()
                )],
                tempfile_suffix='.sql',
                completer=DynamicCompleter(lambda: self.completer),
                history=history,
                auto_suggest=AutoSuggestFromHistory(),
                complete_while_typing=True,
                multiline=cli_is_multiline(self),
                style=style_factory(self.syntax_style, self.cli_style),
                include_default_pygments_style=False,
                key_bindings=key_bindings,
                enable_open_in_editor=True,
                enable_system_prompt=True,
                editing_mode=editing_mode,
                search_ignore_case=True
            )