Ejemplo n.º 1
0
    def get_buffer_window(self):
        " Return the Container object according to which Buffer/Source is visible. "
        source = self.pager.source

        if source not in self._bodies:
            input_processors = [
                ConditionalProcessor(
                    processor=_EscapeProcessor(self.pager),
                    filter=Condition(
                        lambda cli: not bool(self.pager.source.lexer)),
                ),
                TabsProcessor(),
                HighlightSelectionProcessor(),
                ConditionalProcessor(
                    processor=HighlightSearchProcessor(preview_search=True),
                    filter=Condition(lambda cli: self.pager.highlight_search),
                ),
                HighlightMatchingBracketProcessor(),
            ]

            buffer_window = Window(
                always_hide_cursor=True,
                content=BufferControl(
                    buffer_name=self.pager.source_info[source].buffer_name,
                    lexer=source.lexer,
                    input_processors=input_processors))

            self._bodies[source] = buffer_window

        return self._bodies[source]
Ejemplo n.º 2
0
        def create_python_input_window():
            def menu_position():
                """
                When there is no autocompletion menu to be shown, and we have a
                signature, set the pop-up position at `bracket_start`.
                """
                b = python_input.default_buffer

                if b.complete_state is None and python_input.signatures:
                    row, col = python_input.signatures[0].bracket_start
                    index = b.document.translate_row_col_to_index(row - 1, col)
                    return index

            return Window(
                BufferControl(
                    buffer=python_input.default_buffer,
                    search_buffer_control=search_toolbar.control,
                    lexer=lexer,
                    include_default_input_processors=False,
                    input_processors=[
                        ConditionalProcessor(
                            processor=HighlightIncrementalSearchProcessor(),
                            filter=has_focus(SEARCH_BUFFER)
                            | has_focus(search_toolbar.control),
                        ),
                        HighlightSelectionProcessor(),
                        DisplayMultipleCursors(),
                        # Show matching parentheses, but only while editing.
                        ConditionalProcessor(
                            processor=HighlightMatchingBracketProcessor(chars="[](){}"),
                            filter=has_focus(DEFAULT_BUFFER)
                            & ~is_done
                            & Condition(
                                lambda: python_input.highlight_matching_parenthesis
                            ),
                        ),
                        ConditionalProcessor(
                            processor=AppendAutoSuggestion(), filter=~is_done
                        ),
                    ]
                    + extra_buffer_processors,
                    menu_position=menu_position,
                    # Make sure that we always see the result of an reverse-i-search:
                    preview_search=True,
                ),
                left_margins=[PythonPromptMargin(python_input)],
                # Scroll offsets. The 1 at the bottom is important to make sure
                # the cursor is never below the "Press [Meta+Enter]" message
                # which is a float.
                scroll_offsets=ScrollOffsets(bottom=1, left=4, right=4),
                # As long as we're editing, prefer a minimal height of 6.
                height=(
                    lambda: (
                        None
                        if get_app().is_done or python_input.show_exit_confirmation
                        else input_buffer_height
                    )
                ),
                wrap_lines=Condition(lambda: python_input.wrap_lines),
            )
Ejemplo n.º 3
0
def create_buffer_window(source_info):
    """
    Window for the main content.
    """
    pager = source_info.pager

    input_processors = [
        ConditionalProcessor(
            processor=_EscapeProcessor(source_info),
            filter=Condition(lambda: not bool(source_info.source.lexer)),
        ),
        TabsProcessor(),
        ConditionalProcessor(
            processor=HighlightSearchProcessor(),
            filter=Condition(lambda: pager.highlight_search),
        ),
        ConditionalProcessor(
            processor=HighlightIncrementalSearchProcessor(),
            filter=Condition(lambda: pager.highlight_search),
        ),
        HighlightSelectionProcessor(),
        HighlightMatchingBracketProcessor(),
    ]

    return Window(
        always_hide_cursor=True,
        content=BufferControl(
            buffer=source_info.buffer,
            lexer=source_info.source.lexer,
            input_processors=input_processors,
            include_default_input_processors=False,
            preview_search=True,
            search_buffer_control=pager.layout.search_toolbar.control))
