Beispiel #1
0
 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)
     else:
         # assume this is a list of (Token, str) tuples and just print
         tokens = string
     tokens = PygmentsTokens(tokens)
     env = XSH.env
     style_overrides_env = env.get("XONSH_STYLE_OVERRIDES", {})
     if HAS_PYGMENTS:
         self.styler.style_name = env.get("XONSH_COLOR_STYLE")
         self.styler.override(style_overrides_env)
         proxy_style = _style_from_pygments_cls(
             pyghooks.xonsh_style_proxy(self.styler))
     else:
         proxy_style = merge_styles([
             _style_from_pygments_dict(DEFAULT_STYLE_DICT),
             _style_from_pygments_dict(style_overrides_env),
         ])
     ptk_print(
         tokens,
         style=proxy_style,
         end=end,
         include_default_pygments_style=False,
         **kwargs,
     )
Beispiel #2
0
    def _format_fields_tokens(self, fields, title_width=0):
        """Formats a list of fields for display using color tokens from
        pygments.

        Parameters
        ----------
        fields : list
          A list of 2-tuples: (field_title, field_content)
        title_width : int
          How many characters to pad titles to. Default to longest title.
        """
        out = []
        if title_width == 0:
            title_width = max(len(title) + 2 for title, _ in fields)
        for title, content in fields:
            title_len = len(title)
            title = "{BOLD_RED}" + title + ":{NO_COLOR}"
            if not isinstance(content, str) or len(content.splitlines()) > 1:
                title += "\n"
            else:
                title += " ".ljust(title_width - title_len)
            out += partial_color_tokenize(title)
            if isinstance(content, str):
                out[-1] = (out[-1][0], out[-1][1] + content + "\n")
            else:
                out += content
                out[-1] = (out[-1][0], out[-1][1] + "\n")
        out[-1] = (out[-1][0], out[-1][1] + "\n")
        return out
Beispiel #3
0
    def _format_fields_tokens(self, fields, title_width=0):
        """Formats a list of fields for display using color tokens from
        pygments.

        Parameters
        ----------
        fields : list
          A list of 2-tuples: (field_title, field_content)
        title_width : int
          How many characters to pad titles to. Default to longest title.
        """
        out = []
        if title_width == 0:
            title_width = max(len(title) + 2 for title, _ in fields)
        for title, content in fields:
            title_len = len(title)
            title = "{BOLD_RED}" + title + ":{RESET}"
            if not isinstance(content, str) or len(content.splitlines()) > 1:
                title += "\n"
            else:
                title += " ".ljust(title_width - title_len)
            out += partial_color_tokenize(title)
            if isinstance(content, str):
                out[-1] = (out[-1][0], out[-1][1] + content + "\n")
            else:
                out += content
                out[-1] = (out[-1][0], out[-1][1] + "\n")
        out[-1] = (out[-1][0], out[-1][1] + "\n")
        return out
Beispiel #4
0
    def _get_prompt_tokens(self, env_name: str, prompt_name: str, **kwargs):
        env = builtins.__xonsh__.env  # type:ignore
        p = env.get(env_name)

        if not p and "default" in kwargs:
            return kwargs.pop("default")

        try:
            p = self.prompt_formatter(template=p,
                                      threaded=env["ENABLE_ASYNC_PROMPT"],
                                      prompt_name=prompt_name)
        except Exception:  # pylint: disable=broad-except
            print_exception()

        p, osc_tokens = remove_ansi_osc(p)

        if kwargs.get("handle_osc_tokens"):
            # handle OSC tokens
            for osc in osc_tokens:
                if osc[2:4] == "0;":
                    env["TITLE"] = osc[4:-1]
                else:
                    print(osc, file=sys.__stdout__, flush=True)

        toks = partial_color_tokenize(p)

        return tokenize_ansi(PygmentsTokens(toks))
Beispiel #5
0
 def bottom_toolbar_tokens(self):
     """Returns a list of (token, str) tuples for the current bottom
     toolbar.
     """
     p = builtins.__xonsh__.env.get("BOTTOM_TOOLBAR")
     if not p:
         return
     try:
         p = self.prompt_formatter(p)
     except Exception:  # pylint: disable=broad-except
         print_exception()
     toks = partial_color_tokenize(p)
     return PygmentsTokens(toks)
