Exemplo n.º 1
0
    def handle_binding(name):
        try:
            binding = get_by_name(name)
        except KeyError:
            print_warning(
                f"Failed to disable clipboard for ptk action {name!r}")
            return

        if getattr(binding, "xonsh_disabled_clipboard", False):
            # binding's clipboard has already been disabled
            return

        binding.xonsh_disabled_clipboard = True
        original_handler = binding.handler

        # this needs to be defined inside a function so that ``binding`` will be the correct one
        @wraps(original_handler)
        def wrapped_handler(event):
            app = event.app
            prev = app.clipboard
            app.clipboard = dummy_clipboard
            try:
                return original_handler(event)
            finally:
                app.clipboard = prev

        binding.handler = wrapped_handler
Exemplo n.º 2
0
def warn_deprecated_no_color():
    """Show a warning once if NO_COLOR was used instead of RESET."""
    global _NO_COLOR_WARNING_SHOWN
    if not _NO_COLOR_WARNING_SHOWN:
        print_warning(
            "NO_COLOR is deprecated and should be replaced with RESET.")
        _NO_COLOR_WARNING_SHOWN = True
Exemplo n.º 3
0
def install_import_hooks(execer=ARG_NOT_PRESENT):
    """
    Install Xonsh import hooks in ``sys.meta_path`` in order for ``.xsh`` files
    to be importable and import events to be fired.

    Can safely be called many times, will be no-op if xonsh import hooks are
    already present.
    """
    if execer is ARG_NOT_PRESENT:
        print_warning("No execer was passed to install_import_hooks. "
                      "This will become an error in future.")
        execer = XSH.execer
        if execer is None:
            execer = Execer()
            XSH.load(execer=execer)

    found_imp = found_event = False
    for hook in sys.meta_path:
        if isinstance(hook, XonshImportHook):
            found_imp = True
        elif isinstance(hook, XonshImportEventHook):
            found_event = True
    if not found_imp:
        sys.meta_path.append(XonshImportHook(execer))
    if not found_event:
        sys.meta_path.insert(0, XonshImportEventHook())
Exemplo n.º 4
0
    def get_prompt_style(self):
        env = XSH.env

        style_overrides_env = env.get("PTK_STYLE_OVERRIDES", {}).copy()
        if (
            len(style_overrides_env) > 0
            and not self._overrides_deprecation_warning_shown
        ):
            print_warning(
                "$PTK_STYLE_OVERRIDES is deprecated, use $XONSH_STYLE_OVERRIDES instead!"
            )
            self._overrides_deprecation_warning_shown = True
        style_overrides_env.update(env.get("XONSH_STYLE_OVERRIDES", {}))

        if HAS_PYGMENTS:
            style = _style_from_pygments_cls(pyghooks.xonsh_style_proxy(self.styler))
            if len(self.styler.non_pygments_rules) > 0:
                try:
                    style = merge_styles(
                        [
                            style,
                            _style_from_pygments_dict(self.styler.non_pygments_rules),
                        ]
                    )
                except (AttributeError, TypeError, ValueError) as style_exception:
                    print_warning(
                        f"Error applying style override!\n{style_exception}\n"
                    )

        else:
            style = _style_from_pygments_dict(DEFAULT_STYLE_DICT)

        if len(style_overrides_env) > 0:
            try:
                style = merge_styles(
                    [style, _style_from_pygments_dict(style_overrides_env)]
                )
            except (AttributeError, TypeError, ValueError) as style_exception:
                print_warning(f"Error applying style override!\n{style_exception}\n")
        return style
Exemplo n.º 5
0
def _print_proc_warning(msg: str):
    global _WARNINGS_PRINTED
    if msg not in _WARNINGS_PRINTED:
        print_warning(msg)
        _WARNINGS_PRINTED.add(msg)