Ejemplo n.º 4
0
    def create_python_input_window():
        def menu_position(cli):
            """
            When there is no autocompletion menu to be shown, and we have a signature,
            set the pop-up position at `bracket_start`.
            """
            b = cli.buffers[DEFAULT_BUFFER]

            if b.complete_state is None and python_input.signatures:
                row, col = python_input.signatures[0].bracket_start
                index = b.document.translate_row_col_to_index(row - 1, col)
                return index

        return Window(
            BufferControl(
                buffer_name=DEFAULT_BUFFER,
                lexer=lexer,
                input_processors=[
                    ConditionalProcessor(
                        processor=HighlightSearchProcessor(
                            preview_search=True),
                        filter=HasFocus(SEARCH_BUFFER),
                    ),
                    HighlightSelectionProcessor(),
                    # Show matching parentheses, but only while editing.
                    ConditionalProcessor(
                        processor=HighlightMatchingBracketProcessor(
                            chars='[](){}'),
                        filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()
                        & Condition(lambda cli: python_input.
                                    highlight_matching_parenthesis)),
                    ConditionalProcessor(processor=AppendAutoSuggestion(),
                                         filter=~IsDone())
                ] + extra_buffer_processors,
                menu_position=menu_position,

                # Make sure that we always see the result of an reverse-i-search:
                preview_search=True,
            ),
            left_margins=[PythonPromptMargin(python_input)],
            # Scroll offsets. The 1 at the bottom is important to make sure the
            # cursor is never below the "Press [Meta+Enter]" message which is a float.
            scroll_offsets=ScrollOffsets(bottom=1, left=4, right=4),
            # As long as we're editing, prefer a minimal height of 6.
            get_height=(lambda cli:
                        (None if cli.is_done or python_input.
                         show_exit_confirmation else input_buffer_height)),
            wrap_lines=Condition(lambda cli: python_input.wrap_lines),
        )
Ejemplo n.º 5
0
    def _build_cli(self, history):
        def get_message():
            prompt = self.context.get_prompt(self.default_prompt)
            return [('class:prompt', prompt)]

        prompt_app = PromptSession(
            message=get_message,
            complete_style=CompleteStyle.COLUMN,
            completer=ThreadedCompleter(
                DynamicCompleter(lambda: self.completer)),
            complete_while_typing=True,
            editing_mode=EditingMode.VI,
            enable_system_prompt=True,
            enable_suspend=True,
            history=history,
            input_processors=[
                # Highlight matching brackets while editing.
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}', ),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
                # Render \t as 4 spaces instead of "^I"
                TabsProcessor(char1=' ', char2=' ')
            ],
            key_bindings=get_key_bindings(),
            search_ignore_case=True,
        )

        return prompt_app
Ejemplo n.º 6
0
def question(get_prompt_tokens,
             choices,
             default=None,
             page_size=None,
             history=None,
             mouse_support=True):
    buf = ExpandBuffer(
        choices,
        default,
    )
    hint = []
    for choice in buf.choices:
        if choice.key:
            if choice.key not in hint:
                hint.append(choice.key)
    hint = '(%s)' % ''.join(hint)

    layout = create_default_layout(
        get_prompt_tokens=get_prompt_tokens,
        hint=hint,
        extra_input_processors=[
            ConditionalProcessor(HideInputProcessor(), ~IsDone() & Expanded()),
        ],
        reactive_window_factory=expand_window_factory(InfiniteWindow,
                                                      ExpandControl(),
                                                      page_size))

    # don't add list responses to history
    history = None

    return create_prompt_application(layout,
                                     buf=buf,
                                     history=history,
                                     mouse_support=mouse_support)
Ejemplo n.º 7
0
    def _layout_options(self):
        """
        Return the current layout option for the current Terminal InteractiveShell
        """
        return {
            'lexer':
            IPythonPTLexer(),
            'reserve_space_for_menu':
            self.space_for_menu,
            'get_prompt_tokens':
            self.prompts.in_prompt_tokens,
            'get_continuation_tokens':
            self.prompts.continuation_prompt_tokens,
            'multiline':
            True,
            'display_completions_in_columns':
            (self.display_completions == 'multicolumn'),

            # Highlight matching brackets, but only when this setting is
            # enabled, and only when the DEFAULT_BUFFER has the focus.
            'extra_input_processors': [
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()
                    & Condition(lambda cli: self.highlight_matching_brackets))
            ],
        }
