Python源码示例:prompt.Condition()

示例1
def _create_buffer(self) -> Buffer:
        """
        Create the `Buffer` for the Python input.
        """
        python_buffer = Buffer(
            name=DEFAULT_BUFFER,
            complete_while_typing=Condition(lambda: self.complete_while_typing),
            enable_history_search=Condition(lambda: self.enable_history_search),
            tempfile_suffix=".py",
            history=self.history,
            completer=ThreadedCompleter(self._completer),
            validator=ConditionalValidator(
                self._validator, Condition(lambda: self.enable_input_validation)
            ),
            auto_suggest=ConditionalAutoSuggest(
                ThreadedAutoSuggest(AutoSuggestFromHistory()),
                Condition(lambda: self.enable_auto_suggest),
            ),
            accept_handler=self._accept_handler,
            on_text_changed=self._on_input_timeout,
        )

        return python_buffer 
示例2
def __init__(self, client_state):
        def get_message():
            # If there is a message to be shown for this client, show that.
            if client_state.message:
                return client_state.message
            else:
                return ''

        def get_tokens():
            message = get_message()
            if message:
                return FormattedText([
                    ('class:message', message),
                    ('[SetCursorPosition]', ''),
                    ('class:message', ' '),
                ])
            else:
                return ''

        @Condition
        def is_visible():
            return bool(get_message())

        super(MessageToolbar, self).__init__(get_tokens) 
示例3
def _build_layout(self):
        " Rebuild a new Container object and return that. "
        logger.info('Rebuilding layout.')

        if not self.pymux.arrangement.windows:
            # No Pymux windows in the arrangement.
            return Window()

        active_window = self.pymux.arrangement.get_active_window()

        # When zoomed, only show the current pane, otherwise show all of them.
        if active_window.zoom:
            return to_container(_create_container_for_process(
                self.pymux, active_window, active_window.active_pane, zoom=True))
        else:
            window = self.pymux.arrangement.get_active_window()
            return HSplit([
                # Some spacing for the top status bar.
                ConditionalContainer(
                    content=Window(height=1),
                    filter=Condition(lambda: self.pymux.enable_pane_status)),
                # The actual content.
                _create_split(self.pymux, window, window.root)
            ]) 
示例4
def __init__(self, editor):
        once_hidden = [False]  # Nonlocal

        def condition():
            # Get editor buffers
            buffers = editor.window_arrangement.editor_buffers

            # Only show when there is only one empty buffer, but once the
            # welcome message has been hidden, don't show it again.
            result = (len(buffers) == 1 and buffers[0].buffer.text == '' and
                      buffers[0].location is None and not once_hidden[0])
            if not result:
                once_hidden[0] = True
            return result

        super(WelcomeMessageWindow, self).__init__(
            Window(
                FormattedTextControl(lambda: WELCOME_MESSAGE_TOKENS),
                align=WindowAlign.CENTER,
                style="class:welcome"),
            filter=Condition(condition)) 
示例5
def load_abort_and_exit_bindings():
    """
    Basic bindings for abort (Ctrl-C) and exit (Ctrl-D).
    """
    registry = Registry()
    handle = registry.add_binding

    @handle(Keys.ControlC)
    def _(event):
        " Abort when Control-C has been pressed. "
        event.cli.abort()

    @Condition
    def ctrl_d_condition(cli):
        """ Ctrl-D binding is only active when the default buffer is selected
        and empty. """
        return (cli.current_buffer_name == DEFAULT_BUFFER and
                not cli.current_buffer.text)

    handle(Keys.ControlD, filter=ctrl_d_condition)(get_by_name('end-of-file'))

    return registry 
示例6
def load_basic_system_bindings():
    """
    Basic system bindings (For both Emacs and Vi mode.)
    """
    registry = Registry()

    suspend_supported = Condition(
        lambda cli: suspend_to_background_supported())

    @registry.add_binding(Keys.ControlZ, filter=suspend_supported)
    def _(event):
        """
        Suspend process to background.
        """
        event.cli.suspend_to_background()

    return registry 
示例7
def load_auto_suggestion_bindings():
    """
    Key bindings for accepting auto suggestion text.
    """
    registry = Registry()
    handle = registry.add_binding

    suggestion_available = Condition(
        lambda cli:
            cli.current_buffer.suggestion is not None and
            cli.current_buffer.document.is_cursor_at_the_end)

    @handle(Keys.ControlF, filter=suggestion_available)
    @handle(Keys.ControlE, filter=suggestion_available)
    @handle(Keys.Right, filter=suggestion_available)
    def _(event):
        " Accept suggestion. "
        b = event.current_buffer
        suggestion = b.suggestion

        if suggestion:
            b.insert_text(suggestion.text)

    return registry 
