Ejemplo n.º 1
0
def _draw_number(screen, x_offset, number, token=Token.Clock, default_token=Token):
    " Write number at position. "
    for y, row in enumerate(_numbers[number]):
        screen_row = screen.data_buffer[y]
        for x, n in enumerate(row):
            t = token if n == '#' else default_token
            screen_row[x + x_offset] = Char(' ', t)
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
def python_sidebar_help(python_input):
    """
    Create the `Layout` for the help text for the current item in the sidebar.
    """
    token = Token.Sidebar.HelpText

    def get_current_description():
        """
        Return the description of the selected option.
        """
        i = 0
        for category in python_input.options:
            for option in category.options:
                if i == python_input.selected_option_index:
                    return option.description
                i += 1
        return ''

    def get_tokens(cli):
        return [(token, get_current_description())]

    return ConditionalContainer(
        content=Window(TokenListControl(get_tokens, Char(token=token)),
                       height=LayoutDimension(min=3)),
        filter=ShowSidebar(python_input)
        & Condition(lambda cli: python_input.show_sidebar_help) & ~IsDone())
Ejemplo n.º 4
0
def show_sidebar_button_info(python_input):
    """
    Create `Layout` for the information in the right-bottom corner.
    (The right part of the status bar.)
    """
    @if_mousedown
    def toggle_sidebar(cli, mouse_event):
        " Click handler for the menu. "
        python_input.show_sidebar = not python_input.show_sidebar

    token = Token.Toolbar.Status

    version = sys.version_info
    tokens = [
        (token.Key, '[F2]', toggle_sidebar),
        (token, ' Menu', toggle_sidebar),
        (token, ' - '),
        (token.PythonVersion, '%s %i.%i.%i' % (platform.python_implementation(),
                                               version[0], version[1], version[2])),
        (token, ' '),
    ]
    width = token_list_width(tokens)

    def get_tokens(cli):
        # Python version
        return tokens

    return ConditionalContainer(
        content=Window(
            TokenListControl(get_tokens, default_char=Char(token=token)),
            height=LayoutDimension.exact(1),
            width=LayoutDimension.exact(width)),
        filter=~IsDone() & RendererHeightIsKnown() &
            Condition(lambda cli: python_input.show_status_bar and
                                  not python_input.show_exit_confirmation))
Ejemplo n.º 5
0
def status_bar(python_input, *items):
    return StatusToolbar(
        items,
        default_char=Char(token=StatusToken),
        filter=~IsDone() & RendererHeightIsKnown() &
        Condition(lambda cli: python_input.show_bliss_bar and python_input.
                  bliss_bar.items and not python_input.show_exit_confirmation))
Ejemplo n.º 6
0
    def __init__(self, editor, buffer_window, buffer_name):
        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(cli):
            main_document = cli.buffers[buffer_name].document

            return [
                (Token.Toolbar.Status.CursorPosition, '(%i,%i)' % (main_document.cursor_position_row + 1,
                                                            main_document.cursor_position_col + 1)),
                (Token.Toolbar.Status, ' - '),
                (Token.Toolbar.Status.Percentage, get_scroll_text()),
                (Token.Toolbar.Status, ' '),
            ]

        super(WindowStatusBarRuler, self).__init__(
            Window(
                TokenListControl(get_tokens, default_char=Char(' ', Token.Toolbar.Status), align_right=True),
                height=LayoutDimension.exact(1),
              ),
            filter=Condition(lambda cli: editor.show_ruler))