Ejemplo n.º 8
0
def question(get_prompt_tokens,
             default=None,
             validate=None,
             mask=None,
             history=None):
    hint = None
    if default is not None:
        default = '%s' % default
        if mask is None:
            hint = '[hidden]'
        else:
            hint = '(%s)' % (mask * len(default))

    def transformer(text):
        if mask is None:
            return (Token.Hidden, '[hidden]')
        return '*' * len(text)

    layout = create_default_layout(get_prompt_tokens=get_prompt_tokens,
                                   hint=hint,
                                   transformer=transformer,
                                   extra_input_processors=[
                                       ConditionalProcessor(
                                           PasswordProcessor(mask), ~IsDone()),
                                   ],
                                   hide_cursor=mask is None)

    # don't add password responses to history
    history = None

    return create_prompt_application(layout,
                                     default=default,
                                     validator=validate,
                                     history=history)
Ejemplo n.º 9
0
    def _build_cli(self, history):
        def set_vi_mode(value):
            self.vi_mode = value

        key_binding_manager = mssqlcli_bindings(
            get_vi_mode_enabled=lambda: self.vi_mode,
            set_vi_mode_enabled=set_vi_mode)

        def prompt_tokens(_):
            prompt = self.get_prompt()
            return [(Token.Prompt, prompt)]

        def get_continuation_tokens(cli, width):
            continuation = self.multiline_continuation_char * (width - 1) + ' '
            return [(Token.Continuation, continuation)]

        get_toolbar_tokens = create_toolbar_tokens_func(
            lambda: self.vi_mode, None, None, None)

        layout = create_prompt_layout(
            lexer=PygmentsLexer(PostgresLexer),
            reserve_space_for_menu=self.min_num_menu_lines,
            get_prompt_tokens=prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_toolbar_tokens,
            display_completions_in_columns=self.wider_completion_menu,
            multiline=True,
            extra_input_processors=[
                # Highlight matching brackets while editing.
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
            ])

        with self._completer_lock:
            buf = MssqlBuffer(auto_suggest=AutoSuggestFromHistory(),
                              always_multiline=self.multi_line,
                              multiline_mode=self.multiline_mode,
                              completer=self.completer,
                              history=history,
                              complete_while_typing=Always(),
                              accept_action=AcceptAction.RETURN_DOCUMENT)

            editing_mode = EditingMode.VI if self.vi_mode else EditingMode.EMACS

            application = Application(
                style=style_factory(self.syntax_style, self.cli_style),
                layout=layout,
                buffer=buf,
                key_bindings_registry=key_binding_manager.registry,
                on_exit=AbortAction.RAISE_EXCEPTION,
                on_abort=AbortAction.RETRY,
                ignore_case=True,
                editing_mode=editing_mode)

            cli = CommandLineInterface(application=application,
                                       eventloop=self.eventloop)

            return cli
Ejemplo n.º 10
0
    def create_python_input_window():
        def menu_position(cli):
            """
            When there is no autocompletion menu to be shown, and we have a signature,
            set the pop-up position at `bracket_start`.
            """
            b = cli.buffers['default']

            if b.complete_state is None and settings.signatures:
                row, col = settings.signatures[0].bracket_start
                index = b.document.translate_row_col_to_index(row - 1, col)
                return index

        return Window(
            BufferControl(
                buffer_name=DEFAULT_BUFFER,
                lexer=lexer,
                show_line_numbers=ShowLineNumbersFilter(settings, 'default'),
                input_processors=[
                                  # Show matching parentheses, but only while editing.
                                  ConditionalProcessor(
                                      processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                                      filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
                                  HighlightSearchProcessor(preview_search=Always()),
                                  HighlightSelectionProcessor()] + extra_buffer_processors,
                menu_position=menu_position,

                # Make sure that we always see the result of an reverse-i-search:
                preview_search=Always(),
            ),
            # As long as we're editing, prefer a minimal height of 6.
            get_height=(lambda cli: (None if cli.is_done else D(min=6))),
        )
Ejemplo n.º 11
0
    def _extra_prompt_options(self):
        """
        Return the current layout option for the current Terminal InteractiveShell
        """
        def get_message():
            return PygmentsTokens(self.prompts.in_prompt_tokens())

        return {
                'complete_in_thread': False,
                'lexer':IPythonPTLexer(),
                'reserve_space_for_menu':self.space_for_menu,
                'message': get_message,
                'prompt_continuation': (
                    lambda width, lineno, is_soft_wrap:
                        PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
                'multiline': True,
                'complete_style': self.pt_complete_style,

                # Highlight matching brackets, but only when this setting is
                # enabled, and only when the DEFAULT_BUFFER has the focus.
                'input_processors': [ConditionalProcessor(
                        processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                        filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
                            Condition(lambda: self.highlight_matching_brackets))],
                }
Ejemplo n.º 12
0
    def build_cli(self):
        # TODO: Optimize index suggestion to serve indices options only at the needed position, such as 'from'
        indices_list = self.es_executor.indices_list
        sql_completer = WordCompleter(self.keywords_list +
                                      self.functions_list + indices_list,
                                      ignore_case=True)

        # https://stackoverflow.com/a/13726418 denote multiple unused arguments of callback in Python
        def get_continuation(width, *_):
            continuation = self.multiline_continuation_char * (width - 1) + " "
            return [("class:continuation", continuation)]

        prompt_app = PromptSession(
            lexer=PygmentsLexer(SqlLexer),
            completer=sql_completer,
            complete_while_typing=True,
            # TODO: add history, refer to pgcli approach
            # history=history,
            style=style_factory(self.syntax_style, self.cli_style),
            prompt_continuation=get_continuation,
            multiline=es_is_multiline(self),
            auto_suggest=AutoSuggestFromHistory(),
            input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars="[](){}"),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(),
                )
            ],
            tempfile_suffix=".sql",
        )

        return prompt_app