Beispiel #6
0
 def bottom_toolbar_tokens(self):
     """Returns a list of (token, str) tuples for the current bottom
     toolbar.
     """
     p = builtins.__xonsh__.env.get("BOTTOM_TOOLBAR")
     if not p:
         return
     try:
         p = self.prompt_formatter(p)
     except Exception:  # pylint: disable=broad-except
         print_exception()
     toks = partial_color_tokenize(p)
     return PygmentsTokens(toks)
Beispiel #7
0
 def prompt_tokens(self):
     """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 PygmentsTokens(toks)
Beispiel #8
0
 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
Beispiel #9
0
 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)
Beispiel #10
0
 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)
Beispiel #11
0
 def rprompt_tokens(self):
     """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 PygmentsTokens(toks)
Beispiel #12
0
 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
Beispiel #13
0
 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
Beispiel #14
0
 def rprompt_tokens(self):
     """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 PygmentsTokens(toks)
Beispiel #15
0
    def _get_prompt_tokens(self, env_name: str, prompt_name: str, **kwargs):
        env = XSH.env  # type:ignore
        p = env.get(env_name)

        if not p and "default" in kwargs:
            return kwargs.pop("default")

        try:
            p = self.prompt_formatter(template=p,
                                      threaded=env["ENABLE_ASYNC_PROMPT"],
                                      prompt_name=prompt_name)
        except Exception:  # pylint: disable=broad-except
            print_exception()

        toks = partial_color_tokenize(p)

        return tokenize_ansi(PygmentsTokens(toks))
Beispiel #16
0
 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
Beispiel #17
0
 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
Beispiel #18
0
 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)
     else:
         # assume this is a list of (Token, str) tuples and just print
         tokens = string
     tokens = PygmentsTokens(tokens)
     if HAS_PYGMENTS:
         env = builtins.__xonsh__.env
         self.styler.style_name = env.get("XONSH_COLOR_STYLE")
         proxy_style = style_from_pygments_cls(
             pyghooks.xonsh_style_proxy(self.styler))
     else:
         proxy_style = style_from_pygments_dict(DEFAULT_STYLE_DICT)
     ptk_print(tokens,
               style=proxy_style,
               end=end,
               include_default_pygments_style=False)
Beispiel #19
0
 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)
     else:
         # assume this is a list of (Token, str) tuples and just print
         tokens = string
     tokens = PygmentsTokens(tokens)
     if HAS_PYGMENTS:
         env = builtins.__xonsh__.env
         self.styler.style_name = env.get("XONSH_COLOR_STYLE")
         proxy_style = style_from_pygments_cls(
             pyghooks.xonsh_style_proxy(self.styler)
         )
     else:
         proxy_style = style_from_pygments_dict(DEFAULT_STYLE_DICT)
     ptk_print(
         tokens, style=proxy_style, end=end, include_default_pygments_style=False
     )
Beispiel #20
0
def html_format(s, style="default"):
    buf = io.StringIO()
    proxy_style = xonsh_style_proxy(XonshStyle(style))
    # make sure we have a foreground color
    fgcolor = proxy_style._styles[Token.Text][0]
    if not fgcolor:
        fgcolor = invert_color(proxy_style.background_color[1:].strip("#"))
    # need to generate stream before creating formatter so that all tokens actually exist
    if isinstance(s, str):
        token_stream = partial_color_tokenize(s)
    else:
        token_stream = s
    formatter = XonshHtmlFormatter(
        wrapcode=True,
        noclasses=True,
        style=proxy_style,
        prestyles="margin: 0em; padding: 0.5em 0.1em; color: #" + fgcolor,
        cssstyles="border-style: solid; border-radius: 5px",
    )
    formatter.format(token_stream, buf)
    return buf.getvalue()
Beispiel #21
0
    def prompt_tokens(self):
        """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()

        p, osc_tokens = remove_ansi_osc(p)

        toks = partial_color_tokenize(p)
        if self._first_prompt:
            carriage_return()
            self._first_prompt = False

        # handle OSC tokens
        for osc in osc_tokens:
            if osc[2:4] == "0;":
                builtins.__xonsh__.env["TITLE"] = osc[4:-1]
            else:
                print(osc, file=sys.__stdout__, flush=True)

        self.settitle()
        return tokenize_ansi(PygmentsTokens(toks))
Beispiel #22
0
 def _invalidate():
     new_prompt = "".join(self.tokens)
     formatted_tokens = tokenize_ansi(
         PygmentsTokens(partial_color_tokenize(new_prompt)))
     setattr(self.session, self.name, formatted_tokens)
     self.session.app.invalidate()