Beispiel #1
0
 def file_selection(self, filenum):
     sublayout = containers.VSplit([
         self.text_block(lambda x: [(Token, u" {:>2d}:".format(filenum))],
                         dont_extend_width=True),
         containers.Window(
             content=controls.BufferControl(buffer_name='FN%d' % filenum),
             dont_extend_height=True)
     ])
     return sublayout
Beispiel #2
0
def normal_text_window(name=None,
                       lang=None,
                       lineno=False,
                       leading_space=False,
                       trailing_space=False,
                       width=None,
                       height=None):
    if name is None:
        name = buffers.DEFAULT_BUFFER
    bf_attrs = {
        'buffer_name': name,
        'lexer': style.get_lexer_by_lang(lang),
        'highlighters': [highlighters.SelectionHighlighter()]
    }

    input_processors = []
    if leading_space:
        input_processors.append(processors.ShowLeadingWhiteSpaceProcessor())
    if trailing_space:
        input_processors.append(processors.ShowTrailingWhiteSpaceProcessor())
    if input_processors:
        bf_attrs['input_processors'] = input_processors

    win_attrs = {}
    left_margins = []
    if lineno:
        left_margins.append(NumberredMargin(name))
    if left_margins:
        win_attrs['left_margins'] = left_margins

    if height is not None:
        win_attrs['height'] = height
    if width is not None:
        win_attrs['width'] = width

    content = controls.BufferControl(**bf_attrs)
    return containers.Window(content=content, **win_attrs)