Ejemplo n.º 13
0
    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)
Ejemplo n.º 14
0
    def _build_cli(self):
        eventloop = create_eventloop()

        if self._options.persistent_history:
            history = FileHistory(
                os.path.join(
                    os.path.expanduser("~"), ".{}_history".format(self._ctx.binary_name)
                )
            )
        else:
            history = InMemoryHistory()

        layout = create_prompt_layout(
            lexer=PygmentsLexer(NubiaLexer),
            reserve_space_for_menu=5,
            get_prompt_tokens=self.get_prompt_tokens,
            get_rprompt_tokens=self._status_bar.get_rprompt_tokens,
            get_bottom_toolbar_tokens=self._status_bar.get_tokens,
            display_completions_in_columns=False,
            multiline=True,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(chars="[](){}"),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(),
                )
            ],
        )

        buf = Buffer(
            completer=self._completer,
            history=history,
            auto_suggest=self._suggestor,
            complete_while_typing=Always(),
            accept_action=AcceptAction.RETURN_DOCUMENT,
        )

        # If EDITOR does not exist, take EMACS
        # if it does, try fit the EMACS/VI pattern using upper
        editor = getattr(
            EditingMode,
            os.environ.get("EDITOR", EditingMode.EMACS).upper(),
            EditingMode.EMACS,
        )

        application = Application(
            style=shell_style,
            buffer=buf,
            editing_mode=editor,
            key_bindings_registry=self._registry,
            layout=layout,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True,
        )

        cli = CommandLineInterface(application=application, eventloop=eventloop)
        return cli
Ejemplo n.º 15
0
    def _create_buffer_control(self, editor_buffer):
        """
        Create a new BufferControl for a given location.
        """
        buffer_name = editor_buffer.buffer_name

        @Condition
        def preview_search(cli):
            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 cli: self.editor.display_unprintable_characters)),

            # Replace tabs by spaces.
            TabsProcessor(
                tabstop=Integer.from_callable(lambda: self.editor.tabstop),
                get_char1=(
                    lambda cli: '|'
                    if self.editor.display_unprintable_characters else ' '),
                get_char2=(
                    lambda cli: '\u2508'
                    if self.editor.display_unprintable_characters else ' '),
            ),

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

        return BufferControl(lexer=DocumentLexer(editor_buffer),
                             input_processors=input_processors,
                             buffer_name=buffer_name,
                             preview_search=preview_search,
                             focus_on_click=True)
Ejemplo n.º 16
0
    def _create_buffer_control(self, editor_buffer):
        """
        Create a new BufferControl for a given filename.
        """
        filename = editor_buffer.filename
        buffer_name = editor_buffer.buffer_name

        @Condition
        def preview_search(cli):
            return self.editor.incsearch

        input_processors = [
            # Highlighting of the search.
            ConditionalProcessor(
                HighlightSearchProcessor(preview_search=preview_search),
                Condition(lambda cli: self.editor.highlight_search)),

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

            # Highlight selection.
            HighlightSelectionProcessor(),

            # Highlight matching parentheses.
            HighlightMatchingBracketProcessor(),

            # Reporting of errors, for Pyflakes.
            ReportingProcessor(editor_buffer),

            # Replace tabs by spaces.
            TabsProcessor(self.editor)
        ]

        return BufferControl(show_line_numbers=Condition(
            lambda cli: self.editor.show_line_numbers),
                             lexer=DocumentLexer(editor_buffer),
                             input_processors=input_processors,
                             buffer_name=buffer_name,
                             preview_search=preview_search)