示例8
def _create_application(
        self, input: Optional[Input], output: Optional[Output]
    ) -> Application:
        """
        Create an `Application` instance.
        """
        return Application(
            layout=self.ptpython_layout.layout,
            key_bindings=merge_key_bindings(
                [
                    load_python_bindings(self),
                    load_auto_suggest_bindings(),
                    load_sidebar_bindings(self),
                    load_confirm_exit_bindings(self),
                    ConditionalKeyBindings(
                        load_open_in_editor_bindings(),
                        Condition(lambda: self.enable_open_in_editor),
                    ),
                    # Extra key bindings should not be active when the sidebar is visible.
                    ConditionalKeyBindings(
                        self.extra_key_bindings,
                        Condition(lambda: not self.show_sidebar),
                    ),
                ]
            ),
            color_depth=lambda: self.color_depth,
            paste_mode=Condition(lambda: self.paste_mode),
            mouse_support=Condition(lambda: self.enable_mouse_support),
            style=DynamicStyle(lambda: self._current_style),
            style_transformation=self.style_transformation,
            include_default_pygments_style=False,
            reverse_vi_search_direction=True,
            input=input,
            output=output,
        ) 
示例9
def __init__(self, window, pane, style, content):
        @Condition
        def is_selected():
            return window.active_pane == pane

        def conditional_float(char, left=None, right=None, top=None,
                              bottom=None, width=None, height=None):
            return Float(
                content=ConditionalContainer(
                    Window(char=char, style='class:border'),
                    filter=is_selected),
                left=left, right=right, top=top, bottom=bottom, width=width, height=height,
                z_index=Z_INDEX.HIGHLIGHTED_BORDER)

        self.container = FloatContainer(
            content,
            style=style,
            floats=[
                # Sides.
                conditional_float(_focused_border_vertical, left=-1, top=0, bottom=0, width=1),
                conditional_float(_focused_border_vertical, right=-1, top=0, bottom=0, width=1),
                conditional_float(_focused_border_horizontal, left=0, right=0, top=-1, height=1),
                conditional_float(_focused_border_horizontal, left=0, right=0, bottom=-1, height=1),

                # Corners.
                conditional_float(_focused_border_left_top, left=-1, top=-1, width=1, height=1),
                conditional_float(_focused_border_right_top, right=-1, top=-1, width=1, height=1),
                conditional_float(_focused_border_left_bottom, left=-1, bottom=-1, width=1, height=1),
                conditional_float(_focused_border_right_bottom, right=-1, bottom=-1, width=1, height=1),
            ]) 
示例10
def main():
    hidden = [True]  # Nonlocal
    bindings = KeyBindings()

    @bindings.add("c-t")
    def _(event):
        " When ControlT has been pressed, toggle visibility. "
        hidden[0] = not hidden[0]

    print("Type Control-T to toggle password visible.")
    password = prompt(
        "Password: ", is_password=Condition(lambda: hidden[0]), key_bindings=bindings
    )
    print("You said: %s" % password) 
示例11
def main():
    swapped = [False]  # Nonlocal
    bindings = KeyBindings()

    @bindings.add("c-t")
    def _(event):
        " When ControlT has been pressed, toggle light/dark colors. "
        swapped[0] = not swapped[0]

    def bottom_toolbar():
        if swapped[0]:
            on = "on=true"
        else:
            on = "on=false"

        return (
            HTML(
                'Press <style bg="#222222" fg="#ff8888">[control-t]</style> '
                "to swap between dark/light colors. "
                '<style bg="ansiblack" fg="ansiwhite">[%s]</style>'
            )
            % on
        )

    text = prompt(
        HTML('<style fg="#aaaaaa">Give some animals</style>: '),
        completer=html_completer,
        complete_while_typing=True,
        bottom_toolbar=bottom_toolbar,
        key_bindings=bindings,
        lexer=PygmentsLexer(HtmlLexer),
        swap_light_and_dark_colors=Condition(lambda: swapped[0]),
    )
    print("You said: %s" % text) 
示例12
def test_invert():
    assert not (~Always())()
    assert ~Never()()

    c = ~Condition(lambda: False)
    assert c() 
