Beispiel #1
0
    def create_application(self, full_layout=True):
        """ makes the application object and the buffers """
        if full_layout:
            layout = create_layout(self, self.lexer, ExampleLexer, ToolbarLexer)
        else:
            layout = create_tutorial_layout(self.lexer)

        buffers = {
            DEFAULT_BUFFER: Buffer(is_multiline=True),
            'description': Buffer(is_multiline=True, read_only=True),
            'parameter': Buffer(is_multiline=True, read_only=True),
            'examples': Buffer(is_multiline=True, read_only=True),
            'bottom_toolbar': Buffer(is_multiline=True),
            'example_line': Buffer(is_multiline=True),
            'default_values': Buffer(),
            'symbols': Buffer(),
            'progress': Buffer(is_multiline=False)
        }

        writing_buffer = Buffer(
            history=self.history,
            auto_suggest=AutoSuggestFromHistory(),
            enable_history_search=True,
            completer=self.completer,
            complete_while_typing=Always()
        )

        return Application(
            mouse_support=False,
            style=self.styles,
            buffer=writing_buffer,
            on_input_timeout=self.on_input_timeout,
            key_bindings_registry=InteractiveKeyBindings(self).registry,
            layout=layout,
            buffers=buffers,
        )
Beispiel #2
0
    def create_prompt_application(self,
                                  message='',
                                  multiline=False,
                                  wrap_lines=True,
                                  is_password=False,
                                  vi_mode=False,
                                  complete_while_typing=True,
                                  enable_history_search=False,
                                  lexer=None,
                                  enable_system_bindings=False,
                                  enable_open_in_editor=False,
                                  validator=None,
                                  completer=None,
                                  reserve_space_for_menu=8,
                                  auto_suggest=None,
                                  style=None,
                                  history=None,
                                  clipboard=None,
                                  get_prompt_tokens=None,
                                  get_bottom_toolbar_tokens=None,
                                  display_completions_in_columns=False,
                                  get_title=None,
                                  mouse_support=False,
                                  extra_input_processors=None,
                                  key_bindings_registry=None,
                                  on_abort=AbortAction.RAISE_EXCEPTION,
                                  on_exit=AbortAction.RAISE_EXCEPTION,
                                  accept_action=AcceptAction.RETURN_DOCUMENT,
                                  default=''):
        """Create an :class:`~Application` instance for a prompt.

        (It is meant to cover 90% of the prompt use cases, where no extreme
        customization is required. For more complex input, it is required to create
        a custom :class:`~Application` instance.)

        message : Text to be shown before the prompt.
        mulitiline : Allow multiline input. Pressing enter will insert a
                           newline. (This requires Meta+Enter to accept the input.)
        wrap_lines : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`.
            When True (the default), automatically wrap long lines instead of
            scrolling horizontally.
        is_password : Show asterisks instead of the actual typed characters.
        vi_mode : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`. If
            True, use Vi key bindings.
        complete_while_typing : `bool` or
            :class:`~prompt_toolkit.filters.CLIFilter`. Enable autocompletion while
            typing.
        enable_history_search : `bool` or
            :class:`~prompt_toolkit.filters.CLIFilter`. Enable up-arrow parting
            string matching.
        lexer : :class:`~prompt_toolkit.layout.lexers.Lexer` to be used for
            the syntax highlighting.
        validator : :class:`~prompt_toolkit.validation.Validator` instance
            for input validation.
        completer : :class:`~prompt_toolkit.completion.Completer` instance
            for input completion.
        reserve_space_for_menu : Space to be reserved for displaying the menu.
            (0 means that no space needs to be reserved.)
        auto_suggest : :class:`~prompt_toolkit.auto_suggest.AutoSuggest`
            instance for input suggestions.
        style : Pygments style class for the color scheme.
        enable_system_bindings : `bool` or
            :class:`~prompt_toolkit.filters.CLIFilter`. Pressing Meta+'!' will show
            a system prompt.
        enable_open_in_editor : `bool` or
            :class:`~prompt_toolkit.filters.CLIFilter`. Pressing 'v' in Vi mode or
            C-X C-E in emacs mode will open an external editor.
        history : :class:`~prompt_toolkit.history.History` instance.
        clipboard : :class:`~prompt_toolkit.clipboard.base.Clipboard` instance.
            (e.g. :class:`~prompt_toolkit.clipboard.in_memory.InMemoryClipboard`)
        get_bottom_toolbar_tokens : Optional callable which takes a
            :class:`~prompt_toolkit.interface.CommandLineInterface` and returns a
            list of tokens for the bottom toolbar.
        display_completions_in_columns : `bool` or
            :class:`~prompt_toolkit.filters.CLIFilter`. Display the completions in
            multiple columns.
        get_title : Callable that returns the title to be displayed in the
            terminal.
        mouse_support : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`
            to enable mouse support.
        default : The default text to be shown in the input buffer. (This can
            be edited by the user.)

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.

        WARNING; This method is due for removal once prompt-toolkit >v0.54 
        is released.
        """
        if key_bindings_registry is None:
            key_bindings_registry = KeyBindingManager.for_prompt(
                enable_vi_mode=vi_mode,
                enable_system_bindings=enable_system_bindings,
                enable_open_in_editor=enable_open_in_editor).registry

        # Make sure that complete_while_typing is disabled when enable_history_search
        # is enabled. (First convert to SimpleFilter, to avoid doing bitwise operations
        # on bool objects.)
        complete_while_typing = to_simple_filter(complete_while_typing)
        enable_history_search = to_simple_filter(enable_history_search)
        multiline = to_simple_filter(multiline)

        complete_while_typing = complete_while_typing & ~enable_history_search

        # Accept Pygments styles as well for backwards compatibility.
        try:
            if issubclass(style, pygments.style.Style):
                style = PygmentsStyle(style)
        except TypeError:  # Happens when style is `None` or an instance of something else.
            pass

        # Create application
        return Application(layout=self.create_prompt_layout(
            message=message,
            lexer=lexer,
            is_password=is_password,
            reserve_space_for_menu=(reserve_space_for_menu
                                    if completer is not None else 0),
            multiline=Condition(lambda cli: multiline()),
            get_prompt_tokens=get_prompt_tokens,
            get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
            display_completions_in_columns=display_completions_in_columns,
            extra_input_processors=extra_input_processors,
            wrap_lines=wrap_lines),
                           buffer=Buffer(
                               enable_history_search=enable_history_search,
                               complete_while_typing=complete_while_typing,
                               is_multiline=multiline,
                               history=(history or InMemoryHistory()),
                               validator=validator,
                               completer=completer,
                               auto_suggest=auto_suggest,
                               accept_action=accept_action,
                               initial_document=Document(default),
                           ),
                           style=style or DEFAULT_STYLE,
                           clipboard=clipboard,
                           key_bindings_registry=key_bindings_registry,
                           get_title=get_title,
                           mouse_support=mouse_support,
                           on_abort=on_abort,
                           on_exit=on_exit)