Ejemplo n.º 17
0
    def _build_cli(self, history):
        def get_message():
            prompt = self.get_prompt(self.prompt_format)
            return [(u'class:prompt', prompt)]

        def get_continuation(width):
            continuation = self.multiline_continuation_char * (width - 1) + ' '
            return [(u'class:continuation', continuation)]

        get_toolbar_tokens = create_toolbar_tokens_func(self)

        if self.wider_completion_menu:
            complete_style = CompleteStyle.MULTI_COLUMN
        else:
            complete_style = CompleteStyle.COLUMN

        with self._completer_lock:
            self.prompt_session = PromptSession(
                message=get_message,
                style=style_factory(self.syntax_style, self.cli_style),

                # Layout options.
                lexer=PygmentsLexer(PostgresLexer),
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=complete_style,
                input_processors=[
                    ConditionalProcessor(
                        processor=HighlightMatchingBracketProcessor(
                            chars='[](){}'),
                        filter=HasFocus(DEFAULT_BUFFER)
                        & ~IsDone()),  #FIXME: what is this?
                    # Render \t as 4 spaces instead of "^I"
                    TabsProcessor(char1=u' ', char2=u' ')
                ],
                reserve_space_for_menu=self.min_num_menu_lines,

                # Buffer options.
                multiline=mssql_is_multiline(self),
                completer=ThreadedCompleter(
                    DynamicCompleter(lambda: self.completer)),
                history=history,
                auto_suggest=AutoSuggestFromHistory(),
                complete_while_typing=True,

                # Key bindings.
                enable_system_prompt=True,
                enable_open_in_editor=True,

                # Other options.
                key_bindings=mssqlcli_bindings(self),
                editing_mode=EditingMode.VI
                if self.vi_mode else EditingMode.EMACS,
                search_ignore_case=True)

            return self.prompt_session
Ejemplo n.º 18
0
Archivo: saws.py Proyecto: MaWich/saws
    def _create_cli(self):
        """Creates the prompt_toolkit's CommandLineInterface.

        Args:
            * None.

        Returns:
            None.
        """
        history = FileHistory(os.path.expanduser('~/.saws-history'))
        toolbar = Toolbar(self.get_color,
                          self.get_fuzzy_match,
                          self.get_shortcut_match)
        layout = create_default_layout(
            message='saws> ',
            reserve_space_for_menu=8,
            lexer=CommandLexer,
            get_bottom_toolbar_tokens=toolbar.handler,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
            ]
        )
        cli_buffer = Buffer(
            history=history,
            auto_suggest=AutoSuggestFromHistory(),
            enable_history_search=True,
            completer=self.completer,
            complete_while_typing=Always(),
            accept_action=AcceptAction.RETURN_DOCUMENT)
        self.key_manager = KeyManager(
            self.set_color,
            self.get_color,
            self.set_fuzzy_match,
            self.get_fuzzy_match,
            self.set_shortcut_match,
            self.get_shortcut_match,
            self.refresh_resources_and_options,
            self.handle_docs)
        style_factory = StyleFactory(self.theme)
        application = Application(
            mouse_support=False,
            style=style_factory.style,
            layout=layout,
            buffer=cli_buffer,
            key_bindings_registry=self.key_manager.manager.registry,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True)
        eventloop = create_eventloop()
        self.aws_cli = CommandLineInterface(
            application=application,
            eventloop=eventloop)
Ejemplo n.º 19
0
    def __init__(self, shell_ctx):
        self.shell_ctx = shell_ctx

        @Condition
        def show_default(_):
            return self.shell_ctx.is_showing_default

        @Condition
        def show_symbol(_):
            return self.shell_ctx.is_symbols

        @Condition
        def show_progress(_):
            progress = get_progress_message()
            done = get_done()
            return progress != '' and not done

        @Condition
        def has_default_scope(_):
            return self.shell_ctx.default_command == ''

        self.has_default_scope = has_default_scope
        self.show_default = show_default
        self.show_symbol = show_symbol
        self.show_progress = show_progress

        # TODO fix this somehow
        self.input_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.)
                HighlightSearchProcessor(preview_search=Always()),
                HasFocus(SEARCH_BUFFER)),
            HighlightSelectionProcessor(),
            ConditionalProcessor(
                AppendAutoSuggestion(),
                HasFocus(DEFAULT_BUFFER) & self.has_default_scope)
        ]