Exemplo n.º 6
0
    def singleline(self,
                   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_format.fire()
        env = builtins.__xonsh__.env
        mouse_support = env.get("MOUSE_SUPPORT")
        auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None
        refresh_interval = env.get("PROMPT_REFRESH_INTERVAL")
        refresh_interval = refresh_interval if refresh_interval > 0 else None
        complete_in_thread = env.get("COMPLETION_IN_THREAD")
        completions_display = env.get("COMPLETIONS_DISPLAY")
        complete_style = self.completion_displays_to_styles[
            completions_display]

        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

        events.on_timingprobe.fire(name="on_pre_prompt_tokenize")
        get_bottom_toolbar_tokens = self.bottom_toolbar_tokens
        if env.get("UPDATE_PROMPT_ON_KEYPRESS"):
            get_prompt_tokens = self.prompt_tokens
            get_rprompt_tokens = self.rprompt_tokens
        else:
            get_prompt_tokens = self.prompt_tokens()
            get_rprompt_tokens = self.rprompt_tokens()
            if get_bottom_toolbar_tokens:
                get_bottom_toolbar_tokens = get_bottom_toolbar_tokens()
        events.on_timingprobe.fire(name="on_post_prompt_tokenize")

        if env.get("VI_MODE"):
            editing_mode = EditingMode.VI
        else:
            editing_mode = EditingMode.EMACS

        if env.get("XONSH_HISTORY_MATCH_ANYWHERE"):
            self.prompter.default_buffer._history_matches = MethodType(
                _cust_history_matches, self.prompter.default_buffer)
        elif (self.prompter.default_buffer._history_matches
              is not self._history_matches_orig):
            self.prompter.default_buffer._history_matches = self._history_matches_orig

        prompt_args = {
            "mouse_support": mouse_support,
            "auto_suggest": auto_suggest,
            "message": get_prompt_tokens,
            "rprompt": get_rprompt_tokens,
            "bottom_toolbar": get_bottom_toolbar_tokens,
            "completer": completer,
            "multiline": multiline,
            "editing_mode": editing_mode,
            "prompt_continuation": self.continuation_tokens,
            "enable_history_search": enable_history_search,
            "reserve_space_for_menu": 0,
            "key_bindings": self.key_bindings,
            "complete_style": complete_style,
            "complete_while_typing": complete_while_typing,
            "include_default_pygments_style": False,
            "refresh_interval": refresh_interval,
            "complete_in_thread": complete_in_thread,
        }

        if env.get("COLOR_INPUT"):
            events.on_timingprobe.fire(name="on_pre_prompt_style")
            style_overrides_env = env.get("PTK_STYLE_OVERRIDES", {}).copy()
            if (len(style_overrides_env) > 0
                    and not self._overrides_deprecation_warning_shown):
                print_warning(
                    "$PTK_STYLE_OVERRIDES is deprecated, use $XONSH_STYLE_OVERRIDES instead!"
                )
                self._overrides_deprecation_warning_shown = True
            style_overrides_env.update(env.get("XONSH_STYLE_OVERRIDES", {}))

            if HAS_PYGMENTS:
                prompt_args["lexer"] = PygmentsLexer(pyghooks.XonshLexer)
                style = _style_from_pygments_cls(
                    pyghooks.xonsh_style_proxy(self.styler))
                if len(self.styler.non_pygments_rules) > 0:
                    try:
                        style = merge_styles([
                            style,
                            _style_from_pygments_dict(
                                self.styler.non_pygments_rules),
                        ])
                    except (AttributeError, TypeError,
                            ValueError) as style_exception:
                        print_warning(
                            f"Error applying style override!\n{style_exception}\n"
                        )

            else:
                style = _style_from_pygments_dict(DEFAULT_STYLE_DICT)

            if len(style_overrides_env) > 0:
                try:
                    style = merge_styles([
                        style,
                        _style_from_pygments_dict(style_overrides_env)
                    ])
                except (AttributeError, TypeError,
                        ValueError) as style_exception:
                    print_warning(
                        f"Error applying style override!\n{style_exception}\n")

            prompt_args["style"] = style
            events.on_timingprobe.fire(name="on_post_prompt_style")

        if env["ENABLE_ASYNC_PROMPT"]:
            # once the prompt is done, update it in background as each future is completed
            prompt_args["pre_run"] = self.prompt_formatter.start_update

        events.on_pre_prompt.fire()
        line = self.prompter.prompt(**prompt_args)
        events.on_post_prompt.fire()
        return line