示例13
def test_or():
    for a in (True, False):
        for b in (True, False):
            c1 = Condition(lambda: a)
            c2 = Condition(lambda: b)
            c3 = c1 | c2

            assert isinstance(c3, Filter)
            assert c3() == a or b 
示例14
def test_and():
    for a in (True, False):
        for b in (True, False):
            c1 = Condition(lambda: a)
            c2 = Condition(lambda: b)
            c3 = c1 & c2

            assert isinstance(c3, Filter)
            assert c3() == (a and b) 
示例15
def __init__(self, editor):
        super(TabsToolbar, self).__init__(
            Window(TabsControl(editor), height=1),
            filter=Condition(lambda: len(editor.window_arrangement.tab_pages) > 1)) 
示例16
def _bufferlist_overlay_visible(editor):
    """
    True when the buffer list overlay should be displayed.
    (This is when someone starts typing ':b' or ':buffer' in the command line.)
    """
    @Condition
    def overlay_is_visible():
        app = get_app()

        text = editor.command_buffer.text.lstrip()
        return app.layout.has_focus(editor.command_buffer) and (
                any(text.startswith(p) for p in ['b ', 'b! ', 'buffer', 'buffer!']))
    return overlay_is_visible 
示例17
def __init__(self, editor):
        def get_tokens():
            if editor.message:
                return [('class:message', editor.message)]
            else:
                return []

        super(MessageToolbarBar, self).__init__(
            FormattedTextToolbar(get_tokens),
            filter=Condition(lambda: editor.message is not None)) 
示例18
def __init__(self, editor, buffer_window, buffer):
        def get_scroll_text():
            info = buffer_window.render_info

            if info:
                if info.full_height_visible:
                    return 'All'
                elif info.top_visible:
                    return 'Top'
                elif info.bottom_visible:
                    return 'Bot'
                else:
                    percentage = info.vertical_scroll_percentage
                    return '%2i%%' % percentage

            return ''

        def get_tokens():
            main_document = buffer.document

            return [
                ('class:cursorposition', '(%i,%i)' % (main_document.cursor_position_row + 1,
                                                      main_document.cursor_position_col + 1)),
                ('', ' - '),
                ('class:percentage', get_scroll_text()),
                ('', ' '),
            ]

        super(WindowStatusBarRuler, self).__init__(
            Window(
                FormattedTextControl(get_tokens),
                char=' ',
                align=WindowAlign.RIGHT,
                style='class:toolbar.status',
                height=1,
            ),
            filter=Condition(lambda: editor.show_ruler)) 
示例19
def _create_window_frame(self, editor_buffer):
        """
        Create a Window for the buffer, with underneat a status bar.
        """
        @Condition
        def wrap_lines():
            return self.editor.wrap_lines

        window = Window(
            self._create_buffer_control(editor_buffer),
            allow_scroll_beyond_bottom=True,
            scroll_offsets=ScrollOffsets(
                left=0, right=0,
                top=(lambda: self.editor.scroll_offset),
                bottom=(lambda: self.editor.scroll_offset)),
            wrap_lines=wrap_lines,
            left_margins=[ConditionalMargin(
                    margin=NumberedMargin(
                        display_tildes=True,
                        relative=Condition(lambda: self.editor.relative_number)),
                    filter=Condition(lambda: self.editor.show_line_numbers))],
            cursorline=Condition(lambda: self.editor.cursorline),
            cursorcolumn=Condition(lambda: self.editor.cursorcolumn),
            colorcolumns=(
                lambda: [ColorColumn(pos) for pos in self.editor.colorcolumn]),
            ignore_content_width=True,
            ignore_content_height=True,
            get_line_prefix=partial(self._get_line_prefix, editor_buffer.buffer))

        return HSplit([
            window,
            VSplit([
                WindowStatusBar(self.editor, editor_buffer),
                WindowStatusBarRuler(self.editor, window, editor_buffer.buffer),
            ], width=Dimension()),  # Ignore actual status bar width.
        ]), window 
示例20
def _create_application(self):
        """
        Create CommandLineInterface instance.
        """
        # Create Application.
        application = Application(
            input=self.input,
            output=self.output,
            editing_mode=EditingMode.VI,
            layout=self.editor_layout.layout,
            key_bindings=self.key_bindings,
#            get_title=lambda: get_terminal_title(self),
            style=DynamicStyle(lambda: self.current_style),
            paste_mode=Condition(lambda: self.paste_mode),
#            ignore_case=Condition(lambda: self.ignore_case),  # TODO
            include_default_pygments_style=False,
            mouse_support=Condition(lambda: self.enable_mouse_support),
            full_screen=True,
            enable_page_navigation_bindings=True)

        # Handle command line previews.
        # (e.g. when typing ':colorscheme blue', it should already show the
        # preview before pressing enter.)
        def preview(_):
            if self.application.layout.has_focus(self.command_buffer):
                self.previewer.preview(self.command_buffer.text)
        self.command_buffer.on_text_changed += preview

        return application 