Ejemplo n.º 20
0
def loop(cmd, history_file):
    buf = create_buffer(cmd, history_file)
    key_bindings = KeyBindings()
    bind_keys(buf, key_bindings)
    layout = create_layout(
        buffer=buf,
        multiline=True,
        lexer=SqlLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ],
        get_bottom_toolbar_tokens=lambda: get_toolbar_tokens(cmd),
        get_prompt_tokens=lambda: [('class:prompt', 'cr> ')])
    output = get_default_output()
    app = Application(layout=layout,
                      style=style_from_pygments_cls(CrateStyle),
                      key_bindings=merge_key_bindings(
                          [key_bindings,
                           load_open_in_editor_bindings()]),
                      editing_mode=_get_editing_mode(),
                      output=output)
    cmd.get_num_columns = lambda: output.get_size().columns

    while True:
        try:
            text = app.run()
            if text:
                cmd.process(text)
            buf.reset()
        except ProgrammingError as e:
            if '401' in e.message:
                username = cmd.username
                password = cmd.password
                cmd.username = input('Username: '******'Bye!')
            return
Ejemplo n.º 21
0
    def _build_cli(self, history):
        def set_vi_mode(value):
            self.vi_mode = value

        key_binding_manager = pgcli_bindings(
            get_vi_mode_enabled=lambda: self.vi_mode,
            set_vi_mode_enabled=set_vi_mode)

        def prompt_tokens(_):
            return [(Token.Prompt, '%s> ' % self.pgexecute.dbname)]

        def get_continuation_tokens(cli, width):
            return [(Token.Continuation, '.' * (width - 1) + ' ')]

        get_toolbar_tokens = create_toolbar_tokens_func(
            lambda: self.vi_mode, self.completion_refresher.is_refreshing)

        layout = create_prompt_layout(
            lexer=PygmentsLexer(PostgresLexer),
            reserve_space_for_menu=4,
            get_prompt_tokens=prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_toolbar_tokens,
            display_completions_in_columns=self.wider_completion_menu,
            multiline=True,
            extra_input_processors=[
                # Highlight matching brackets while editing.
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
            ])

        with self._completer_lock:
            buf = PGBuffer(always_multiline=self.multi_line,
                           completer=self.completer,
                           history=history,
                           complete_while_typing=Always(),
                           accept_action=AcceptAction.RETURN_DOCUMENT)

            application = Application(
                style=style_factory(self.syntax_style, self.cli_style),
                layout=layout,
                buffer=buf,
                key_bindings_registry=key_binding_manager.registry,
                on_exit=AbortAction.RAISE_EXCEPTION,
                on_abort=AbortAction.RETRY,
                ignore_case=True)

            cli = CommandLineInterface(application=application)

            return cli