def CreatePromptLayout(config,
                       lexer=None,
                       is_password=False,
                       get_prompt_tokens=None,
                       get_continuation_tokens=None,
                       get_bottom_status_tokens=None,
                       get_bottom_toolbar_tokens=None,
                       extra_input_processors=None,
                       multiline=False,
                       show_help=True,
                       wrap_lines=True):
    """Create a container instance for the prompt."""
    assert get_bottom_status_tokens is None or callable(
        get_bottom_status_tokens)
    assert get_bottom_toolbar_tokens is None or callable(
        get_bottom_toolbar_tokens)
    assert get_prompt_tokens is None or callable(get_prompt_tokens)
    assert not (config.prompt and get_prompt_tokens)

    multi_column_completion_menu = filters.to_cli_filter(
        config.multi_column_completion_menu)
    multiline = filters.to_cli_filter(multiline)

    if get_prompt_tokens is None:
        get_prompt_tokens = lambda _: [(token.Token.Prompt, config.prompt)]

    has_before_tokens, get_prompt_tokens_1, get_prompt_tokens_2 = (
        shortcuts._split_multiline_prompt(get_prompt_tokens))  # pylint: disable=protected-access
    # TODO(b/35347840): reimplement _split_multiline_prompt to remove
    #                   protected-access.

    # Create processors list.
    input_processors = [
        processors.ConditionalProcessor(
            # By default, only highlight search when the search
            # input has the focus. (Note that this doesn't mean
            # there is no search: the Vi 'n' binding for instance
            # still allows to jump to the next match in
            # navigation mode.)
            processors.HighlightSearchProcessor(preview_search=True),
            filters.HasFocus(enums.SEARCH_BUFFER)),
        processors.HighlightSelectionProcessor(),
        processors.ConditionalProcessor(
            processors.AppendAutoSuggestion(),
            filters.HasFocus(enums.DEFAULT_BUFFER)
            & ~filters.IsDone()),
        processors.ConditionalProcessor(processors.PasswordProcessor(),
                                        is_password),
    ]

    if extra_input_processors:
        input_processors.extend(extra_input_processors)

    # Show the prompt before the input using the DefaultPrompt processor.
    # This also replaces it with reverse-i-search and 'arg' when required.
    # (Only for single line mode.)
    # (DefaultPrompt should always be at the end of the processors.)
    input_processors.append(
        processors.ConditionalProcessor(
            prompt.DefaultPrompt(get_prompt_tokens_2), ~multiline))

    # Create toolbars
    toolbars = []
    if config.fixed_prompt_position:
        help_height = dimension.LayoutDimension.exact(config.help_lines)
        help_filter = (show_help & ~filters.IsDone()
                       & filters.RendererHeightIsKnown())
    else:
        help_height = dimension.LayoutDimension(preferred=config.help_lines,
                                                max=config.help_lines)
        help_filter = (show_help & UserTypingFilter & ~filters.IsDone()
                       & filters.RendererHeightIsKnown())
    toolbars.append(
        containers.ConditionalContainer(layout.HSplit([
            layout.Window(
                controls.FillControl(char=screen.Char('_', token.Token.HSep)),
                height=dimension.LayoutDimension.exact(1)),
            layout.Window(help_window.HelpWindowControl(
                default_char=screen.Char(' ', token.Token.Toolbar)),
                          height=help_height),
        ]),
                                        filter=help_filter))
    if (config.bottom_status_line and get_bottom_status_tokens
            or config.bottom_bindings_line and get_bottom_toolbar_tokens):
        windows = []
        windows.append(
            layout.Window(
                controls.FillControl(char=screen.Char('_', token.Token.HSep)),
                height=dimension.LayoutDimension.exact(1)))
        if config.bottom_status_line and get_bottom_status_tokens:
            windows.append(
                layout.Window(controls.TokenListControl(
                    get_bottom_status_tokens,
                    default_char=screen.Char(' ', token.Token.Toolbar)),
                              height=dimension.LayoutDimension.exact(1)))
        if config.bottom_bindings_line and get_bottom_toolbar_tokens:
            windows.append(
                layout.Window(controls.TokenListControl(
                    get_bottom_toolbar_tokens,
                    default_char=screen.Char(' ', token.Token.Toolbar)),
                              height=dimension.LayoutDimension.exact(1)))
        toolbars.append(
            containers.ConditionalContainer(layout.HSplit(windows),
                                            filter=~filters.IsDone()
                                            & filters.RendererHeightIsKnown()))

    def GetHeight(cli):
        """Determine the height for the input buffer."""
        # If there is an autocompletion menu to be shown, make sure that our
        # layout has at least a minimal height in order to display it.
        if cli.config.completion_menu_lines and not cli.is_done:
            # Reserve the space, either when there are completions, or when
            # `complete_while_typing` is true and we expect completions very
            # soon.
            buf = cli.current_buffer
            # if UserTypingFilter(cli) or not buf.text or buf.complete_state:
            if UserTypingFilter(cli) or buf.complete_state:
                return dimension.LayoutDimension(
                    min=cli.config.completion_menu_lines + 1)
        return dimension.LayoutDimension()

    # Create and return Container instance.
    return layout.HSplit([
        # The main input, with completion menus floating on top of it.
        containers.FloatContainer(
            layout.HSplit([
                containers.ConditionalContainer(
                    layout.Window(
                        controls.TokenListControl(get_prompt_tokens_1),
                        dont_extend_height=True,
                        wrap_lines=wrap_lines,
                    ),
                    filters.Condition(has_before_tokens),
                ),
                layout.Window(
                    controls.BufferControl(
                        input_processors=input_processors,
                        lexer=lexer,
                        # Enable preview_search, we want to have immediate
                        # feedback in reverse-i-search mode.
                        preview_search=True,
                    ),
                    get_height=GetHeight,
                    left_margins=[
                        # In multiline mode, use the window margin to display
                        # the prompt and continuation tokens.
                        margins.ConditionalMargin(
                            margins.PromptMargin(get_prompt_tokens_2,
                                                 get_continuation_tokens),
                            filter=multiline,
                        ),
                    ],
                    wrap_lines=wrap_lines,
                ),
            ]),
            [
                # Completion menus.
                layout.Float(
                    xcursor=True,
                    ycursor=True,
                    content=menus.CompletionsMenu(
                        max_height=16,
                        scroll_offset=1,
                        extra_filter=(filters.HasFocus(enums.DEFAULT_BUFFER)
                                      & ~multi_column_completion_menu),
                    ),
                ),
                layout.Float(
                    ycursor=True,
                    content=menus.MultiColumnCompletionsMenu(
                        show_meta=True,
                        extra_filter=(filters.HasFocus(enums.DEFAULT_BUFFER)
                                      & multi_column_completion_menu),
                    ),
                ),
            ],
        ),
        pt_toolbars.ValidationToolbar(),
        pt_toolbars.SystemToolbar(),

        # In multiline mode, we use two toolbars for 'arg' and 'search'.
        containers.ConditionalContainer(pt_toolbars.ArgToolbar(), multiline),
        containers.ConditionalContainer(pt_toolbars.SearchToolbar(),
                                        multiline),
    ] + toolbars)
Beispiel #4
0
            buf.validation_error = None
        except Exception as e:
            buf.validation_error = ValidationError(message=repr(e))
            buf.validation_state = ValidationState.INVALID


path_completer = completion.PathCompleter(expanduser=True)

buffer = Buffer(
    on_text_changed=on_text_changed,
    complete_while_typing=True,
    completer=path_completer,
    multiline=False,
)
header = controls.FormattedTextControl("Press C-d or C-c or C-g to quit")
buffer_control = controls.BufferControl(buffer=buffer)
content_display = controls.FormattedTextControl(text="hello world")
current_display = controls.FormattedTextControl(text="")

