Python prompt_toolkit.layout.controls.BufferControl() Examples

The following are 21 code examples of prompt_toolkit.layout.controls.BufferControl(). 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.layout.controls , or try the search function .
Example #1
Source File: processors.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(
        self,
        buffer_control: "BufferControl",
        document: Document,
        lineno: int,
        source_to_display: SourceToDisplay,
        fragments: StyleAndTextTuples,
        width: int,
        height: int,
    ) -> None:

        self.buffer_control = buffer_control
        self.document = document
        self.lineno = lineno
        self.source_to_display = source_to_display
        self.fragments = fragments
        self.width = width
        self.height = height 
Example #2
Source File: layout.py    From azure-cli-shell with MIT License 5 votes vote down vote up
def get_descript(lexer):
    """ command description window """
    return Window(
        content=BufferControl(
            buffer_name="description",
            lexer=lexer)) 
Example #3
Source File: layout.py    From pyvim with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, editor):
        super(CommandLine, self).__init__(
            Window(
                BufferControl(
                    buffer=editor.command_buffer,
                    input_processors=[BeforeInput(':')],
                    lexer=create_command_lexer()),
                height=1),
            filter=has_focus(editor.command_buffer)) 
Example #4
Source File: test_layout.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_layout_class():
    c1 = BufferControl()
    c2 = BufferControl()
    c3 = BufferControl()
    win1 = Window(content=c1)
    win2 = Window(content=c2)
    win3 = Window(content=c3)

    layout = Layout(container=VSplit([HSplit([win1, win2]), win3]))

    # Listing of windows/controls.
    assert list(layout.find_all_windows()) == [win1, win2, win3]
    assert list(layout.find_all_controls()) == [c1, c2, c3]

    # Focusing something.
    layout.focus(c1)
    assert layout.has_focus(c1)
    assert layout.has_focus(win1)
    assert layout.current_control == c1
    assert layout.previous_control == c1

    layout.focus(c2)
    assert layout.has_focus(c2)
    assert layout.has_focus(win2)
    assert layout.current_control == c2
    assert layout.previous_control == c1

    layout.focus(win3)
    assert layout.has_focus(c3)
    assert layout.has_focus(win3)
    assert layout.current_control == c3
    assert layout.previous_control == c2

    # Pop focus. This should focus the previous control again.
    layout.focus_last()
    assert layout.has_focus(c2)
    assert layout.has_focus(win2)
    assert layout.current_control == c2
    assert layout.previous_control == c1 
Example #5
Source File: processors.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_main_buffer(
        self, buffer_control: "BufferControl"
    ) -> Optional["BufferControl"]:
        from prompt_toolkit.layout.controls import BufferControl

        prev_control = get_app().layout.search_target_buffer_control
        if (
            isinstance(prev_control, BufferControl)
            and prev_control.search_buffer_control == buffer_control
        ):
            return prev_control
        return None 
Example #6
Source File: processors.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_search_text(self, buffer_control: "BufferControl") -> str:
        """
        The text we are searching for.
        """
        # When the search buffer has focus, take that text.
        search_buffer = buffer_control.search_buffer
        if search_buffer is not None and search_buffer.text:
            return search_buffer.text
        return "" 
Example #7
Source File: processors.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unpack(
        self,
    ) -> Tuple[
        "BufferControl", Document, int, SourceToDisplay, StyleAndTextTuples, int, int
    ]:
        return (
            self.buffer_control,
            self.document,
            self.lineno,
            self.source_to_display,
            self.fragments,
            self.width,
            self.height,
        ) 
Example #8
Source File: search.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_reverse_search_links(
    layout: "Layout",
) -> Dict["BufferControl", "SearchBufferControl"]:
    """
    Return mapping from BufferControl to SearchBufferControl.
    """
    return {
        buffer_control: search_buffer_control
        for search_buffer_control, buffer_control in layout.search_links.items()
    } 