Ejemplo n.º 22
0
 def create_cli_layout(self):
     from .lexer import AzureShellLexer
     lexer = AzureShellLexer
     return create_default_layout(
         message=u'azure> ',
         reserve_space_for_menu=8,
         lexer=lexer,
         extra_input_processors=[
             ConditionalProcessor(
                 processor=HighlightMatchingBracketProcessor(
                     chars='[](){}'),
                 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
         ])
Ejemplo n.º 23
0
    def _build_prompt_app(self, history):
        key_bindings = cli_bindings(self)

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

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

        def show_suggestion_tip():
            return self.iterations < 2

        get_toolbar_tokens = create_toolbar_tokens_func(
            self, show_suggestion_tip)

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

            self.prompt_app = PromptSession(
                lexer=PygmentsLexer(Lexer),
                reserve_space_for_menu=self.get_reserved_space(),
                message=get_message,
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=CompleteStyle.COLUMN,
                input_processors=[
                    ConditionalProcessor(
                        processor=HighlightMatchingBracketProcessor(
                            chars='[](){}'),
                        filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
                ],
                tempfile_suffix='.sql',
                completer=DynamicCompleter(lambda: self.completer),
                history=history,
                auto_suggest=AutoSuggestFromHistory(),
                complete_while_typing=True,
                multiline=cli_is_multiline(self),
                style=style_factory(self.syntax_style, self.cli_style),
                include_default_pygments_style=False,
                key_bindings=key_bindings,
                enable_open_in_editor=True,
                enable_system_prompt=True,
                editing_mode=editing_mode,
                search_ignore_case=True)
Ejemplo n.º 24
0
    def _create_buffer_control(self, editor_buffer):
        """
        Create a new BufferControl for a given location.
        """
        buffer_name = editor_buffer.buffer_name

        @Condition
        def preview_search(cli):
            return self.editor.incsearch

        @Condition
        def wrap_lines(cli):
            return self.editor.wrap_lines

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

            # Reporting of errors, for Pyflakes.
            ReportingProcessor(editor_buffer),

            # Replace tabs by spaces.
            TabsProcessor(self.editor)
        ]

        highlighters = [
            # Highlighting of the selection.
            SelectionHighlighter(),

            # Highlighting of the search.
            ConditionalHighlighter(
                SearchHighlighter(preview_search=preview_search),
                Condition(lambda cli: self.editor.highlight_search)),

            # Highlight matching parentheses.
            MatchingBracketHighlighter(),
        ]

        return BufferControl(lexer=DocumentLexer(editor_buffer),
                             input_processors=input_processors,
                             highlighters=highlighters,
                             buffer_name=buffer_name,
                             preview_search=preview_search,
                             wrap_lines=wrap_lines,
                             focus_on_click=True)
Ejemplo n.º 25
0
def main():
    hy_repl = HyREPL()
    eventloop = create_eventloop()
    validator = HyValidator()
    history = FileHistory(expanduser("~/.pthy_history"))

    def src_is_multiline():
        if app and app.buffer:
            text = app.buffer.document.text
            if '\n' in text:
                return True
        return False

    app = create_default_application(
        "λ: ",
        validator=validator,
        multiline=Condition(src_is_multiline),
        lexer=HyLexer,
        style=HyStyle,
        history=history,
        completer=HyCompleter(hy_repl),
        display_completions_in_columns=True,
        extra_input_processors=[
            ConditionalProcessor(processor=HighlightMatchingBracketProcessor(),
                                 filter=~IsDone())
        ])

    # Somewhat ugly trick to add a margin to the multiline input
    # without needing to define a custom layout
    app.layout.children[0].children[
        1].content.content.margin = ConditionalMargin(NumberredMargin(),
                                                      filter=IsMultiline())

    cli = CommandLineInterface(application=app, eventloop=eventloop)
    load_modified_bindings(app.key_bindings_registry)

    hy_repl.cli = cli

    try:
        while True:
            try:
                code_obj = cli.run()
                hy_repl.evaluate(code_obj.text)
            except KeyboardInterrupt:
                pass
    except EOFError:
        pass
    finally:
        eventloop.close()
Ejemplo n.º 26
0
Archivo: repl.py Proyecto: boseca/crash
def loop(cmd, history_file):
    key_binding_manager = KeyBindingManager(
        enable_search=True, enable_abort_and_exit_bindings=True)
    layout = create_prompt_layout(
        message=u'cr> ',
        multiline=True,
        lexer=SqlLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ])
    buffer = CrashBuffer(history=TruncatedFileHistory(
        history_file, max_length=MAX_HISTORY_LENGTH),
                         accept_action=AcceptAction.RETURN_DOCUMENT,
                         completer=SQLCompleter(cmd))
    buffer.complete_while_typing = lambda cli=None: cmd.should_autocomplete()
    application = Application(
        layout=layout,
        buffer=buffer,
        style=PygmentsStyle.from_defaults(pygments_style_cls=CrateStyle),
        key_bindings_registry=key_binding_manager.registry,
        editing_mode=_get_editing_mode(),
        on_exit=AbortAction.RAISE_EXCEPTION,
        on_abort=AbortAction.RETRY,
    )
    eventloop = create_eventloop()
    output = create_output()
    cli = CommandLineInterface(application=application,
                               eventloop=eventloop,
                               output=output)

    def get_num_columns_override():
        return output.get_size().columns

    cmd.get_num_columns = get_num_columns_override

    while True:
        try:
            doc = cli.run(reset_current_buffer=True)
            if doc:
                cmd.process(doc.text)
        except KeyboardInterrupt:
            cmd.logger.warn(
                "Query not cancelled. Run KILL <jobId> to cancel it")
        except EOFError:
            cmd.logger.warn(u'Bye!')
            return