layout = Layout(
    containers.HSplit([
        containers.Window(header, height=1, style="reverse"),
        containers.FloatContainer(
            containers.HSplit([
                containers.Window(content=buffer_control, height=1),
                containers.Window(height=1, char="-", style="class:line"),
                containers.Window(content=current_display, height=1),
                containers.Window(height=1, char="-", style="class:line"),
                containers.Window(content=content_display),
            ]),
            floats=[
Beispiel #5
0
top_text = "Press C-c or C-g to quit"
buffer = Buffer(
    on_text_changed=on_text_changed,
    complete_while_typing=True,
    completer=animal_completer,
)
header = controls.FormattedTextControl(top_text)
display = controls.FormattedTextControl(text="hello world")

layout = Layout(
    containers.HSplit([
        containers.Window(header, height=1, style="reverse"),
        containers.FloatContainer(
            containers.HSplit([
                containers.Window(content=controls.BufferControl(
                    buffer=buffer))
            ]),
            floats=[
                containers.Float(
                    xcursor=True,
                    ycursor=True,
                    content=menus.CompletionsMenu(max_height=16,
                                                  scroll_offset=1),
                )
            ],
        ),
        containers.Window(height=1, char="-", style="class:line"),
        containers.Window(content=display),
    ]))

kb = KeyBindings()
Beispiel #6
0
    def create(self):
        self.buffer = pt.buffer.Buffer(
            accept_action=pt.buffer.AcceptAction(handler=self.handle_command),
            history=self.history,
            completer=CommandCompleter(self.valid_commands),
            on_cursor_position_changed=self.handle_help_bar,
        )
        self.buffers = {'PROMPT': self.buffer}
        for i in range(10):
            self.buffers['FN%d' % i] = pt.buffer.Buffer(
                accept_action=pt.buffer.AcceptAction(handler=self.save_state),
                history=None,
                completer=None)

        divider_line = lambda: containers.Window(
            content=controls.FillControl('-', token=Token.Line),
            height=dimension.LayoutDimension.exact(1))

        buffer_sublayout = containers.VSplit([
            # containers.Window(content=controls.TokenListControl(get_tokens=lambda cli : ([Token.Red, u'> ']))),
            self.text_block(lambda x: [(Token.Prompt, u">> ")],
                            dont_extend_width=True),
            containers.Window(
                content=controls.BufferControl(buffer_name='PROMPT'),
                dont_extend_height=True),
        ])

        self.main_layout = containers.HSplit([
            divider_line(),
            self.text_block(self.test_mode),
            self.text_block(self.test_settings),
            divider_line(),
            self.text_block(self.turn_table_settings),
            divider_line(),
            self.text_block(self.save_location_setting),
            divider_line(),
            buffer_sublayout,
            containers.Window(content=controls.TokenListControl(
                get_tokens=self.status_bar)),
        ])

        self.save_load_layout = containers.HSplit(
            [divider_line()] + [self.file_selection(i) for i in range(10)] + [
                divider_line(),
                containers.Window(content=controls.TokenListControl(
                    get_tokens=self.status_bar)),
            ])
        self.update_state_name_display()

        loop = pt.shortcuts.create_eventloop()
        application = pt.application.Application(
            layout=self.main_layout,
            buffers=self.buffers,
            style=self.style,
            initial_focussed_buffer='PROMPT',
            key_bindings_registry=registry)
        cli = pt.interface.CommandLineInterface(application=application,
                                                eventloop=loop)
        cli.state = "MAIN"
        self.init_key_bindings()
        cli.run()
Beispiel #7
0
top_text = "Press C-c or C-g to quit"
buffer = Buffer(
    on_text_changed=on_text_changed,
    complete_while_typing=True,
    completer=animal_completer,
)
header = controls.FormattedTextControl(top_text)
display = controls.FormattedTextControl(text="hello world")

layout = Layout(
    containers.HSplit([
        containers.Window(header, height=1, style="reverse"),
        containers.FloatContainer(
            containers.HSplit([
                containers.Window(
                    content=controls.BufferControl(buffer=buffer), height=1),
                containers.Window(height=1, char="-", style="class:line"),
                containers.Window(content=display),
            ]),
            floats=[
                containers.Float(
                    xcursor=True,
                    ycursor=True,
                    content=menus.CompletionsMenu(max_height=12,
                                                  scroll_offset=1),
                )
            ],
        ),
    ]))

kb = KeyBindings()