Example #9
Source File: search.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def accept_search() -> None:
    """
    Accept current search query. Focus original `BufferControl` again.
    """
    layout = get_app().layout

    search_control = layout.current_control
    target_buffer_control = layout.search_target_buffer_control

    from prompt_toolkit.layout.controls import BufferControl

    if not isinstance(search_control, BufferControl):
        return
    if target_buffer_control is None:
        return

    search_state = target_buffer_control.search_state

    # Update search state.
    if search_control.buffer.text:
        search_state.text = search_control.buffer.text

    # Apply search.
    target_buffer_control.buffer.apply_search(
        search_state, include_current_position=True
    )

    # Add query to history of search line.
    search_control.buffer.append_to_history()

    # Stop search and focus previous control again.
    stop_search(target_buffer_control) 
Example #10
Source File: search.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def do_incremental_search(direction: SearchDirection, count: int = 1) -> None:
    """
    Apply search, but keep search buffer focused.
    """
    assert is_searching()

    layout = get_app().layout

    # Only search if the current control is a `BufferControl`.
    from prompt_toolkit.layout.controls import BufferControl

    search_control = layout.current_control
    if not isinstance(search_control, BufferControl):
        return

    prev_control = layout.search_target_buffer_control
    if prev_control is None:
        return
    search_state = prev_control.search_state

    # Update search_state.
    direction_changed = search_state.direction != direction

    search_state.text = search_control.buffer.text
    search_state.direction = direction

    # Apply search to current buffer.
    if not direction_changed:
        prev_control.buffer.apply_search(
            search_state, include_current_position=False, count=count
        ) 
Example #11
Source File: search.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start_search(
    buffer_control: Optional["BufferControl"] = None,
    direction: SearchDirection = SearchDirection.FORWARD,
) -> None:
    """
    Start search through the given `buffer_control` using the
    `search_buffer_control`.

    :param buffer_control: Start search for this `BufferControl`. If not given,
        search through the current control.
    """
    from prompt_toolkit.layout.controls import BufferControl

    assert buffer_control is None or isinstance(buffer_control, BufferControl)

    layout = get_app().layout

    # When no control is given, use the current control if that's a BufferControl.
    if buffer_control is None:
        if not isinstance(layout.current_control, BufferControl):
            return
        buffer_control = layout.current_control

    # Only if this control is searchable.
    search_buffer_control = buffer_control.search_buffer_control

    if search_buffer_control:
        buffer_control.search_state.direction = direction

        # Make sure to focus the search BufferControl
        layout.focus(search_buffer_control)

        # Remember search link.
        layout.search_links[search_buffer_control] = buffer_control

        # If we're in Vi mode, make sure to go into insert mode.
        get_app().vi_state.input_mode = InputMode.INSERT 
Example #12
Source File: app.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def control_is_searchable() -> bool:
    " When the current UIControl is searchable. "
    from prompt_toolkit.layout.controls import BufferControl

    control = get_app().layout.current_control

    return (
        isinstance(control, BufferControl) and control.search_buffer_control is not None
    ) 
Example #13
Source File: app.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def buffer_has_focus() -> bool:
    """
    Enabled when the currently focused control is a `BufferControl`.
    """
    return get_app().layout.buffer_has_focus 
Example #14
Source File: named_commands.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reverse_search_history(event: E) -> None:
    """
    Search backward starting at the current line and moving `up` through
    the history as necessary. This is an incremental search.
    """
    control = event.app.layout.current_control

    if isinstance(control, BufferControl) and control.search_buffer_control:
        event.app.current_search_state.direction = SearchDirection.BACKWARD
        event.app.layout.current_control = control.search_buffer_control


#
# Commands for changing text
# 
Example #15
Source File: application.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def current_search_state(self) -> SearchState:
        """
        Return the current :class:`.SearchState`. (The one for the focused
        :class:`.BufferControl`.)
        """
        ui_control = self.layout.current_control
        if isinstance(ui_control, BufferControl):
            return ui_control.search_state
        else:
            return SearchState()  # Dummy search state.  (Don't return None!) 
Example #16
Source File: layout.py    From azure-cli-shell with MIT License 5 votes vote down vote up
def get_example(config, exam_lex):
    """ example description window """
    if config.BOOLEAN_STATES[config.config.get('Layout', 'examples')]:
        return Window(
            content=BufferControl(
                buffer_name="examples",
                lexer=exam_lex))
    else:
        return get_empty() 