Ejemplo n.º 7
0
def create_popup_window(title, body):
    """
    Return the layout for a pop-up window. It consists of a title bar showing
    the `title` text, and a body layout. The window is surrounded by borders.
    """
    assert isinstance(title, six.text_type)
    assert isinstance(body, Container)

    return HSplit([
        VSplit([
            Window(width=D.exact(1), height=D.exact(1),
                   content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
            TokenListToolbar(
                get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
                align_center=True,
                default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
            Window(width=D.exact(1), height=D.exact(1),
                   content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
        ]),
        VSplit([
            Window(width=D.exact(1),
                   content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
            body,
            Window(width=D.exact(1),
                   content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
        ]),
        VSplit([
            Window(width=D.exact(1), height=D.exact(1),
                   content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
            Window(height=D.exact(1),
                   content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
            Window(width=D.exact(1), height=D.exact(1),
                   content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
        ]),
    ])
Ejemplo n.º 8
0
    def __init__(self, editor, editor_buffer):
        def get_tokens(cli):
            insert_mode = cli.vi_state.input_mode in (InputMode.INSERT, InputMode.INSERT_MULTIPLE)
            replace_mode = cli.vi_state.input_mode == InputMode.REPLACE
            sel = cli.buffers[editor_buffer.buffer_name].selection_state
            visual_line = sel is not None and sel.type == SelectionType.LINES
            visual_block = sel is not None and sel.type == SelectionType.BLOCK
            visual_char = sel is not None and sel.type == SelectionType.CHARACTERS

            def mode():
                if cli.current_buffer_name == editor_buffer.buffer_name:
                    if insert_mode:
                        if editor.paste_mode:
                            return ' -- INSERT (paste)--'
                        else:
                            return ' -- INSERT --'
                    elif replace_mode:
                        return ' -- REPLACE --'
                    elif visual_block:
                        return ' -- VISUAL BLOCK --'
                    elif visual_line:
                        return ' -- VISUAL LINE --'
                    elif visual_char:
                        return ' -- VISUAL --'
                return '                     '

            return [
                (Token.Toolbar.Status, ' '),
                (Token.Toolbar.Status, editor_buffer.location or ''),
                (Token.Toolbar.Status, ' [New File]' if editor_buffer.is_new else ''),
                (Token.Toolbar.Status, '*' if editor_buffer.has_unsaved_changes else ''),
                (Token.Toolbar.Status, ' '),
                (Token.Toolbar.Status, mode()),
            ]
        super(WindowStatusBar, self).__init__(get_tokens, default_char=Char(' ', Token.Toolbar.Status))
Ejemplo n.º 9
0
    def _reset_screen(self):
        """ Reset the Screen content. (also called when switching from/to
        alternate buffer. """
        self.pt_screen = Screen(default_char=Char(
            ' ', ''))  # TODO: maybe stop using this Screen class.

        self.pt_screen.cursor_position = CursorPosition(0, 0)
        self.pt_screen.show_cursor = True

        self.data_buffer = self.pt_screen.data_buffer
        self.pt_cursor_position = self.pt_screen.cursor_position
        self.wrapped_lines = []  # List of line indexes that were wrapped.

        self._attrs = Attrs(color=None,
                            bgcolor=None,
                            bold=False,
                            underline=False,
                            italic=False,
                            blink=False,
                            reverse=False,
                            hidden=False)
        self._style_str = ''

        self.margins = None

        self.max_y = 0  # Max 'y' position to which is written.
Ejemplo n.º 10
0
def python_sidebar_navigation(python_input):
    """
    Create the `Layout` showing the navigation information for the sidebar.
    """
    def get_tokens(cli):
        tokens = []
        T = Token.Sidebar

        # Show navigation info.
        tokens.extend([
            (T.Separator, ' ' * 43 + '\n'),
            (T, '    '),
            (T.Key, '[Arrows]'),
            (T, ' '),
            (T.Key.Description, 'Navigate'),
            (T, ' '),
            (T.Key, '[Enter]'),
            (T, ' '),
            (T.Key.Description, 'Hide menu'),
        ])

        return tokens

    return ConditionalContainer(content=Window(
        TokenListControl(get_tokens, Char(token=Token.Sidebar)),
        width=LayoutDimension.exact(43),
        height=LayoutDimension.exact(2)),
                                filter=ShowSidebar(python_input) & ~IsDone())
Ejemplo n.º 11
0
    def __init__(self, pager):
        def get_tokens(cli):
            return pager.titlebar_tokens

        super(Titlebar, self).__init__(
            get_tokens,
            default_char=Char(' ', Token.Titlebar),
            filter=Condition(lambda cli: pager.display_titlebar))
Ejemplo n.º 12
0
def _draw_number(screen,
                 x_offset,
                 y_offset,
                 number,
                 style='class:clock',
                 transparent=False):
    " Write number at position. "
    fg = Char(' ', 'class:clock')
    bg = Char(' ', '')

    for y, row in enumerate(_numbers[number]):
        screen_row = screen.data_buffer[y + y_offset]
        for x, n in enumerate(row):
            if n == '#':
                screen_row[x + x_offset] = fg
            elif not transparent:
                screen_row[x + x_offset] = bg
Ejemplo n.º 13
0
def python_sidebar(python_input):
    """
    Create the `Layout` for the sidebar with the configurable options.
    """
    def get_tokens(cli):
        tokens = []
        T = Token.Sidebar

        def append_category(category):
            tokens.extend([
                (T, '  '),
                (T.Title, '   %-36s' % category.title),
                (T, '\n'),
            ])

        def append(selected, label, status):
            token = T.Selected if selected else T

            tokens.append((T, ' >' if selected else '  '))
            tokens.append((token.Label, '%-24s' % label))
            tokens.append((token.Status, ' '))
            tokens.append((token.Status, '%s' % status))

            if selected:
                tokens.append((Token.SetCursorPosition, ''))

            tokens.append((token.Status, ' ' * (14 - len(status))))
            tokens.append((T, '<' if selected else ''))
            tokens.append((T, '\n'))

        i = 0
        for category in python_input.options:
            append_category(category)

            for option in category.options:
                append(i == python_input.selected_option_index,
                       option.title, '%s' % option.get_current_value())
                i += 1

        tokens.pop()  # Remove last newline.

        return tokens

    class Control(TokenListControl):
        def move_cursor_down(self, cli):
            python_input.selected_option_index += 1

        def move_cursor_up(self, cli):
            python_input.selected_option_index -= 1

    return ConditionalContainer(
        content=Window(
            Control(get_tokens, Char(token=Token.Sidebar),
                has_focus=ShowSidebar(python_input) & ~IsDone()),
            width=LayoutDimension.exact(43),
            height=LayoutDimension(min=3),
            scroll_offsets=ScrollOffsets(top=1, bottom=1)),
        filter=ShowSidebar(python_input) & ~IsDone())
Ejemplo n.º 14
0
def status_bar(key_bindings_manager, python_input):
    """
    Create the `Layout` for the status bar.
    """
    TB = Token.Toolbar.Status

    @if_mousedown
    def toggle_paste_mode(cli, mouse_event):
        python_input.paste_mode = not python_input.paste_mode

    @if_mousedown
    def enter_history(cli, mouse_event):
        python_input.enter_history(cli)

    def get_tokens(cli):
        python_buffer = cli.buffers[DEFAULT_BUFFER]

        result = []
        append = result.append

        append((TB, ' '))
        result.extend(get_inputmode_tokens(cli, python_input))
        append((TB, ' '))

        # Position in history.
        append((TB, '%i/%i ' % (python_buffer.working_index + 1,
                                len(python_buffer._working_lines))))

        # Shortcuts.
        if not python_input.vi_mode and cli.current_buffer_name == SEARCH_BUFFER:
            append((TB, '[Ctrl-G] Cancel search [Enter] Go to this position.'))
        elif bool(cli.current_buffer.selection_state
                  ) and not python_input.vi_mode:
            # Emacs cut/copy keys.
            append(
                (TB,
                 '[Ctrl-W] Cut [Meta-W] Copy [Ctrl-Y] Paste [Ctrl-G] Cancel'))
        else:
            result.extend([
                (TB.Key, '[F3]', enter_history),
                (TB, ' History ', enter_history),
                (TB.Key, '[F6]', toggle_paste_mode),
                (TB, ' ', toggle_paste_mode),
            ])

            if python_input.paste_mode:
                append((TB.PasteModeOn, 'Paste mode (on)', toggle_paste_mode))
            else:
                append((TB, 'Paste mode', toggle_paste_mode))

        return result

    return TokenListToolbar(
        get_tokens,
        default_char=Char(token=TB),
        filter=~IsDone() & RendererHeightIsKnown()
        & Condition(lambda cli: python_input.show_status_bar and
                    not python_input.show_exit_confirmation))
Ejemplo n.º 15
0
    def chars_are_equal(new_char, old_char):
        """
        Test whether two `Char` instances are equal if printed.
        """
        if grayed:
            new_char = Char(new_char.char, token=Token.Aborted)

        # We ignore z-index, that does not matter if things get painted.
        return new_char.char == old_char.char and new_char.token == old_char.token
Ejemplo n.º 16
0
    def __init__(self):
        def get_tokens(cli):
            return [
                (Token.Header,
                 "    Experimental Pure Python Vim editor. Type ':q' to quit."
                 ),
            ]

        super(Header, self).__init__(get_tokens,
                                     default_char=Char(' ', Token.Header))
Ejemplo n.º 17
0
    def write_to_screen(self, cli, screen, mouse_handlers, write_position):
        """
        Write window to screen. This renders the user control, the margins and
        copies everything over to the absolute position at the given screen.
        """
        # Set size of the screen.
        self.process.set_size(write_position.width, write_position.height)

        vertical_scroll = self.process.screen.line_offset

        # Render UserControl.
        temp_screen = self.process.screen.pt_screen

        # Write body to screen.
        self._copy_body(cli, temp_screen, screen, write_position,
                        vertical_scroll, write_position.width)

        # Set mouse handlers.
        def mouse_handler(cli, mouse_event):
            """ Wrapper around the mouse_handler of the `UIControl` that turns
            absolute coordinates into relative coordinates. """
            position = mouse_event.position

            # Call the mouse handler of the UIControl first.
            self._mouse_handler(
                cli,
                MouseEvent(position=Point(x=position.x - write_position.xpos,
                                          y=position.y - write_position.ypos +
                                          vertical_scroll),
                           event_type=mouse_event.event_type))

        mouse_handlers.set_mouse_handler_for_range(
            x_min=write_position.xpos,
            x_max=write_position.xpos + write_position.width,
            y_min=write_position.ypos,
            y_max=write_position.ypos + write_position.height,
            handler=mouse_handler)

        # If reverse video is enabled for the whole screen.
        if self.process.screen.has_reverse_video:
            data_buffer = screen.data_buffer

            for y in range(write_position.ypos,
                           write_position.ypos + write_position.height):
                row = data_buffer[y]

                for x in range(write_position.xpos,
                               write_position.xpos + write_position.width):
                    char = row[x]
                    token = list(char.token or DEFAULT_TOKEN)

                    # The token looks like ('C', *attrs). Replace the value of the reverse flag.
                    if token and token[0] == 'C':
                        token[-1] = not token[-1]  # Invert reverse value.
                        row[x] = Char(char.char, tuple(token))
Ejemplo n.º 18
0
    def draw(self, char):
        pt_screen = self.pt_screen

        # Translating a given character.
        if self.charset:
            char = char.translate(self.g1_charset)
        else:
            char = char.translate(self.g0_charset)

        # Calculate character width. (We use the prompt_toolkit function which
        # has built-in caching.)
        char_width = get_cwidth(char)

        # If this was the last column in a line and auto wrap mode is
        # enabled, move the cursor to the beginning of the next line,
        # otherwise replace characters already displayed with newly
        # entered.
        if pt_screen.cursor_position.x >= self.columns:
            if mo.DECAWM in self.mode:
                self.carriage_return()
                self.linefeed()
            else:
                pt_screen.cursor_position.x -= char_width

        # If Insert mode is set, new characters move old characters to
        # the right, otherwise terminal is in Replace mode and new
        # characters replace old characters at cursor position.
        if mo.IRM in self.mode:
            self.insert_characters(char_width)

        token = ('C', ) + self._attrs
        row = pt_screen.data_buffer[pt_screen.cursor_position.y]
        row[pt_screen.cursor_position.x] = Char(char, token)

        if char_width > 1:
            row[pt_screen.cursor_position.x + 1] = Char(' ', token)

        # .. note:: We can't use :meth:`cursor_forward()`, because that
        #           way, we'll never know when to linefeed.
        pt_screen.cursor_position.x += char_width

        self.max_y = max(self.max_y, pt_screen.cursor_position.y)
Ejemplo n.º 19
0
    def create_screen(self, cli, width, height):
        screen = Screen(initial_width=width)

        for y in range(self.HEIGHT):
            for x in range(self.WIDTH):
                screen.data_buffer[y][x] = Char(' ', Token)

        # Display time.
        now = datetime.datetime.now()
        _draw_number(screen, 0, now.hour // 10)
        _draw_number(screen, 6, now.hour % 10)
        _draw_number(screen, 16, now.minute // 10)
        _draw_number(screen, 23, now.minute % 10)

        # Add a colon
        screen.data_buffer[1][13] = Char(' ', Token.Clock)
        screen.data_buffer[3][13] = Char(' ', Token.Clock)

        screen.width = self.WIDTH
        screen.height = self.HEIGHT
        return screen
Ejemplo n.º 20
0
def create_default_layout(message='', lexer=None, is_password=False,
                          reserve_space_for_menu=False, get_bottom_toolbar_tokens=None):
    """
    Generate default layout.
    """
    assert get_bottom_toolbar_tokens is None or callable(get_bottom_toolbar_tokens)

    # Create processors list.
    input_processors = [HighlightSearchProcessor(), HighlightSelectionProcessor()]
    if is_password:
        input_processors.extend([PasswordProcessor(), DefaultPrompt(message)])
    else:
        input_processors.append(DefaultPrompt(message))

    # Create bottom toolbar.
    if get_bottom_toolbar_tokens:
        toolbars = [Window(TokenListControl(get_bottom_toolbar_tokens,
                                            default_char=Char(' ', Token.Toolbar)),
                           height=LayoutDimension.exact(1),
                           filter=~IsDone())]
    else:
        toolbars = []

    def get_height(cli):
        # 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 reserve_space_for_menu and not cli.is_done:
            return LayoutDimension(min=8)
        else:
            return LayoutDimension()

    # Create and return Layout instance.
    return HSplit([
        FloatContainer(
            Window(
                BufferControl(
                    input_processors=input_processors,
                    lexer=lexer,
                    # Enable preview_search, we want to have immediate feedback
                    # in reverse-i-search mode.
                    preview_search=Always()),
                get_height=get_height,
            ),
            [
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(max_height=16,
                                              extra_filter=HasFocus(DEFAULT_BUFFER)))
            ]
        ),
        ValidationToolbar(),
        SystemToolbar(),
    ] + toolbars)
Ejemplo n.º 21
0
 def __init__(self, tosh):
     self._tosh = tosh
     self._tabs = [ToshTab(tosh)]
     self._active_tab = 0
     layout = [
         Window(TokenListControl(
             self._get_tabs_tokens,
             default_char=Char(' ', Token.Tabs),
         ),
                height=D(max=1)), self._tabs[0].layout
     ]
     super().__init__(layout)
Ejemplo n.º 22
0
    def erase_in_display(self, type_of=0, private=False):
        """Erases display in a specific way.

        :param int type_of: defines the way the line should be erased in:

            * ``0`` -- Erases from cursor to end of screen, including
              cursor position.
            * ``1`` -- Erases from beginning of screen to cursor,
              including cursor position.
            * ``2`` -- Erases complete display. All lines are erased
              and changed to single-width. Cursor does not move.
            * ``3`` -- Erase saved lines. (Xterm) Clears the history.
        :param bool private: when ``True`` character attributes aren left
                             unchanged **not implemented**.
        """
        line_offset = self.line_offset
        pt_cursor_position = self.pt_cursor_position
        try:
            max_line = max(self.pt_screen.data_buffer)
        except ValueError:
            # max() called on empty sequence. Screen is empty. Nothing to erase.
            return

        if type_of == 3:
            # Clear data buffer.
            for y in list(self.data_buffer):
                self.data_buffer.pop(y, None)

            # Reset line_offset.
            pt_cursor_position.y = 0
            self.max_y = 0
        else:
            try:
                interval = (
                    # a) erase from cursor to the end of the display, including
                    # the cursor,
                    range(pt_cursor_position.y + 1, max_line + 1),
                    # b) erase from the beginning of the display to the cursor,
                    # including it,
                    range(line_offset, pt_cursor_position.y),
                    # c) erase the whole display.
                    range(line_offset, max_line + 1))[type_of]
            except IndexError:
                return

            data_buffer = self.data_buffer
            for line in interval:
                data_buffer[line] = defaultdict(lambda: Char(' '))

            # In case of 0 or 1 we have to erase the line with the cursor.
            if type_of in [0, 1]:
                self.erase_in_line(type_of)
Ejemplo n.º 23
0
def create_default_layout(message='', lexer=None, is_password=False,
                          reserve_space_for_menu=False, get_bottom_toolbar_tokens=None):
    """
    Generate default layout.
    """
    assert get_bottom_toolbar_tokens is None or callable(get_bottom_toolbar_tokens)

    # Create processors list.
    if is_password:
        input_processors = [PasswordProcessor(), DefaultPrompt(message)]
    else:
        input_processors = [DefaultPrompt(message)]

    # Create bottom toolbar.
    if get_bottom_toolbar_tokens:
        toolbars = [Window(TokenListControl(get_bottom_toolbar_tokens,
                                            default_char=Char(' ', Token.Toolbar)),
                           height=LayoutDimension.exact(1),
                           filter=~IsDone())]
    else:
        toolbars = []

    def get_height(cli):
        # 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 reserve_space_for_menu and not cli.is_done:
            return LayoutDimension(min=8)
        else:
            return LayoutDimension()

    # Create and return Layout instance.
    return HSplit([
        FloatContainer(
            Window(
                BufferControl(
                    input_processors=input_processors,
                    lexer=lexer),
                get_height=get_height,
            ),
            [
                Float(xcursor=True,
                      ycursor=True,
                      content=CompletionsMenu(max_height=16,
                                              extra_filter=HasFocus('default')))
            ]
        ),
        ValidationToolbar(),
        SystemToolbar(),
    ] + toolbars)
Ejemplo n.º 24
0
    def __init__(self,
                 key_bindings_manager,
                 settings,
                 token=Token.Toolbar.Status):
        def get_tokens(cli):
            _, python_buffer = current_python_buffer(cli, settings)
            if not python_buffer:
                return []

            TB = token
            result = []
            append = result.append

            append((TB, ' '))
            result.extend(get_inputmode_tokens(TB, key_bindings_manager, cli))
            append((TB, '  '))

            # Position in history.
            append((TB, '%i/%i ' % (python_buffer.working_index + 1,
                                    len(python_buffer._working_lines))))

            # Shortcuts.
            if not key_bindings_manager.enable_vi_mode and cli.focus_stack.current == 'search':
                append((TB,
                        '[Ctrl-G] Cancel search [Enter] Go to this position.'))
            elif bool(cli.current_buffer.selection_state
                      ) and not key_bindings_manager.enable_vi_mode:
                # Emacs cut/copy keys.
                append((
                    TB,
                    '[Ctrl-W] Cut [Meta-W] Copy [Ctrl-Y] Paste [Ctrl-G] Cancel'
                ))
            else:
                append((TB, '  '))

                if settings.paste_mode:
                    append((TB.On, '[F6] Paste mode (on)   '))
                else:
                    append((TB.Off, '[F6] Paste mode (off)  '))

                if python_buffer.is_multiline:
                    append((TB, ' [Meta+Enter] Execute'))

            return result

        super(PythonToolbar,
              self).__init__(get_tokens,
                             default_char=Char(token=token),
                             filter=~IsDone() & RendererHeightIsKnown())
Ejemplo n.º 25
0
    def __init__(self, settings, key_bindings_manager):
        def get_tokens(cli):
            tokens = []
            TB = Token.Sidebar

            if key_bindings_manager.enable_vi_mode:
                mode = 'vi'
            else:
                mode = 'emacs'

            if settings.show_completions_toolbar:
                completion_style = 'toolbar'
            elif settings.show_completions_menu:
                completion_style = 'pop-up'
            else:
                completion_style = 'off'

            def append(shortcut, label, status):
                tokens.append((TB.Shortcut, ' [%s] ' % shortcut))
                tokens.append((TB.Label, '%-18s' % label))
                if status:
                    tokens.append((TB.Status, '%9s\n' % status))
                else:
                    tokens.append((TB.Label, '\n'))

            append('Ctrl-T', 'New tab', '')
            append('Ctrl-D', 'Close tab', '')
            append('Ctrl-Left/Right', 'Focus tab', '')
            append('F3', 'Completion menu', '(%s)' % completion_style)
            append('F4', 'Input mode', '(%s)' % mode)
            append('F5', 'Show all tabs',
                   '(on)' if settings.show_all_buffers else '(off)')
            #            append('F5', 'Merge from history', '')
            append('F6', 'Paste mode',
                   '(on)' if settings.paste_mode else '(off)')
            append('F7', 'Multiline',
                   '(always)' if settings.currently_multiline else '(auto)')
            append('F8', 'Show signature',
                   '(on)' if settings.show_signature else '(off)')
            append('F9', 'Show docstring',
                   '(on)' if settings.show_docstring else '(off)')
            append('F10', 'Show line numbers',
                   '(on)' if settings.show_line_numbers else '(off)')

            return tokens

        super(PythonSidebarControl, self).__init__(get_tokens,
                                                   Char(token=Token.Sidebar))
Ejemplo n.º 26
0
    def __init__(self, pdb_ref):
        token = Token.Toolbar.Title

        def get_tokens(cli):
            pdb = pdb_ref()

            return [
                (token, '\u2500\u2500'),
                (token.Text, ' '),
                (token.Text, pdb.curframe.f_code.co_filename or 'None'),
                (token.Text, ' : %s ' % pdb.curframe.f_lineno),
            ]

        super(SourceTitlebar, self).__init__(get_tokens,
                                             default_char=Char(token=token,
                                                               char='\u2500'))
Ejemplo n.º 27
0
    def __init__(self, pymux):
        token = Token.ConfirmationToolbar

        def get_tokens(cli):
            client_state = pymux.get_client_state(cli)
            return [
                (token.Question, ' '),
                (token.Question, format_pymux_string(
                    pymux, cli, client_state.confirm_text or '')),
                (token.Question, ' '),
                (token.YesNo, '  y/n'),
                (Token.SetCursorPosition, ''),
                (token.YesNo, '  '),
            ]

        super(ConfirmationToolbar, self).__init__(get_tokens, default_char=Char(' ', token))
Ejemplo n.º 28
0
    def __init__(self, pymux, arrangement_pane):
        assert isinstance(arrangement_pane, arrangement.Pane)

        def focussed(cli):
            return pymux.arrangement.get_active_pane(cli) == arrangement_pane

        def get_before_input(cli):
            if not arrangement_pane.is_searching:
                text = ''
            elif arrangement_pane.search_state.direction == IncrementalSearchDirection.BACKWARD:
                text = 'Search up: '
            else:
                text = 'Search down: '

            if focussed(cli):
                return [(Token.Search.Focussed, text)]
            else:
                return [(Token.Search, text)]

        def get_after_input(cli):
            if focussed(cli):
                return [(Token.Search.Focussed, ' ')]
            else:
                return []

        class SearchLexer(Lexer):
            " Color for the search string. "

            def lex_document(self, cli, document):
                def get_line(lineno):
                    text = document.lines[lineno]
                    if focussed(cli):
                        return [(Token.Search.Focussed.Text, text)]
                    else:
                        return [(Token.Search.Text, text)]

                return get_line

        super(SearchWindow, self).__init__(content=BufferControl(
            buffer_name='search-%i' % arrangement_pane.pane_id,
            input_processors=[
                BeforeInput(get_before_input),
                AfterInput(get_after_input)
            ],
            lexer=SearchLexer(),
            default_char=Char(token=Token)),
                                           dont_extend_height=True)
Ejemplo n.º 29
0
    def _reset_screen(self):
        """ Reset the Screen content. (also called when switching from/to
        alternate buffer. """
        self.pt_screen = Screen(default_char=Char(' ', DEFAULT_TOKEN))

        self.pt_screen.cursor_position = CursorPosition(0, 0)
        self.pt_screen.show_cursor = True

        self.data_buffer = self.pt_screen.data_buffer
        self.pt_cursor_position = self.pt_screen.cursor_position

        self._attrs = Attrs(color=None, bgcolor=None, bold=False,
                            underline=False, italic=False, blink=False, reverse=False)

        self.margins = None

        self.max_y = 0  # Max 'y' position to which is written.
Ejemplo n.º 30
0
    def __init__(self, opt_ns, srv_c, inst_xml):
        manager = KeyBindingManager()  # Start with the `KeyBindingManager`.

        self.srv_text = ServiceOutput(opt_ns, srv_c, inst_xml)
        layout = HSplit(
            [
                # One window that holds the BufferControl with the default buffer on the
                # left.
                Window(
                    height=D.exact(1),
                    content=TokenListControl(
                        self.get_title_line,
                        default_char=Char(" ", token=Token.String.ICSW.Header)
                    )
                ),
                Window(
                    height=D.exact(1),
                    content=FillControl('-', token=Token.Line)
                ),
                # Display the text 'Hello world' on the right.
                Window(
                    content=TokenListControl(
                        self.get_icsw_output,
                    )
                ),
            ]
        )

        self._updating = False

        @manager.registry.add_binding(Keys.ControlC, eager=True)
        @manager.registry.add_binding("q", eager=True)
        def _handler_data(event):
            event.cli.set_return_value(0)

        our_style = style_from_dict(logging_tools.get_icsw_prompt_styles())
        application = Application(
            layout=layout,
            use_alternate_screen=True,
            style=our_style,
            on_input_timeout=self.input_timeout,
            key_bindings_registry=manager.registry,
        )
        event_loop = create_eventloop()
        self.application = application
        self.event_loop = event_loop