示例21
def __init__(self, min_rows=3, suggested_max_column_width=30, show_meta=True, extra_filter=True):
        show_meta = to_cli_filter(show_meta)
        extra_filter = to_cli_filter(extra_filter)

        # Display filter: show when there are completions but not at the point
        # we are returning the input.
        full_filter = HasCompletions() & ~IsDone() & extra_filter

        any_completion_has_meta = Condition(lambda cli:
                any(c.display_meta for c in cli.current_buffer.complete_state.current_completions))

        # Create child windows.
        completions_window = ConditionalContainer(
            content=Window(
                content=MultiColumnCompletionMenuControl(
                    min_rows=min_rows, suggested_max_column_width=suggested_max_column_width),
                width=LayoutDimension(min=8),
                height=LayoutDimension(min=1)),
            filter=full_filter)

        meta_window = ConditionalContainer(
            content=Window(content=_SelectedCompletionMetaControl()),
            filter=show_meta & full_filter & any_completion_has_meta)

        # Initialise split.
        super(MultiColumnCompletionsMenu, self).__init__([
            completions_window,
            meta_window
        ]) 
示例22
def __init__(self, python_input, original_document):
        """
        Create an `Application` for the history screen.
        This has to be run as a sub application of `python_input`.

        When this application runs and returns, it retuns the selected lines.
        """
        self.python_input = python_input

        history_mapping = HistoryMapping(self, python_input.history, original_document)
        self.history_mapping = history_mapping

        document = Document(history_mapping.concatenated_history)
        document = Document(
            document.text,
            cursor_position=document.cursor_position
            + document.get_start_of_line_position(),
        )

        self.history_buffer = Buffer(
            document=document,
            on_cursor_position_changed=self._history_buffer_pos_changed,
            accept_handler=(
                lambda buff: get_app().exit(result=self.default_buffer.text)
            ),
            read_only=True,
        )

        self.default_buffer = Buffer(
            name=DEFAULT_BUFFER,
            document=history_mapping.get_new_document(),
            on_cursor_position_changed=self._default_buffer_pos_changed,
            read_only=True,
        )

        self.help_buffer = Buffer(document=Document(HELP_TEXT, 0), read_only=True)

        self.history_layout = HistoryLayout(self)

        self.app = Application(
            layout=self.history_layout.layout,
            full_screen=True,
            style=python_input._current_style,
            mouse_support=Condition(lambda: python_input.enable_mouse_support),
            key_bindings=create_key_bindings(self, python_input, history_mapping),
        ) 
示例23
def _create_buffer_control(self, editor_buffer):
        """
        Create a new BufferControl for a given location.
        """
        @Condition
        def preview_search():
            return self.editor.incsearch

        input_processors = [
            # Processor for visualising spaces. (should come before the
            # selection processor, otherwise, we won't see these spaces
            # selected.)
            ConditionalProcessor(
                ShowTrailingWhiteSpaceProcessor(),
                Condition(lambda: self.editor.display_unprintable_characters)),

            # Replace tabs by spaces.
            TabsProcessor(
                tabstop=(lambda: self.editor.tabstop),
                char1=(lambda: '|' if self.editor.display_unprintable_characters else ' '),
                char2=(lambda: _try_char('\u2508', '.', get_app().output.encoding())
                                       if self.editor.display_unprintable_characters else ' '),
            ),

            # Reporting of errors, for Pyflakes.
            ReportingProcessor(editor_buffer),
            HighlightSelectionProcessor(),
            ConditionalProcessor(
                HighlightSearchProcessor(),
                Condition(lambda: self.editor.highlight_search)),
            ConditionalProcessor(
                HighlightIncrementalSearchProcessor(),
                Condition(lambda: self.editor.highlight_search) & preview_search),
            HighlightMatchingBracketProcessor(),
            DisplayMultipleCursors(),
        ]

        return BufferControl(
            lexer=DocumentLexer(editor_buffer),
            include_default_input_processors=False,
            input_processors=input_processors,
            buffer=editor_buffer.buffer,
            preview_search=preview_search,
            search_buffer_control=self.search_control,
            focus_on_click=True)