Example #17
Source File: layout.py    From azure-cli-shell with MIT License 5 votes vote down vote up
def get_param(lexer):
    """ parameter description window """
    return Window(
        content=BufferControl(
            buffer_name="parameter",
            lexer=lexer)) 
Example #18
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 #19
Source File: processors.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _content(
        self, main_control: "BufferControl", ti: TransformationInput
    ) -> "UIContent":
        from prompt_toolkit.layout.controls import BufferControl

        # Emulate the BufferControl through which we are searching.
        # For this we filter out some of the input processors.
        excluded_processors = tuple(self._excluded_input_processors)

        def filter_processor(item: Processor) -> Optional[Processor]:
            """ Filter processors from the main control that we want to disable
            here. This returns either an accepted processor or None. """
            # For a `_MergedProcessor`, check each individual processor, recursively.
            if isinstance(item, _MergedProcessor):
                accepted_processors = [filter_processor(p) for p in item.processors]
                return merge_processors(
                    [p for p in accepted_processors if p is not None]
                )

            # For a `ConditionalProcessor`, check the body.
            elif isinstance(item, ConditionalProcessor):
                p = filter_processor(item.processor)
                if p:
                    return ConditionalProcessor(p, item.filter)

            # Otherwise, check the processor itself.
            else:
                if not isinstance(item, excluded_processors):
                    return item

            return None

        filtered_processor = filter_processor(
            merge_processors(main_control.input_processors or [])
        )
        highlight_processor = HighlightIncrementalSearchProcessor()

        if filtered_processor:
            new_processors = [filtered_processor, highlight_processor]
        else:
            new_processors = [highlight_processor]

        from .controls import SearchBufferControl

        assert isinstance(ti.buffer_control, SearchBufferControl)

        buffer_control = BufferControl(
            buffer=main_control.buffer,
            input_processors=new_processors,
            include_default_input_processors=False,
            lexer=main_control.lexer,
            preview_search=True,
            search_buffer_control=cast(SearchBufferControl, ti.buffer_control),
        )

        return buffer_control.create_content(ti.width, ti.height, preview_search=True) 
Example #20
Source File: layout.py    From pyvim with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self, editor, window_arrangement):
        self.editor = editor  # Back reference to editor.
        self.window_arrangement = window_arrangement

        # Mapping from (`window_arrangement.Window`, `EditorBuffer`) to a frame
        # (Layout instance).
        # We keep this as a cache in order to easily reuse the same frames when
        # the layout is updated. (We don't want to create new frames on every
        # update call, because that way, we would loose some state, like the
        # vertical scroll offset.)
        self._frames = {}

        self._fc = FloatContainer(
            content=VSplit([
                Window(BufferControl())  # Dummy window
            ]),
            floats=[
                Float(xcursor=True, ycursor=True,
                      content=CompletionsMenu(max_height=12,
                                              scroll_offset=2,
                                              extra_filter=~has_focus(editor.command_buffer))),
                Float(content=BufferListOverlay(editor), bottom=1, left=0),
                Float(bottom=1, left=0, right=0, height=1,
                      content=ConditionalContainer(
                          CompletionsToolbar(),
                          filter=has_focus(editor.command_buffer) &
                                       ~_bufferlist_overlay_visible(editor) &
                                       Condition(lambda: editor.show_wildmenu))),
                Float(bottom=1, left=0, right=0, height=1,
                      content=ValidationToolbar()),
                Float(bottom=1, left=0, right=0, height=1,
                      content=MessageToolbarBar(editor)),
                Float(content=WelcomeMessageWindow(editor),
                      height=WELCOME_MESSAGE_HEIGHT,
                      width=WELCOME_MESSAGE_WIDTH),
            ]
        )

        search_toolbar = SearchToolbar(vi_mode=True, search_buffer=editor.search_buffer)
        self.search_control = search_toolbar.control

        self.layout = Layout(FloatContainer(
            content=HSplit([
                TabsToolbar(editor),
                self._fc,
                CommandLine(editor),
                ReportMessageToolbar(editor),
                SystemToolbar(),
                search_toolbar,
            ]),
            floats=[
                Float(right=0, height=1, bottom=0, width=5,
                      content=SimpleArgToolbar()),
            ]
        )) 
Example #21
Source File: layout.py    From pyvim with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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)