Esempio n. 1
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.prompter = Prompter()
     self.history = PromptToolkitHistory()
     self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
     self.key_bindings_manager = KeyBindingManager(
         enable_auto_suggest_bindings=True,
         enable_search=True,
         enable_abort_and_exit_bindings=True,
         enable_vi_mode=Condition(lambda cli: builtins.__xonsh_env__.get('VI_MODE')),
         enable_open_in_editor=True)
     load_xonsh_bindings(self.key_bindings_manager)
Esempio n. 2
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.prompter = Prompter()
     self.history = PromptToolkitHistory()
     self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
     key_bindings_manager_args = {
         'enable_auto_suggest_bindings': True,
         'enable_search': True,
         'enable_abort_and_exit_bindings': True,
         }
     self.key_bindings_manager = KeyBindingManager(**key_bindings_manager_args)
     load_xonsh_bindings(self.key_bindings_manager)
Esempio n. 3
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.prompter = Prompter()
     self.history = PromptToolkitHistory()
     self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
     key_bindings_manager_args = {
         'enable_auto_suggest_bindings': True,
         'enable_search': True,
         'enable_abort_and_exit_bindings': True,
     }
     self.key_bindings_manager = KeyBindingManager(
         **key_bindings_manager_args)
     load_xonsh_bindings(self.key_bindings_manager)
     # This assumes that PromptToolkitShell is a singleton
     events.on_ptk_create.fire(self.prompter, self.history,
                               self.pt_completer, self.key_bindings_manager)
Esempio n. 4
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     if ON_WINDOWS:
         winutils.enable_virtual_terminal_processing()
     self._first_prompt = True
     self.prompter = Prompter()
     self.history = PromptToolkitHistory()
     self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx, self)
     key_bindings_manager_args = {
         'enable_auto_suggest_bindings': True,
         'enable_search': True,
         'enable_abort_and_exit_bindings': True,
     }
     self.key_bindings_manager = KeyBindingManager(**key_bindings_manager_args)
     load_xonsh_bindings(self.key_bindings_manager)
     # This assumes that PromptToolkitShell is a singleton
     events.on_ptk_create.fire(
         prompter=self.prompter,
         history=self.history,
         completer=self.pt_completer,
         bindings=self.key_bindings_manager,
     )
Esempio n. 5
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.prompter = Prompter()
     self.history = PromptToolkitHistory()
     self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
     key_bindings_manager_args = {
         'enable_auto_suggest_bindings': True,
         'enable_search': True,
         'enable_abort_and_exit_bindings': True,
         }
     self.key_bindings_manager = KeyBindingManager(**key_bindings_manager_args)
     load_xonsh_bindings(self.key_bindings_manager)
     # This assumes that PromptToolkitShell is a singleton
     events.on_ptk_create.fire(self.prompter, self.history, self.pt_completer, self.key_bindings_manager)
Esempio n. 6
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)

        key_bindings_manager_args = {
                'enable_auto_suggest_bindings': True,
                'enable_search': True,
                'enable_abort_and_exit_bindings': True,
                }

        self.key_bindings_manager = KeyBindingManager(**key_bindings_manager_args)
        load_xonsh_bindings(self.key_bindings_manager)
Esempio n. 7
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)

        key_bindings_manager_args = {
            'enable_auto_suggest_bindings': True,
            'enable_search': True,
            'enable_abort_and_exit_bindings': True,
            'enable_open_in_editor': True,
        }
        major, minor = ptk_version_info()[:2]
        self.new_vi_mode_flag = (major, minor) >= (1, 0) \
                                and ptk_version() != '<0.57'
        if not self.new_vi_mode_flag:
            # enable_vi_mode is deprecated acoording to prompt_toolset 1.0 document.
            key_bindings_manager_args['enable_vi_mode'] = Condition(
                lambda cli: builtins.__xonsh_env__.get('VI_MODE'))

        self.key_bindings_manager = KeyBindingManager(
            **key_bindings_manager_args)
        load_xonsh_bindings(self.key_bindings_manager)
Esempio n. 8
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     if ON_WINDOWS:
         winutils.enable_virtual_terminal_processing()
     self._first_prompt = True
     self.prompter = Prompter()
     self.history = PromptToolkitHistory()
     self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx, self)
     key_bindings_manager_args = {
         'enable_auto_suggest_bindings': True,
         'enable_search': True,
         'enable_abort_and_exit_bindings': True,
         }
     self.key_bindings_manager = KeyBindingManager(**key_bindings_manager_args)
     load_xonsh_bindings(self.key_bindings_manager)
     # This assumes that PromptToolkitShell is a singleton
     events.on_ptk_create.fire(
         prompter=self.prompter,
         history=self.history,
         completer=self.pt_completer,
         bindings=self.key_bindings_manager,
     )