Ejemplo n.º 27
0
    def _extra_prompt_options(self):
        """
        Return the current layout option for the current Terminal InteractiveShell
        """
        def get_message():
            return PygmentsTokens(self.prompts.in_prompt_tokens())

        if self.editing_mode == 'emacs':
            # with emacs mode the prompt is (usually) static, so we call only
            # the function once. With VI mode it can toggle between [ins] and
            # [nor] so we can't precompute.
            # here I'm going to favor the default keybinding which almost
            # everybody uses to decrease CPU usage.
            # if we have issues with users with custom Prompts we can see how to
            # work around this.
            get_message = get_message()

        options = {
            'complete_in_thread':
            False,
            'lexer':
            IPythonPTLexer(),
            'reserve_space_for_menu':
            self.space_for_menu,
            'message':
            get_message,
            'prompt_continuation':
            (lambda width, lineno, is_soft_wrap: PygmentsTokens(
                self.prompts.continuation_prompt_tokens(width))),
            'multiline':
            True,
            'complete_style':
            self.pt_complete_style,

            # Highlight matching brackets, but only when this setting is
            # enabled, and only when the DEFAULT_BUFFER has the focus.
            'input_processors': [
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()
                    & Condition(lambda: self.highlight_matching_brackets))
            ],
        }
        if not PTK3:
            options['inputhook'] = self.inputhook

        return options
Ejemplo n.º 28
0
    def _build_cli(self):
        eventloop = create_eventloop()

        history = FileHistory(
            os.path.join(
                os.path.expanduser("~"),
                ".{}_history".format(self._ctx.binary_name),
            ))

        layout = create_prompt_layout(
            lexer=PygmentsLexer(NubiaLexer),
            reserve_space_for_menu=5,
            get_prompt_tokens=self.get_prompt_tokens,
            get_rprompt_tokens=self._status_bar.get_rprompt_tokens,
            get_bottom_toolbar_tokens=self._status_bar.get_tokens,
            display_completions_in_columns=False,
            multiline=True,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars="[](){}"),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(),
                )
            ],
        )

        buf = Buffer(
            completer=self._completer,
            history=history,
            auto_suggest=self._suggestor,
            complete_while_typing=Always(),
            accept_action=AcceptAction.RETURN_DOCUMENT,
        )

        application = Application(
            style=shell_style,
            buffer=buf,
            key_bindings_registry=self._registry,
            layout=layout,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True,
        )

        cli = CommandLineInterface(application=application,
                                   eventloop=eventloop)
        return cli
Ejemplo n.º 29
0
    def __init__(self, project=None, instance=None, database=None, credentials=None, with_pager=False,
                 inp=None, output=None):
        # setup environment variables
        # less option for pager
        if not os.environ.get(config.EnvironmentVariables.LESS):
            os.environ[config.EnvironmentVariables.LESS] = config.Constants.LESS_FLAG
        self.with_pager = with_pager
        self.logger = logging.getLogger('spanner-cli')
        self.logger.debug("Staring spanner-cli project=%s, instance=%s, database=%s", project, instance, database)
        self.project = project
        with warnings.catch_warnings(record=True) as warns:
            warnings.simplefilter("always")
            self.client = spanner.Client(
                project=self.project,
                credentials=credentials,
                client_info=client_info.ClientInfo(user_agent=__name__),
            )
            if len(warns) > 0:
                for w in warns:
                    self.logger.debug(w)
                    click.echo(message=w.message, err=True, nl=True)

        self.instance = self.client.instance(instance)
        self.database = self.instance.database(database)
        self.prompt_message = self.get_prompt_message()
        self.completer = SQLCompleter()
        self.open_history_file()
        self.rehash()
        self.session = PromptSession(
            message=self.prompt_message,
            lexer=PygmentsLexer(lexer.SpannerLexer),
            completer=DynamicCompleter(lambda: self.completer),
            style=style_from_pygments_cls(get_style_by_name(config.get_pygment_style())),
            history=self.history,
            auto_suggest=AutoSuggestFromHistory(),
            input_processors=[ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(
                    chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()  # pylint: disable=invalid-unary-operand-type
            )],
            input=inp,
            output=output,
        )

        self.formatter = tabular_output.TabularOutputFormatter('ascii')
Ejemplo n.º 30
0
def question(get_prompt_tokens, choices, default=None, page_size=None, history=None, mouse_support=True):
    layout = create_default_layout(
        get_prompt_tokens=get_prompt_tokens,
        extra_input_processors=[
            ConditionalProcessor(HideInputProcessor(), ~IsDone()),
        ],
        reactive_window_factory=rawlist_window_factory(InfiniteWindow, RawListControl(), page_size),
        hide_cursor=True)

    # don't add list responses to history
    history = None

    return create_prompt_application(
        layout,
        buf=RawListBuffer(
            choices,
            default,
        ),
        history=history,
        mouse_support=mouse_support)