Beispiel #3
0
    def _create_cli(self):
        """Creates a new cli"""
        history = FileHistory('.history')

        def toolbar_handler(_):
            """Returns bottom menu items.
            Args:
                * _: An instance of prompt_toolkit's Cli (not used).
            Returns:
                A list of Token.Toolbar.
            """
            return [(Token.Toolbar, ' [F9] Docs '),
                    (Token.Toolbar, ' [F10] Exit ')]

        def url_handler(_):
            if self.service.last_request is not None:
                method = ' ' + self.service.last_request['method']
                url = ' ' + self.service.last_request['url']
                headers = ''
                if self.service.last_request['headers'] is not None:
                    headers = ' ' + '; '.join([
                        key + ': ' + value for key, value in
                        self.service.last_request['headers'].items()
                    ])
                return [(Token.Method, method), (Token.Url, url),
                        (Token.Headers, headers)]
            return [(Token.Method, ''), (Token.Url, ''), (Token.Headers, '')]

        layout = self._create_layout(message='atomix> ',
                                     reserve_space_for_menu=8,
                                     lexer=CommandLexer,
                                     get_bottom_toolbar_tokens=toolbar_handler,
                                     get_url_tokens=url_handler)

        buffer = Buffer(history=history,
                        auto_suggest=CommandAutoSuggest(self.commands),
                        enable_history_search=True,
                        completer=CommandCompleter(self.commands),
                        complete_while_typing=Always(),
                        accept_action=AcceptAction.RETURN_DOCUMENT)

        key_manager = KeyBindingManager(enable_search=True,
                                        enable_abort_and_exit_bindings=True,
                                        enable_system_bindings=True,
                                        enable_auto_suggest_bindings=True)

        @key_manager.registry.add_binding(Keys.F9)
        def handle_f9(_):
            """Inputs the "docs" command when the `F9` key is pressed.
            Args:
                * _: An instance of prompt_toolkit's Event (not used).
            Returns:
                None.
            """
            webbrowser.open('http://atomix.io')

        @key_manager.registry.add_binding(Keys.F10)
        def handle_f10(_):
            """Quits when the `F10` key is pressed."""
            raise EOFError

        @key_manager.registry.add_binding(Keys.ControlSpace)
        def handle_ctrl_space(event):
            """Initializes autocompletion at the cursor.
            If the autocompletion menu is not showing, display it with the
            appropriate completions for the context.
            If the menu is showing, select the next completion.
            Args:
                * event: An instance of prompt_toolkit's Event.
            Returns:
                None.
            """
            b = event.cli.current_buffer
            if b.complete_state:
                b.complete_next()
            else:
                event.cli.start_completion(select_first=False)

        application = Application(mouse_support=False,
                                  style=get_style(self.theme),
                                  layout=layout,
                                  buffer=buffer,
                                  key_bindings_registry=key_manager.registry,
                                  on_exit=AbortAction.RAISE_EXCEPTION,
                                  on_abort=AbortAction.RETRY,
                                  ignore_case=True)

        eventloop = create_eventloop()

        return CommandLineInterface(application=application,
                                    eventloop=eventloop)