Esempio n. 9
0
class PromptToolkitShell(BaseShell):
    """The xonsh shell."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)

        key_bindings_manager_args = {
                'enable_auto_suggest_bindings': True,
                'enable_search': True,
                'enable_abort_and_exit_bindings': True,
                }

        self.key_bindings_manager = KeyBindingManager(**key_bindings_manager_args)
        load_xonsh_bindings(self.key_bindings_manager)

    def singleline(self, store_in_history=True, auto_suggest=None,
                   enable_history_search=True, multiline=True, **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        env = builtins.__xonsh_env__
        mouse_support = env.get('MOUSE_SUPPORT')
        if store_in_history:
            history = self.history
        else:
            history = None
            enable_history_search = False
        auto_suggest = auto_suggest if env.get('AUTO_SUGGEST') else None
        completions_display = env.get('COMPLETIONS_DISPLAY')
        multicolumn = (completions_display == 'multi')
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        completer = None if completions_display == 'none' else self.pt_completer
        prompt_tokens = self.prompt_tokens(None)
        get_prompt_tokens = lambda cli: prompt_tokens
        rprompt_tokens = self.rprompt_tokens(None)
        get_rprompt_tokens = lambda cli: rprompt_tokens
        with self.prompter:
            prompt_args = {
                    'mouse_support': mouse_support,
                    'auto_suggest': auto_suggest,
                    'get_prompt_tokens': get_prompt_tokens,
                    'get_rprompt_tokens': get_rprompt_tokens,
                    'style': PygmentsStyle(xonsh_style_proxy(self.styler)),
                    'completer': completer,
                    'multiline': multiline,
                    'get_continuation_tokens': self.continuation_tokens,
                    'history': history,
                    'enable_history_search': enable_history_search,
                    'reserve_space_for_menu': 0,
                    'key_bindings_registry': self.key_bindings_manager.registry,
                    'display_completions_in_columns': multicolumn,
                    }
            if builtins.__xonsh_env__.get('COLOR_INPUT'):
                prompt_args['lexer'] = PygmentsLexer(XonshLexer)
            line = self.prompter.prompt(**prompt_args)
        return line

    def push(self, line):
        """Pushes a line onto the buffer and compiles the code in a way that
        enables multiline input.
        """
        code = None
        self.buffer.append(line)
        if self.need_more_lines:
            return None, code
        src = ''.join(self.buffer)
        try:
            code = self.execer.compile(src,
                                       mode='single',
                                       glbs=self.ctx,
                                       locs=None)
            self.reset_buffer()
        except Exception:  # pylint: disable=broad-except
            self.reset_buffer()
            print_exception()
            return src, None
        return src, code

    def cmdloop(self, intro=None):
        """Enters a loop that reads and execute input from user."""
        if intro:
            print(intro)
        auto_suggest = AutoSuggestFromHistory()
        while not builtins.__xonsh_exit__:
            try:
                line = self.singleline(auto_suggest=auto_suggest)
                if not line:
                    self.emptyline()
                else:
                    line = self.precmd(line)
                    self.default(line)
            except KeyboardInterrupt:
                self.reset_buffer()
            except EOFError:
                if builtins.__xonsh_env__.get("IGNOREEOF"):
                    print('Use "exit" to leave the shell.')
                else:
                    break

    def prompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current prompt."""
        p = builtins.__xonsh_env__.get('PROMPT')
        try:
            p = partial_format_prompt(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        self.settitle()
        return toks

    def rprompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current right
        prompt.
        """
        p = builtins.__xonsh_env__.get('RIGHT_PROMPT')
        # partial_format_prompt does handle empty strings properly,
        # but this avoids descending into it in the common case of
        # $RIGHT_PROMPT == ''.
        if isinstance(p, str) and len(p) == 0:
            return []
        try:
            p = partial_format_prompt(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        return toks

    def continuation_tokens(self, cli, width):
        """Displays dots in multiline prompt"""
        width = width - 1
        dots = builtins.__xonsh_env__.get('MULTILINE_PROMPT')
        dots = dots() if callable(dots) else dots
        if dots is None:
            return [(Token, ' '*(width + 1))]
        basetoks = self.format_color(dots)
        baselen = sum(len(t[1]) for t in basetoks)
        if baselen == 0:
            return [(Token, ' '*(width + 1))]
        toks = basetoks * (width // baselen)
        n = width % baselen
        count = 0
        for tok in basetoks:
            slen = len(tok[1])
            newcount = slen + count
            if slen == 0:
                continue
            elif newcount <= n:
                toks.append(tok)
            else:
                toks.append((tok[0], tok[1][:n-count]))
            count = newcount
            if n <= count:
                break
        toks.append((Token, ' '))  # final space
        return toks

    def format_color(self, string, **kwargs):
        """Formats a color string using Pygments. This, therefore, returns
        a list of (Token, str) tuples.
        """
        return partial_color_tokenize(string)

    def print_color(self, string, end='\n', **kwargs):
        """Prints a color string using prompt-toolkit color management."""
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        if isinstance(string, str):
            tokens = partial_color_tokenize(string + end)
        else:
            # assume this is a list of (Token, str) tuples and just print
            tokens = string
        proxy_style = PygmentsStyle(xonsh_style_proxy(self.styler))
        print_tokens(tokens, style=proxy_style)

    def color_style_names(self):
        """Returns an iterable of all available style names."""
        return get_all_styles()

    def color_style(self):
        """Returns the current color map."""
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        return self.styler.styles
Esempio n. 10
0
class PromptToolkitShell(BaseShell):
    """The xonsh shell."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
        self.key_bindings_manager = KeyBindingManager(
            enable_auto_suggest_bindings=True,
            enable_search=True,
            enable_abort_and_exit_bindings=True,
            enable_vi_mode=Condition(lambda cli: builtins.__xonsh_env__.get('VI_MODE')),
            enable_open_in_editor=True)
        load_xonsh_bindings(self.key_bindings_manager)

    def cmdloop(self, intro=None):
        """Enters a loop that reads and execute input from user."""
        if intro:
            print(intro)
        _auto_suggest = AutoSuggestFromHistory()
        while not builtins.__xonsh_exit__:
            try:
                token_func, style_cls = self._get_prompt_tokens_and_style()
                env = builtins.__xonsh_env__
                mouse_support = env.get('MOUSE_SUPPORT')
                if env.get('AUTO_SUGGEST'):
                    auto_suggest = _auto_suggest
                else:
                    auto_suggest = None
                completions_display = env.get('COMPLETIONS_DISPLAY')
                multicolumn = (completions_display == 'multi')
                completer = None if completions_display == 'none' else self.pt_completer
                with self.prompter:
                    line = self.prompter.prompt(
                        mouse_support=mouse_support,
                        auto_suggest=auto_suggest,
                        get_prompt_tokens=token_func,
                        style=style_cls,
                        completer=completer,
                        lexer=PygmentsLexer(XonshLexer),
                        history=self.history,
                        multiline=True, 
                        enable_history_search=True,
                        reserve_space_for_menu=0,
                        key_bindings_registry=self.key_bindings_manager.registry,
                        display_completions_in_columns=multicolumn)
                if not line:
                    self.emptyline()
                else:
                    line = self.precmd(line)
                    self.default(line)
            except KeyboardInterrupt:
                self.reset_buffer()
            except EOFError:
                if builtins.__xonsh_env__.get("IGNOREEOF"):
                    print('Use "exit" to leave the shell.')
                else:
                    break

    def _get_prompt_tokens_and_style(self):
        """Returns function to pass as prompt to prompt_toolkit."""
        token_names, cstyles, strings = format_prompt_for_prompt_toolkit(self.prompt)
        tokens = [getattr(Token, n) for n in token_names]

        def get_tokens(cli):
            return list(zip(tokens, strings))

        custom_style = _xonsh_style(tokens, cstyles)

        return get_tokens, custom_style
Esempio n. 11
0
class PromptToolkitShell(BaseShell):
    """The xonsh shell."""
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
        key_bindings_manager_args = {
            'enable_auto_suggest_bindings': True,
            'enable_search': True,
            'enable_abort_and_exit_bindings': True,
        }
        self.key_bindings_manager = KeyBindingManager(
            **key_bindings_manager_args)
        load_xonsh_bindings(self.key_bindings_manager)
        # This assumes that PromptToolkitShell is a singleton
        events.on_ptk_create.fire(self.prompter, self.history,
                                  self.pt_completer, self.key_bindings_manager)

    def singleline(self,
                   store_in_history=True,
                   auto_suggest=None,
                   enable_history_search=True,
                   multiline=True,
                   **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        env = builtins.__xonsh_env__
        mouse_support = env.get('MOUSE_SUPPORT')
        if store_in_history:
            history = self.history
        else:
            history = None
            enable_history_search = False
        auto_suggest = auto_suggest if env.get('AUTO_SUGGEST') else None
        completions_display = env.get('COMPLETIONS_DISPLAY')
        multicolumn = (completions_display == 'multi')
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        completer = None if completions_display == 'none' else self.pt_completer
        if not env.get('UPDATE_PROMPT_ON_KEYPRESS'):
            prompt_tokens_cached = self.prompt_tokens(None)
            get_prompt_tokens = lambda cli: prompt_tokens_cached
            rprompt_tokens_cached = self.rprompt_tokens(None)
            get_rprompt_tokens = lambda cli: rprompt_tokens_cached
            bottom_toolbar_tokens_cached = self.bottom_toolbar_tokens(None)
            get_bottom_toolbar_tokens = lambda cli: bottom_toolbar_tokens_cached
        else:
            get_prompt_tokens = self.prompt_tokens
            get_rprompt_tokens = self.rprompt_tokens
            get_bottom_toolbar_tokens = self.bottom_toolbar_tokens

        with self.prompter:
            prompt_args = {
                'mouse_support': mouse_support,
                'auto_suggest': auto_suggest,
                'get_prompt_tokens': get_prompt_tokens,
                'get_rprompt_tokens': get_rprompt_tokens,
                'get_bottom_toolbar_tokens': get_bottom_toolbar_tokens,
                'style': PygmentsStyle(xonsh_style_proxy(self.styler)),
                'completer': completer,
                'multiline': multiline,
                'get_continuation_tokens': self.continuation_tokens,
                'history': history,
                'enable_history_search': enable_history_search,
                'reserve_space_for_menu': 0,
                'key_bindings_registry': self.key_bindings_manager.registry,
                'display_completions_in_columns': multicolumn,
            }
            if builtins.__xonsh_env__.get('COLOR_INPUT'):
                prompt_args['lexer'] = PygmentsLexer(XonshLexer)
            line = self.prompter.prompt(**prompt_args)
        return line

    def _push(self, line):
        """Pushes a line onto the buffer and compiles the code in a way that
        enables multiline input.
        """
        code = None
        self.buffer.append(line)
        if self.need_more_lines:
            return None, code
        src = ''.join(self.buffer)
        src = transform_command(src)
        try:
            code = self.execer.compile(src,
                                       mode='single',
                                       glbs=self.ctx,
                                       locs=None)
            self.reset_buffer()
        except Exception:  # pylint: disable=broad-except
            self.reset_buffer()
            print_exception()
            return src, None
        return src, code

    def cmdloop(self, intro=None):
        """Enters a loop that reads and execute input from user."""
        if intro:
            print(intro)
        auto_suggest = AutoSuggestFromHistory()
        self.push = self._push
        while not builtins.__xonsh_exit__:
            try:
                line = self.singleline(auto_suggest=auto_suggest)
                if not line:
                    self.emptyline()
                else:
                    line = self.precmd(line)
                    self.default(line)
            except KeyboardInterrupt:
                self.reset_buffer()
            except EOFError:
                if builtins.__xonsh_env__.get("IGNOREEOF"):
                    print('Use "exit" to leave the shell.', file=sys.stderr)
                else:
                    break

    def prompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current prompt."""
        p = builtins.__xonsh_env__.get('PROMPT')
        try:
            p = self.prompt_formatter(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        self.settitle()
        return toks

    def rprompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current right
        prompt.
        """
        p = builtins.__xonsh_env__.get('RIGHT_PROMPT')
        # self.prompt_formatter does handle empty strings properly,
        # but this avoids descending into it in the common case of
        # $RIGHT_PROMPT == ''.
        if isinstance(p, str) and len(p) == 0:
            return []
        try:
            p = self.prompt_formatter(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        return toks

    def bottom_toolbar_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current bottom
        toolbar.
        """
        p = builtins.__xonsh_env__.get('BOTTOM_TOOLBAR')
        # self.prompt_formatter does handle empty strings properly,
        # but this avoids descending into it in the common case of
        # $TOOLBAR == ''.
        if isinstance(p, str) and len(p) == 0:
            return []
        try:
            p = self.prompt_formatter(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        return toks

    def continuation_tokens(self, cli, width):
        """Displays dots in multiline prompt"""
        width = width - 1
        dots = builtins.__xonsh_env__.get('MULTILINE_PROMPT')
        dots = dots() if callable(dots) else dots
        if dots is None:
            return [(Token, ' ' * (width + 1))]
        basetoks = self.format_color(dots)
        baselen = sum(len(t[1]) for t in basetoks)
        if baselen == 0:
            return [(Token, ' ' * (width + 1))]
        toks = basetoks * (width // baselen)
        n = width % baselen
        count = 0
        for tok in basetoks:
            slen = len(tok[1])
            newcount = slen + count
            if slen == 0:
                continue
            elif newcount <= n:
                toks.append(tok)
            else:
                toks.append((tok[0], tok[1][:n - count]))
            count = newcount
            if n <= count:
                break
        toks.append((Token, ' '))  # final space
        return toks

    def format_color(self, string, hide=False, force_string=False, **kwargs):
        """Formats a color string using Pygments. This, therefore, returns
        a list of (Token, str) tuples. If force_string is set to true, though,
        this will return a color fomtatted string.
        """
        tokens = partial_color_tokenize(string)
        if force_string:
            env = builtins.__xonsh_env__
            self.styler.style_name = env.get('XONSH_COLOR_STYLE')
            proxy_style = xonsh_style_proxy(self.styler)
            formatter = XonshTerminal256Formatter(style=proxy_style)
            s = pygments.format(tokens, formatter)
            return s
        else:
            return tokens

    def print_color(self, string, end='\n', **kwargs):
        """Prints a color string using prompt-toolkit color management."""
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        if isinstance(string, str):
            tokens = partial_color_tokenize(string + end)
        else:
            # assume this is a list of (Token, str) tuples and just print
            tokens = string
        proxy_style = PygmentsStyle(xonsh_style_proxy(self.styler))
        print_tokens(tokens, style=proxy_style)

    def color_style_names(self):
        """Returns an iterable of all available style names."""
        return get_all_styles()

    def color_style(self):
        """Returns the current color map."""
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        return self.styler.styles
Esempio n. 12
0
File: shell.py Progetto: minrk/xonsh
class PromptToolkitShell(BaseShell):
    """The xonsh shell."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
        self.key_bindings_manager = KeyBindingManager(
            enable_auto_suggest_bindings=True,
            enable_search=True,
            enable_abort_and_exit_bindings=True,
            enable_vi_mode=Condition(lambda cli: builtins.__xonsh_env__.get('VI_MODE')),
            enable_open_in_editor=True)
        load_xonsh_bindings(self.key_bindings_manager)

    def singleline(self, store_in_history=True, auto_suggest=None, 
                   enable_history_search=True, multiline=True, **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        token_func, style_cls = self._get_prompt_tokens_and_style()
        env = builtins.__xonsh_env__
        mouse_support = env.get('MOUSE_SUPPORT')
        if store_in_history:
            history = self.history
        else:
            history = None
            enable_history_search = False
        auto_suggest = auto_suggest if env.get('AUTO_SUGGEST') else None
        completions_display = env.get('COMPLETIONS_DISPLAY')
        multicolumn = (completions_display == 'multi')
        completer = None if completions_display == 'none' else self.pt_completer
        with self.prompter:
            line = self.prompter.prompt(
                    mouse_support=mouse_support,
                    auto_suggest=auto_suggest,
                    get_prompt_tokens=token_func,
                    style=style_cls,
                    completer=completer,
                    lexer=PygmentsLexer(XonshLexer),
                    multiline=multiline, 
                    history=history,
                    enable_history_search=enable_history_search,
                    reserve_space_for_menu=0,
                    key_bindings_registry=self.key_bindings_manager.registry,
                    display_completions_in_columns=multicolumn)
        return line

    def push(self, line):
        """Pushes a line onto the buffer and compiles the code in a way that
        enables multiline input.
        """
        code = None
        self.buffer.append(line)
        if self.need_more_lines:
            return None, code
        src = ''.join(self.buffer)
        try:
            code = self.execer.compile(src,
                                       mode='single',
                                       glbs=None,
                                       locs=self.ctx)
            self.reset_buffer()
        except Exception:  # pylint: disable=broad-except
            self.reset_buffer()
            print_exception()
            return src, None
        return src, code

    def cmdloop(self, intro=None):
        """Enters a loop that reads and execute input from user."""
        if intro:
            print(intro)
        auto_suggest = AutoSuggestFromHistory()
        while not builtins.__xonsh_exit__:
            try:
                line = self.singleline(auto_suggest=auto_suggest)
                if not line:
                    self.emptyline()
                else:
                    line = self.precmd(line)
                    self.default(line)
            except KeyboardInterrupt:
                self.reset_buffer()
            except EOFError:
                if builtins.__xonsh_env__.get("IGNOREEOF"):
                    print('Use "exit" to leave the shell.')
                else:
                    break

    def _get_prompt_tokens_and_style(self):
        """Returns function to pass as prompt to prompt_toolkit."""
        token_names, cstyles, strings = format_prompt_for_prompt_toolkit(self.prompt)
        tokens = [getattr(Token, n) for n in token_names]

        def get_tokens(cli):
            return list(zip(tokens, strings))

        custom_style = _xonsh_style(tokens, cstyles)

        return get_tokens, custom_style
Esempio n. 13
0
class PromptToolkitShell(BaseShell):
    """The xonsh shell."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
        self.key_bindings_manager = KeyBindingManager(
            enable_auto_suggest_bindings=True,
            enable_search=True,
            enable_abort_and_exit_bindings=True,
            enable_vi_mode=Condition(lambda cli: builtins.__xonsh_env__.get('VI_MODE')),
            enable_open_in_editor=True)
        load_xonsh_bindings(self.key_bindings_manager)

    def singleline(self, store_in_history=True, auto_suggest=None,
                   enable_history_search=True, multiline=True, **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        env = builtins.__xonsh_env__
        mouse_support = env.get('MOUSE_SUPPORT')
        if store_in_history:
            history = self.history
        else:
            history = None
            enable_history_search = False
        auto_suggest = auto_suggest if env.get('AUTO_SUGGEST') else None
        completions_display = env.get('COMPLETIONS_DISPLAY')
        multicolumn = (completions_display == 'multi')
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        completer = None if completions_display == 'none' else self.pt_completer
        prompt_tokens = self.prompt_tokens(None)
        get_prompt_tokens = lambda cli: prompt_tokens
        rprompt_tokens = self.rprompt_tokens(None)
        get_rprompt_tokens = lambda cli: rprompt_tokens
        with self.prompter:
            line = self.prompter.prompt(
                    mouse_support=mouse_support,
                    auto_suggest=auto_suggest,
                    get_prompt_tokens=get_prompt_tokens,
                    get_rprompt_tokens=get_rprompt_tokens,
                    style=PygmentsStyle(xonsh_style_proxy(self.styler)),
                    completer=completer,
                    lexer=PygmentsLexer(XonshLexer),
                    multiline=multiline,
                    get_continuation_tokens=self.continuation_tokens,
                    history=history,
                    enable_history_search=enable_history_search,
                    reserve_space_for_menu=0,
                    key_bindings_registry=self.key_bindings_manager.registry,
                    display_completions_in_columns=multicolumn)
        return line

    def push(self, line):
        """Pushes a line onto the buffer and compiles the code in a way that
        enables multiline input.
        """
        code = None
        self.buffer.append(line)
        if self.need_more_lines:
            return None, code
        src = ''.join(self.buffer)
        try:
            code = self.execer.compile(src,
                                       mode='single',
                                       glbs=self.ctx,
                                       locs=None)
            self.reset_buffer()
        except Exception:  # pylint: disable=broad-except
            self.reset_buffer()
            print_exception()
            return src, None
        return src, code

    def cmdloop(self, intro=None):
        """Enters a loop that reads and execute input from user."""
        if intro:
            print(intro)
        auto_suggest = AutoSuggestFromHistory()
        while not builtins.__xonsh_exit__:
            try:
                line = self.singleline(auto_suggest=auto_suggest)
                if not line:
                    self.emptyline()
                else:
                    line = self.precmd(line)
                    self.default(line)
            except KeyboardInterrupt:
                self.reset_buffer()
            except EOFError:
                if builtins.__xonsh_env__.get("IGNOREEOF"):
                    print('Use "exit" to leave the shell.')
                else:
                    break

    def prompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current prompt."""
        p = builtins.__xonsh_env__.get('PROMPT')
        try:
            p = partial_format_prompt(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        self.settitle()
        return toks

    def rprompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current right
        prompt.
        """
        p = builtins.__xonsh_env__.get('RIGHT_PROMPT')
        if len(p) == 0:
            return []
        try:
            p = partial_format_prompt(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        return toks

    def continuation_tokens(self, cli, width):
        """Displays dots in multiline prompt"""
        dots = builtins.__xonsh_env__.get('MULTILINE_PROMPT')
        _width = width - 1
        dots = _width // len(dots) * dots + dots[:_width % len(dots)]
        return [(Token, dots + ' ')]

    def format_color(self, string, **kwargs):
        """Formats a color string using Pygments. This, therefore, returns
        a list of (Token, str) tuples.
        """
        return partial_color_tokenize(string)

    def print_color(self, string, end='\n', **kwargs):
        """Prints a color string using prompt-toolkit color management."""
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        if isinstance(string, str):
            tokens = partial_color_tokenize(string + end)
        else:
            # assume this is a list of (Token, str) tuples and just print
            tokens = string
        proxy_style = PygmentsStyle(xonsh_style_proxy(self.styler))
        print_tokens(tokens, style=proxy_style)

    def color_style_names(self):
        """Returns an iterable of all available style names."""
        return get_all_styles()

    def color_style(self):
        """Returns the current color map."""
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        return self.styler.styles
Esempio n. 14
0
class PromptToolkitShell(BaseShell):
    """The xonsh shell."""
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
        self.key_bindings_manager = KeyBindingManager(
            enable_auto_suggest_bindings=True,
            enable_search=True,
            enable_abort_and_exit_bindings=True,
            enable_vi_mode=Condition(
                lambda cli: builtins.__xonsh_env__.get('VI_MODE')),
            enable_open_in_editor=True)
        load_xonsh_bindings(self.key_bindings_manager)

    def singleline(self,
                   store_in_history=True,
                   auto_suggest=None,
                   enable_history_search=True,
                   multiline=True,
                   **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        env = builtins.__xonsh_env__
        mouse_support = env.get('MOUSE_SUPPORT')
        if store_in_history:
            history = self.history
        else:
            history = None
            enable_history_search = False
        auto_suggest = auto_suggest if env.get('AUTO_SUGGEST') else None
        completions_display = env.get('COMPLETIONS_DISPLAY')
        multicolumn = (completions_display == 'multi')
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        completer = None if completions_display == 'none' else self.pt_completer
        prompt_tokens = self.prompt_tokens(None)
        get_prompt_tokens = lambda cli: prompt_tokens
        rprompt_tokens = self.rprompt_tokens(None)
        get_rprompt_tokens = lambda cli: rprompt_tokens
        with self.prompter:
            line = self.prompter.prompt(
                mouse_support=mouse_support,
                auto_suggest=auto_suggest,
                get_prompt_tokens=get_prompt_tokens,
                get_rprompt_tokens=get_rprompt_tokens,
                style=PygmentsStyle(xonsh_style_proxy(self.styler)),
                completer=completer,
                lexer=PygmentsLexer(XonshLexer),
                multiline=multiline,
                get_continuation_tokens=self.continuation_tokens,
                history=history,
                enable_history_search=enable_history_search,
                reserve_space_for_menu=0,
                key_bindings_registry=self.key_bindings_manager.registry,
                display_completions_in_columns=multicolumn)
        return line

    def push(self, line):
        """Pushes a line onto the buffer and compiles the code in a way that
        enables multiline input.
        """
        code = None
        self.buffer.append(line)
        if self.need_more_lines:
            return None, code
        src = ''.join(self.buffer)
        try:
            code = self.execer.compile(src,
                                       mode='single',
                                       glbs=None,
                                       locs=self.ctx)
            self.reset_buffer()
        except Exception:  # pylint: disable=broad-except
            self.reset_buffer()
            print_exception()
            return src, None
        return src, code

    def cmdloop(self, intro=None):
        """Enters a loop that reads and execute input from user."""
        if intro:
            print(intro)
        auto_suggest = AutoSuggestFromHistory()
        while not builtins.__xonsh_exit__:
            try:
                line = self.singleline(auto_suggest=auto_suggest)
                if not line:
                    self.emptyline()
                else:
                    line = self.precmd(line)
                    self.default(line)
            except KeyboardInterrupt:
                self.reset_buffer()
            except EOFError:
                if builtins.__xonsh_env__.get("IGNOREEOF"):
                    print('Use "exit" to leave the shell.')
                else:
                    break

    def prompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current prompt."""
        p = builtins.__xonsh_env__.get('PROMPT')
        try:
            p = partial_format_prompt(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        self.settitle()
        return toks

    def rprompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current right
        prompt.
        """
        p = builtins.__xonsh_env__.get('RIGHT_PROMPT')
        if len(p) == 0:
            return []
        try:
            p = partial_format_prompt(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        return toks

    def continuation_tokens(self, cli, width):
        """Displays dots in multiline prompt"""
        dots = builtins.__xonsh_env__.get('MULTILINE_PROMPT')
        _width = width - 1
        dots = _width // len(dots) * dots + dots[:_width % len(dots)]
        return [(Token, dots + ' ')]

    def format_color(self, string, **kwargs):
        """Formats a color string using Pygments. This, therefore, returns
        a list of (Token, str) tuples.
        """
        return partial_color_tokenize(string)

    def print_color(self, string, end='\n', **kwargs):
        """Prints a color string using prompt-toolkit color management."""
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        if isinstance(string, str):
            tokens = partial_color_tokenize(string + end)
        else:
            # assume this is a list of (Token, str) tuples and just print
            tokens = string
        proxy_style = PygmentsStyle(xonsh_style_proxy(self.styler))
        print_tokens(tokens, style=proxy_style)

    def color_style_names(self):
        """Returns an iterable of all available style names."""
        return get_all_styles()

    def color_style(self):
        """Returns the current color map."""
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        return self.styler.styles
Esempio n. 15
0
class PromptToolkitShell(BaseShell):
    """The xonsh shell."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        if ON_WINDOWS:
            winutils.enable_virtual_terminal_processing()
        self._first_prompt = True
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx, self)
        key_bindings_manager_args = {
            'enable_auto_suggest_bindings': True,
            'enable_search': True,
            'enable_abort_and_exit_bindings': True,
            }
        self.key_bindings_manager = KeyBindingManager(**key_bindings_manager_args)
        load_xonsh_bindings(self.key_bindings_manager)
        # This assumes that PromptToolkitShell is a singleton
        events.on_ptk_create.fire(
            prompter=self.prompter,
            history=self.history,
            completer=self.pt_completer,
            bindings=self.key_bindings_manager,
        )

    def singleline(self, store_in_history=True, auto_suggest=None,
                   enable_history_search=True, multiline=True, **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        events.on_pre_prompt.fire()
        env = builtins.__xonsh_env__
        mouse_support = env.get('MOUSE_SUPPORT')
        if store_in_history:
            history = self.history
        else:
            history = None
            enable_history_search = False
        auto_suggest = auto_suggest if env.get('AUTO_SUGGEST') else None
        completions_display = env.get('COMPLETIONS_DISPLAY')
        multicolumn = (completions_display == 'multi')
        complete_while_typing = env.get('UPDATE_COMPLETIONS_ON_KEYPRESS')
        if complete_while_typing:
            # PTK requires history search to be none when completing while typing
            enable_history_search = False
        if HAS_PYGMENTS:
            self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        completer = None if completions_display == 'none' else self.pt_completer
        if not env.get('UPDATE_PROMPT_ON_KEYPRESS'):
            prompt_tokens_cached = self.prompt_tokens(None)
            get_prompt_tokens = lambda cli: prompt_tokens_cached
            rprompt_tokens_cached = self.rprompt_tokens(None)
            get_rprompt_tokens = lambda cli: rprompt_tokens_cached
            bottom_toolbar_tokens_cached = self.bottom_toolbar_tokens(None)
            get_bottom_toolbar_tokens = lambda cli: bottom_toolbar_tokens_cached
        else:
            get_prompt_tokens = self.prompt_tokens
            get_rprompt_tokens = self.rprompt_tokens
            get_bottom_toolbar_tokens = self.bottom_toolbar_tokens

        with self.prompter:
            prompt_args = {
                'mouse_support': mouse_support,
                'auto_suggest': auto_suggest,
                'get_prompt_tokens': get_prompt_tokens,
                'get_rprompt_tokens': get_rprompt_tokens,
                'get_bottom_toolbar_tokens': get_bottom_toolbar_tokens,
                'completer': completer,
                'multiline': multiline,
                'get_continuation_tokens': self.continuation_tokens,
                'history': history,
                'enable_history_search': enable_history_search,
                'reserve_space_for_menu': 0,
                'key_bindings_registry': self.key_bindings_manager.registry,
                'display_completions_in_columns': multicolumn,
                'complete_while_typing': complete_while_typing,
            }
            if builtins.__xonsh_env__.get('COLOR_INPUT'):
                if HAS_PYGMENTS:
                    prompt_args['lexer'] = PygmentsLexer(pyghooks.XonshLexer)
                    prompt_args['style'] = PygmentsStyle(pyghooks.xonsh_style_proxy(self.styler))
                else:
                    prompt_args['style'] = style_from_dict(DEFAULT_STYLE_DICT)
            line = self.prompter.prompt(**prompt_args)
            events.on_post_prompt.fire()
        return line

    def _push(self, line):
        """Pushes a line onto the buffer and compiles the code in a way that
        enables multiline input.
        """
        code = None
        self.buffer.append(line)
        if self.need_more_lines:
            return None, code
        src = ''.join(self.buffer)
        src = transform_command(src)
        try:
            code = self.execer.compile(src,
                                       mode='single',
                                       glbs=self.ctx,
                                       locs=None)
            self.reset_buffer()
        except Exception:  # pylint: disable=broad-except
            self.reset_buffer()
            print_exception()
            return src, None
        return src, code

    def cmdloop(self, intro=None):
        """Enters a loop that reads and execute input from user."""
        if intro:
            print(intro)
        auto_suggest = AutoSuggestFromHistory()
        self.push = self._push
        while not builtins.__xonsh_exit__:
            try:
                line = self.singleline(auto_suggest=auto_suggest)
                if not line:
                    self.emptyline()
                else:
                    line = self.precmd(line)
                    self.default(line)
            except (KeyboardInterrupt, SystemExit):
                self.reset_buffer()
            except EOFError:
                if builtins.__xonsh_env__.get("IGNOREEOF"):
                    print('Use "exit" to leave the shell.', file=sys.stderr)
                else:
                    break

    def prompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current prompt."""
        p = builtins.__xonsh_env__.get('PROMPT')
        try:
            p = self.prompt_formatter(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        if self._first_prompt:
            carriage_return()
            self._first_prompt = False
        self.settitle()
        return toks

    def rprompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current right
        prompt.
        """
        p = builtins.__xonsh_env__.get('RIGHT_PROMPT')
        # self.prompt_formatter does handle empty strings properly,
        # but this avoids descending into it in the common case of
        # $RIGHT_PROMPT == ''.
        if isinstance(p, str) and len(p) == 0:
            return []
        try:
            p = self.prompt_formatter(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        return toks

    def bottom_toolbar_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current bottom
        toolbar.
        """
        p = builtins.__xonsh_env__.get('BOTTOM_TOOLBAR')
        # self.prompt_formatter does handle empty strings properly,
        # but this avoids descending into it in the common case of
        # $TOOLBAR == ''.
        if isinstance(p, str) and len(p) == 0:
            return []
        try:
            p = self.prompt_formatter(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        return toks

    def continuation_tokens(self, cli, width):
        """Displays dots in multiline prompt"""
        width = width - 1
        dots = builtins.__xonsh_env__.get('MULTILINE_PROMPT')
        dots = dots() if callable(dots) else dots
        if dots is None:
            return [(Token, ' '*(width + 1))]
        basetoks = self.format_color(dots)
        baselen = sum(len(t[1]) for t in basetoks)
        if baselen == 0:
            return [(Token, ' '*(width + 1))]
        toks = basetoks * (width // baselen)
        n = width % baselen
        count = 0
        for tok in basetoks:
            slen = len(tok[1])
            newcount = slen + count
            if slen == 0:
                continue
            elif newcount <= n:
                toks.append(tok)
            else:
                toks.append((tok[0], tok[1][:n-count]))
            count = newcount
            if n <= count:
                break
        toks.append((Token, ' '))  # final space
        return toks

    def format_color(self, string, hide=False, force_string=False, **kwargs):
        """Formats a color string using Pygments. This, therefore, returns
        a list of (Token, str) tuples. If force_string is set to true, though,
        this will return a color formatted string.
        """
        tokens = partial_color_tokenize(string)
        if force_string and HAS_PYGMENTS:
            env = builtins.__xonsh_env__
            self.styler.style_name = env.get('XONSH_COLOR_STYLE')
            proxy_style = pyghooks.xonsh_style_proxy(self.styler)
            formatter = pyghooks.XonshTerminal256Formatter(style=proxy_style)
            s = pygments.format(tokens, formatter)
            return s
        elif force_string:
            print("To force colorization of string, install Pygments")
            return tokens
        else:
            return tokens

    def print_color(self, string, end='\n', **kwargs):
        """Prints a color string using prompt-toolkit color management."""
        if isinstance(string, str):
            tokens = partial_color_tokenize(string + end)
        else:
            # assume this is a list of (Token, str) tuples and just print
            tokens = string
        if HAS_PYGMENTS:
            env = builtins.__xonsh_env__
            self.styler.style_name = env.get('XONSH_COLOR_STYLE')
            proxy_style = PygmentsStyle(pyghooks.xonsh_style_proxy(self.styler))
        else:
            proxy_style = style_from_dict(DEFAULT_STYLE_DICT)
        print_tokens(tokens, style=proxy_style)

    def color_style_names(self):
        """Returns an iterable of all available style names."""
        if not HAS_PYGMENTS:
            return ['For other xonsh styles, please install pygments']
        return pygments.styles.get_all_styles()

    def color_style(self):
        """Returns the current color map."""
        if not HAS_PYGMENTS:
            return DEFAULT_STYLE_DICT
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get('XONSH_COLOR_STYLE')
        return self.styler.styles

    def restore_tty_sanity(self):
        """An interface for resetting the TTY stdin mode. This is highly
Esempio n. 16
0
class PromptToolkitShell(BaseShell):
    """The xonsh shell."""
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        if ON_WINDOWS:
            winutils.enable_virtual_terminal_processing()
        self._first_prompt = True
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx,
                                                   self)
        key_bindings_manager_args = {
            "enable_auto_suggest_bindings": True,
            "enable_search": True,
            "enable_abort_and_exit_bindings": True,
        }
        self.key_bindings_manager = KeyBindingManager(
            **key_bindings_manager_args)
        load_xonsh_bindings(self.key_bindings_manager)
        # This assumes that PromptToolkitShell is a singleton
        events.on_ptk_create.fire(
            prompter=self.prompter,
            history=self.history,
            completer=self.pt_completer,
            bindings=self.key_bindings_manager,
        )

    def singleline(self,
                   store_in_history=True,
                   auto_suggest=None,
                   enable_history_search=True,
                   multiline=True,
                   **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        events.on_pre_prompt.fire()
        env = builtins.__xonsh_env__
        mouse_support = env.get("MOUSE_SUPPORT")
        if store_in_history:
            history = self.history
        else:
            history = None
            enable_history_search = False
        auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None
        completions_display = env.get("COMPLETIONS_DISPLAY")
        multicolumn = completions_display == "multi"
        complete_while_typing = env.get("UPDATE_COMPLETIONS_ON_KEYPRESS")
        if complete_while_typing:
            # PTK requires history search to be none when completing while typing
            enable_history_search = False
        if HAS_PYGMENTS:
            self.styler.style_name = env.get("XONSH_COLOR_STYLE")
        completer = None if completions_display == "none" else self.pt_completer
        if not env.get("UPDATE_PROMPT_ON_KEYPRESS"):
            prompt_tokens_cached = self.prompt_tokens(None)
            get_prompt_tokens = lambda cli: prompt_tokens_cached
            rprompt_tokens_cached = self.rprompt_tokens(None)
            get_rprompt_tokens = lambda cli: rprompt_tokens_cached
            bottom_toolbar_tokens_cached = self.bottom_toolbar_tokens(None)
            get_bottom_toolbar_tokens = lambda cli: bottom_toolbar_tokens_cached
        else:
            get_prompt_tokens = self.prompt_tokens
            get_rprompt_tokens = self.rprompt_tokens
            get_bottom_toolbar_tokens = self.bottom_toolbar_tokens

        with self.prompter:
            prompt_args = {
                "mouse_support": mouse_support,
                "auto_suggest": auto_suggest,
                "get_prompt_tokens": get_prompt_tokens,
                "get_rprompt_tokens": get_rprompt_tokens,
                "get_bottom_toolbar_tokens": get_bottom_toolbar_tokens,
                "completer": completer,
                "multiline": multiline,
                "get_continuation_tokens": self.continuation_tokens,
                "history": history,
                "enable_history_search": enable_history_search,
                "reserve_space_for_menu": 0,
                "key_bindings_registry": self.key_bindings_manager.registry,
                "display_completions_in_columns": multicolumn,
                "complete_while_typing": complete_while_typing,
            }
            if builtins.__xonsh_env__.get("COLOR_INPUT"):
                if HAS_PYGMENTS:
                    prompt_args["lexer"] = PygmentsLexer(pyghooks.XonshLexer)
                    prompt_args["style"] = PygmentsStyle(
                        pyghooks.xonsh_style_proxy(self.styler))
                else:
                    prompt_args["style"] = style_from_dict(DEFAULT_STYLE_DICT)
            line = self.prompter.prompt(**prompt_args)
            events.on_post_prompt.fire()
        return line

    def _push(self, line):
        """Pushes a line onto the buffer and compiles the code in a way that
        enables multiline input.
        """
        code = None
        self.buffer.append(line)
        if self.need_more_lines:
            return None, code
        src = "".join(self.buffer)
        src = transform_command(src)
        try:
            code = self.execer.compile(src,
                                       mode="single",
                                       glbs=self.ctx,
                                       locs=None)
            self.reset_buffer()
        except Exception:  # pylint: disable=broad-except
            self.reset_buffer()
            print_exception()
            return src, None
        return src, code

    def cmdloop(self, intro=None):
        """Enters a loop that reads and execute input from user."""
        if intro:
            print(intro)
        auto_suggest = AutoSuggestFromHistory()
        self.push = self._push
        while not builtins.__xonsh_exit__:
            try:
                line = self.singleline(auto_suggest=auto_suggest)
                if not line:
                    self.emptyline()
                else:
                    line = self.precmd(line)
                    self.default(line)
            except (KeyboardInterrupt, SystemExit):
                self.reset_buffer()
            except EOFError:
                if builtins.__xonsh_env__.get("IGNOREEOF"):
                    print('Use "exit" to leave the shell.', file=sys.stderr)
                else:
                    break

    def prompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current prompt."""
        p = builtins.__xonsh_env__.get("PROMPT")
        try:
            p = self.prompt_formatter(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        if self._first_prompt:
            carriage_return()
            self._first_prompt = False
        self.settitle()
        return toks

    def rprompt_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current right
        prompt.
        """
        p = builtins.__xonsh_env__.get("RIGHT_PROMPT")
        # self.prompt_formatter does handle empty strings properly,
        # but this avoids descending into it in the common case of
        # $RIGHT_PROMPT == ''.
        if isinstance(p, str) and len(p) == 0:
            return []
        try:
            p = self.prompt_formatter(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        return toks

    def bottom_toolbar_tokens(self, cli):
        """Returns a list of (token, str) tuples for the current bottom
        toolbar.
        """
        p = builtins.__xonsh_env__.get("BOTTOM_TOOLBAR")
        # self.prompt_formatter does handle empty strings properly,
        # but this avoids descending into it in the common case of
        # $TOOLBAR == ''.
        if isinstance(p, str) and len(p) == 0:
            return []
        try:
            p = self.prompt_formatter(p)
        except Exception:  # pylint: disable=broad-except
            print_exception()
        toks = partial_color_tokenize(p)
        return toks

    def continuation_tokens(self, cli, width):
        """Displays dots in multiline prompt"""
        width = width - 1
        dots = builtins.__xonsh_env__.get("MULTILINE_PROMPT")
        dots = dots() if callable(dots) else dots
        if dots is None:
            return [(Token, " " * (width + 1))]
        basetoks = self.format_color(dots)
        baselen = sum(len(t[1]) for t in basetoks)
        if baselen == 0:
            return [(Token, " " * (width + 1))]
        toks = basetoks * (width // baselen)
        n = width % baselen
        count = 0
        for tok in basetoks:
            slen = len(tok[1])
            newcount = slen + count
            if slen == 0:
                continue
            elif newcount <= n:
                toks.append(tok)
            else:
                toks.append((tok[0], tok[1][:n - count]))
            count = newcount
            if n <= count:
                break
        toks.append((Token, " "))  # final space
        return toks

    def format_color(self, string, hide=False, force_string=False, **kwargs):
        """Formats a color string using Pygments. This, therefore, returns
        a list of (Token, str) tuples. If force_string is set to true, though,
        this will return a color formatted string.
        """
        tokens = partial_color_tokenize(string)
        if force_string and HAS_PYGMENTS:
            env = builtins.__xonsh_env__
            self.styler.style_name = env.get("XONSH_COLOR_STYLE")
            proxy_style = pyghooks.xonsh_style_proxy(self.styler)
            formatter = pyghooks.XonshTerminal256Formatter(style=proxy_style)
            s = pygments.format(tokens, formatter)
            return s
        elif force_string:
            print("To force colorization of string, install Pygments")
            return tokens
        else:
            return tokens

    def print_color(self, string, end="\n", **kwargs):
        """Prints a color string using prompt-toolkit color management."""
        if isinstance(string, str):
            tokens = partial_color_tokenize(string + end)
        else:
            # assume this is a list of (Token, str) tuples and just print
            tokens = string
        if HAS_PYGMENTS:
            env = builtins.__xonsh_env__
            self.styler.style_name = env.get("XONSH_COLOR_STYLE")
            proxy_style = PygmentsStyle(pyghooks.xonsh_style_proxy(
                self.styler))
        else:
            proxy_style = style_from_dict(DEFAULT_STYLE_DICT)
        print_tokens(tokens, style=proxy_style)

    def color_style_names(self):
        """Returns an iterable of all available style names."""
        if not HAS_PYGMENTS:
            return ["For other xonsh styles, please install pygments"]
        return get_all_styles()

    def color_style(self):
        """Returns the current color map."""
        if not HAS_PYGMENTS:
            return DEFAULT_STYLE_DICT
        env = builtins.__xonsh_env__
        self.styler.style_name = env.get("XONSH_COLOR_STYLE")
        return self.styler.styles

    def restore_tty_sanity(self):
        """An interface for resetting the TTY stdin mode. This is highly
Esempio n. 17
0
File: shell.py Progetto: minrk/xonsh
class PromptToolkitShell(BaseShell):
    """The xonsh shell."""

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prompter = Prompter()
        self.history = PromptToolkitHistory()
        self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx)
        self.key_bindings_manager = KeyBindingManager(
            enable_auto_suggest_bindings=True,
            enable_search=True,
            enable_abort_and_exit_bindings=True,
            enable_vi_mode=Condition(lambda cli: builtins.__xonsh_env__.get("VI_MODE")),
            enable_open_in_editor=True,
        )
        load_xonsh_bindings(self.key_bindings_manager)

    def singleline(
        self, store_in_history=True, auto_suggest=None, enable_history_search=True, multiline=True, **kwargs
    ):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        token_func, style_cls = self._get_prompt_tokens_and_style()
        env = builtins.__xonsh_env__
        mouse_support = env.get("MOUSE_SUPPORT")
        if store_in_history:
            history = self.history
        else:
            history = None
            enable_history_search = False
        auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None
        completions_display = env.get("COMPLETIONS_DISPLAY")
        multicolumn = completions_display == "multi"
        completer = None if completions_display == "none" else self.pt_completer
        with self.prompter:
            line = self.prompter.prompt(
                mouse_support=mouse_support,
                auto_suggest=auto_suggest,
                get_prompt_tokens=token_func,
                style=style_cls,
                completer=completer,
                lexer=PygmentsLexer(XonshLexer),
                multiline=multiline,
                history=history,
                enable_history_search=enable_history_search,
                reserve_space_for_menu=0,
                key_bindings_registry=self.key_bindings_manager.registry,
                display_completions_in_columns=multicolumn,
            )
        return line

    def push(self, line):
        """Pushes a line onto the buffer and compiles the code in a way that
        enables multiline input.
        """
        code = None
        self.buffer.append(line)
        if self.need_more_lines:
            return None, code
        src = "".join(self.buffer)
        try:
            code = self.execer.compile(src, mode="single", glbs=None, locs=self.ctx)
            self.reset_buffer()
        except Exception:  # pylint: disable=broad-except
            self.reset_buffer()
            print_exception()
            return src, None
        return src, code

    def cmdloop(self, intro=None):
        """Enters a loop that reads and execute input from user."""
        if intro:
            print(intro)
        auto_suggest = AutoSuggestFromHistory()
        while not builtins.__xonsh_exit__:
            try:
                line = self.singleline(auto_suggest=auto_suggest)
                if not line:
                    self.emptyline()
                else:
                    line = self.precmd(line)
                    self.default(line)
            except KeyboardInterrupt:
                self.reset_buffer()
            except EOFError:
                if builtins.__xonsh_env__.get("IGNOREEOF"):
                    print('Use "exit" to leave the shell.')
                else:
                    break

    def _get_prompt_tokens_and_style(self):
        """Returns function to pass as prompt to prompt_toolkit."""
        token_names, cstyles, strings = format_prompt_for_prompt_toolkit(self.prompt)
        tokens = [getattr(Token, n) for n in token_names]

        def get_tokens(cli):
            return list(zip(tokens, strings))

        custom_style = _xonsh_style(tokens, cstyles)

        return get_tokens, custom_style