1# -*- coding: utf-8 -*-
2"""Hooks for pygments syntax highlighting."""
3import os
4import re
5import sys
6import string
7import builtins
8from collections import ChainMap
9from collections.abc import MutableMapping
10
11from pygments.lexer import inherit, bygroups, include
12from pygments.lexers.agile import PythonLexer
13from pygments.token import (
14    Keyword,
15    Name,
16    Comment,
17    String,
18    Error,
19    Number,
20    Operator,
21    Generic,
22    Whitespace,
23    Token,
24    Punctuation,
25    Text,
26)
27from pygments.style import Style
28import pygments.util
29
30from xonsh.commands_cache import CommandsCache
31from xonsh.lazyasd import LazyObject, LazyDict, lazyobject
32from xonsh.tools import (
33    ON_WINDOWS,
34    intensify_colors_for_cmd_exe,
35    ansicolors_to_ptk1_names,
36    ANSICOLOR_NAMES_MAP,
37    PTK_NEW_OLD_COLOR_MAP,
38    hardcode_colors_for_win10,
39)
40
41from xonsh.color_tools import (
42    RE_BACKGROUND,
43    BASE_XONSH_COLORS,
44    make_palette,
45    find_closest_color,
46)
47from xonsh.style_tools import norm_name
48from xonsh.lazyimps import terminal256
49from xonsh.platform import (
50    os_environ,
51    win_ansi_support,
52    ptk_version_info,
53    pygments_version_info,
54)
55
56from xonsh.pygments_cache import get_style_by_name
57
58
59def _command_is_valid(cmd):
60    try:
61        cmd_abspath = os.path.abspath(os.path.expanduser(cmd))
62    except (FileNotFoundError, OSError):
63        return False
64    return cmd in builtins.__xonsh_commands_cache__ or (
65        os.path.isfile(cmd_abspath) and os.access(cmd_abspath, os.X_OK)
66    )
67
68
69def _command_is_autocd(cmd):
70    if not builtins.__xonsh_env__.get("AUTO_CD", False):
71        return False
72    try:
73        cmd_abspath = os.path.abspath(os.path.expanduser(cmd))
74    except (FileNotFoundError, OSError):
75        return False
76    return os.path.isdir(cmd_abspath)
77
78
79def subproc_cmd_callback(_, match):
80    """Yield Builtin token if match contains valid command,
81    otherwise fallback to fallback lexer.
82    """
83    cmd = match.group()
84    yield match.start(), Name.Builtin if _command_is_valid(cmd) else Error, cmd
85
86
87def subproc_arg_callback(_, match):
88    """Check if match contains valid path"""
89    text = match.group()
90    try:
91        ispath = os.path.exists(os.path.expanduser(text))
92    except (FileNotFoundError, OSError):
93        ispath = False
94    yield (match.start(), Name.Constant if ispath else Text, text)
95
96
97COMMAND_TOKEN_RE = r'[^=\s\[\]{}()$"\'`<&|;!]+(?=\s|$|\)|\]|\}|!)'
98
99
100class XonshLexer(PythonLexer):
101    """Xonsh console lexer for pygments."""
102
103    name = "Xonsh lexer"
104    aliases = ["xonsh", "xsh"]
105    filenames = ["*.xsh", "*xonshrc"]
106
107    def __init__(self, *args, **kwargs):
108        # If the lexor is loaded as a pygment plugin, we have to mock
109        # __xonsh_env__ and __xonsh_commands_cache__
110        if not hasattr(builtins, "__xonsh_env__"):
111            setattr(builtins, "__xonsh_env__", {})
112            if ON_WINDOWS:
113                pathext = os_environ.get("PATHEXT", [".EXE", ".BAT", ".CMD"])
114                builtins.__xonsh_env__["PATHEXT"] = pathext.split(os.pathsep)
115        if not hasattr(builtins, "__xonsh_commands_cache__"):
116            setattr(builtins, "__xonsh_commands_cache__", CommandsCache())
117        _ = builtins.__xonsh_commands_cache__.all_commands  # NOQA
118        super().__init__(*args, **kwargs)
119
120    tokens = {
121        "mode_switch_brackets": [
122            (r"(\$)(\{)", bygroups(Keyword, Punctuation), "py_curly_bracket"),
123            (r"(@)(\()", bygroups(Keyword, Punctuation), "py_bracket"),
124            (
125                r"([\!\$])(\()",
126                bygroups(Keyword, Punctuation),
127                ("subproc_bracket", "subproc_start"),
128            ),
129            (
130                r"(@\$)(\()",
131                bygroups(Keyword, Punctuation),
132                ("subproc_bracket", "subproc_start"),
133            ),
134            (
135                r"([\!\$])(\[)",
136                bygroups(Keyword, Punctuation),
137                ("subproc_square_bracket", "subproc_start"),
138            ),
139            (r"(g?)(`)", bygroups(String.Affix, String.Backtick), "backtick_re"),
140        ],
141        "subproc_bracket": [(r"\)", Punctuation, "#pop"), include("subproc")],
142        "subproc_square_bracket": [(r"\]", Punctuation, "#pop"), include("subproc")],
143        "py_bracket": [(r"\)", Punctuation, "#pop"), include("root")],
144        "py_curly_bracket": [(r"\}", Punctuation, "#pop"), include("root")],
145        "backtick_re": [
146            (r"[\.\^\$\*\+\?\[\]\|]", String.Regex),
147            (r"({[0-9]+}|{[0-9]+,[0-9]+})\??", String.Regex),
148            (r"\\([0-9]+|[AbBdDsSwWZabfnrtuUvx\\])", String.Escape),
149            (r"`", String.Backtick, "#pop"),
150            (r"[^`\.\^\$\*\+\?\[\]\|]+", String.Backtick),
151        ],
152        "root": [
153            (r"\?", Keyword),
154            (r"(?<=\w)!", Keyword),
155            (r"\$\w+", Name.Variable),
156            (r"\(", Punctuation, "py_bracket"),
157            (r"\{", Punctuation, "py_curly_bracket"),
158            include("mode_switch_brackets"),
159            inherit,
160        ],
161        "subproc_start": [
162            (r"\s+", Whitespace),
163            (COMMAND_TOKEN_RE, subproc_cmd_callback, "#pop"),
164            (r"", Whitespace, "#pop"),
165        ],
166        "subproc": [
167            include("mode_switch_brackets"),
168            (r"&&|\|\|", Operator, "subproc_start"),
169            (r'"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double),
170            (r"'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single),
171            (r"(?<=\w|\s)!", Keyword, "subproc_macro"),
172            (r"^!", Keyword, "subproc_macro"),
173            (r";", Punctuation, "subproc_start"),
174            (r"&|=", Punctuation),
175            (r"\|", Punctuation, "subproc_start"),
176            (r"\s+", Text),
177            (r'[^=\s\[\]{}()$"\'`<&|;]+', subproc_arg_callback),
178            (r"<", Text),
179            (r"\$\w+", Name.Variable),
180        ],
181        "subproc_macro": [
182            (r"(\s*)([^\n]+)", bygroups(Whitespace, String)),
183            (r"", Whitespace, "#pop"),
184        ],
185    }
186
187    def get_tokens_unprocessed(self, text):
188        """Check first command, then call super.get_tokens_unprocessed
189        with root or subproc state"""
190        start = 0
191        state = ("root",)
192        m = re.match(r"(\s*)({})".format(COMMAND_TOKEN_RE), text)
193        if m is not None:
194            yield m.start(1), Whitespace, m.group(1)
195            cmd = m.group(2)
196            cmd_is_valid = _command_is_valid(cmd)
197            cmd_is_autocd = _command_is_autocd(cmd)
198
199            if cmd_is_valid or cmd_is_autocd:
200                yield (m.start(2), Name.Builtin if cmd_is_valid else Name.Constant, cmd)
201                start = m.end(2)
202                state = ("subproc",)
203
204        for i, t, v in super().get_tokens_unprocessed(text[start:], state):
205            yield i + start, t, v
206
207
208class XonshConsoleLexer(XonshLexer):
209    """Xonsh console lexer for pygments."""
210
211    name = "Xonsh console lexer"
212    aliases = ["xonshcon"]
213    filenames = []
214
215    tokens = {
216        "root": [
217            (r"^(>>>|\.\.\.) ", Generic.Prompt),
218            (r"\n(>>>|\.\.\.)", Generic.Prompt),
219            (r"\n(?![>.][>.][>.] )([^\n]*)", Generic.Output),
220            (r"\n(?![>.][>.][>.] )(.*?)$", Generic.Output),
221            inherit,
222        ]
223    }
224
225
226#
227# Colors and Styles
228#
229
230Color = Token.Color  # alias to new color token namespace
231
232
233def color_by_name(name, fg=None, bg=None):
234    """Converts a color name to a color token, foreground name,
235    and background name.  Will take into consideration current foreground
236    and background colors, if provided.
237
238    Parameters
239    ----------
240    name : str
241        Color name.
242    fg : str, optional
243        Foreground color name.
244    bg : str, optional
245        Background color name.
246
247    Returns
248    -------
249    tok : Token
250        Pygments Token.Color subclass
251    fg : str or None
252        New computed foreground color name.
253    bg : str or None
254        New computed background color name.
255    """
256    name = name.upper()
257    if name == "NO_COLOR":
258        return Color.NO_COLOR, None, None
259    m = RE_BACKGROUND.search(name)
260    if m is None:  # must be foreground color
261        fg = norm_name(name)
262    else:
263        bg = norm_name(name)
264    # assemble token
265    if fg is None and bg is None:
266        tokname = "NO_COLOR"
267    elif fg is None:
268        tokname = bg
269    elif bg is None:
270        tokname = fg
271    else:
272        tokname = fg + "__" + bg
273    tok = getattr(Color, tokname)
274    return tok, fg, bg
275
276
277def code_by_name(name, styles):
278    """Converts a token name into a pygments-style color code.
279
280    Parameters
281    ----------
282    name : str
283        Color token name.
284    styles : Mapping
285        Mapping for looking up non-hex colors
286
287    Returns
288    -------
289    code : str
290        Pygments style color code.
291    """
292    fg, _, bg = name.lower().partition("__")
293    if fg.startswith("background_"):
294        fg, bg = bg, fg
295    codes = []
296    # foreground color
297    if len(fg) == 0:
298        pass
299    elif "hex" in fg:
300        for p in fg.split("_"):
301            codes.append("#" + p[3:] if p.startswith("hex") else p)
302    else:
303        fgtok = getattr(Color, fg.upper())
304        if fgtok in styles:
305            codes.append(styles[fgtok])
306        else:
307            codes += fg.split("_")
308    # background color
309    if len(bg) == 0:
310        pass
311    elif bg.startswith("background_hex"):
312        codes.append("bg:#" + bg[14:])
313    else:
314        bgtok = getattr(Color, bg.upper())
315        if bgtok in styles:
316            codes.append(styles[bgtok])
317        else:
318            codes.append(bg.replace("background_", "bg:"))
319    code = " ".join(codes)
320    return code
321
322
323def partial_color_tokenize(template):
324    """Tokenizes a template string containing colors. Will return a list
325    of tuples mapping the token to the string which has that color.
326    These sub-strings maybe templates themselves.
327    """
328    if hasattr(builtins, "__xonsh_shell__"):
329        styles = __xonsh_shell__.shell.styler.styles
330    else:
331        styles = None
332    color = Color.NO_COLOR
333    try:
334        toks, color = _partial_color_tokenize_main(template, styles)
335    except Exception:
336        toks = [(Color.NO_COLOR, template)]
337    if styles is not None:
338        styles[color]  # ensure color is available
339    return toks
340
341
342def _partial_color_tokenize_main(template, styles):
343    formatter = string.Formatter()
344    bopen = "{"
345    bclose = "}"
346    colon = ":"
347    expl = "!"
348    color = Color.NO_COLOR
349    fg = bg = None
350    value = ""
351    toks = []
352    for literal, field, spec, conv in formatter.parse(template):
353        if field is None:
354            value += literal
355        elif field in KNOWN_COLORS or "#" in field:
356            value += literal
357            next_color, fg, bg = color_by_name(field, fg, bg)
358            if next_color is not color:
359                if len(value) > 0:
360                    toks.append((color, value))
361                    if styles is not None:
362                        styles[color]  # ensure color is available
363                color = next_color
364                value = ""
365        elif field is not None:
366            parts = [literal, bopen, field]
367            if conv is not None and len(conv) > 0:
368                parts.append(expl)
369                parts.append(conv)
370            if spec is not None and len(spec) > 0:
371                parts.append(colon)
372                parts.append(spec)
373            parts.append(bclose)
374            value += "".join(parts)
375        else:
376            value += literal
377    toks.append((color, value))
378    return toks, color
379
380
381class CompoundColorMap(MutableMapping):
382    """Looks up color tokens by name, potentially generating the value
383    from the lookup.
384    """
385
386    def __init__(self, styles, *args, **kwargs):
387        self.styles = styles
388        self.colors = dict(*args, **kwargs)
389
390    def __getitem__(self, key):
391        if key in self.colors:
392            return self.colors[key]
393        if key in self.styles:
394            value = self.styles[key]
395            self[key] = value
396            return value
397        if key is Color:
398            raise KeyError
399        pre, _, name = str(key).rpartition(".")
400        if pre != "Token.Color":
401            raise KeyError
402        value = code_by_name(name, self.styles)
403        self[key] = value
404        return value
405
406    def __setitem__(self, key, value):
407        self.colors[key] = value
408
409    def __delitem__(self, key):
410        del self.colors[key]
411
412    def __iter__(self):
413        yield from self.colors.keys()
414
415    def __len__(self):
416        return len(self.colors)
417
418
419class XonshStyle(Style):
420    """A xonsh pygments style that will dispatch to the correct color map
421    by using a ChainMap.  The style_name property may be used to reset
422    the current style.
423    """
424
425    def __init__(self, style_name="default"):
426        """
427        Parameters
428        ----------
429        style_name : str, optional
430            The style name to initialize with.
431        """
432        self.trap = {}  # for trapping custom colors set by user
433        self._smap = {}
434        self._style_name = ""
435        self.style_name = style_name
436        super().__init__()
437
438    @property
439    def style_name(self):
440        return self._style_name
441
442    @style_name.setter
443    def style_name(self, value):
444        if self._style_name == value:
445            return
446        if value not in STYLES:
447            try:  # loading style dynamically
448                pygments_style_by_name(value)
449            except Exception:
450                print(
451                    "Could not find style {0!r}, using default".format(value),
452                    file=sys.stderr,
453                )
454                value = "default"
455                builtins.__xonsh_env__["XONSH_COLOR_STYLE"] = value
456        cmap = STYLES[value]
457        if value == "default":
458            self._smap = XONSH_BASE_STYLE.copy()
459        else:
460            try:
461                self._smap = get_style_by_name(value)().styles.copy()
462            except (ImportError, pygments.util.ClassNotFound):
463                self._smap = XONSH_BASE_STYLE.copy()
464        compound = CompoundColorMap(ChainMap(self.trap, cmap, PTK_STYLE, self._smap))
465        self.styles = ChainMap(self.trap, cmap, PTK_STYLE, self._smap, compound)
466        self._style_name = value
467        # Convert new ansicolor names to old PTK1 names
468        # Can be remvoed when PTK1 support is dropped.
469        if builtins.__xonsh_shell__.shell_type != "prompt_toolkit2":
470            for smap in [self.trap, cmap, PTK_STYLE, self._smap]:
471                smap.update(ansicolors_to_ptk1_names(smap))
472        if ON_WINDOWS and "prompt_toolkit" in builtins.__xonsh_shell__.shell_type:
473            self.enhance_colors_for_cmd_exe()
474
475    @style_name.deleter
476    def style_name(self):
477        self._style_name = ""
478
479    def enhance_colors_for_cmd_exe(self):
480        """ Enhance colors when using cmd.exe on windows.
481            When using the default style all blue and dark red colors
482            are changed to CYAN and intense red.
483        """
484        env = builtins.__xonsh_env__
485        # Ensure we are not using ConEmu or Visual Stuio Code
486        if "CONEMUANSI" in env or "VSCODE_PID" in env:
487            return
488        if env.get("INTENSIFY_COLORS_ON_WIN", False):
489            if win_ansi_support():
490                newcolors = hardcode_colors_for_win10(self.styles)
491            else:
492                newcolors = intensify_colors_for_cmd_exe(self.styles)
493            self.trap.update(newcolors)
494
495
496def xonsh_style_proxy(styler):
497    """Factory for a proxy class to a xonsh style."""
498    # Monky patch pygments' list of known ansi colors
499    # with the new ansi color names used by PTK2
500    # Can be removed once pygment names get fixed.
501    pygments.style.ansicolors.update(ANSICOLOR_NAMES_MAP)
502
503    class XonshStyleProxy(Style):
504        """Simple proxy class to fool prompt toolkit."""
505
506        target = styler
507        styles = styler.styles
508
509        def __new__(cls, *args, **kwargs):
510            return cls.target
511
512    return XonshStyleProxy
513
514
515PTK_STYLE = LazyObject(
516    lambda: {
517        Token.Menu.Completions: "bg:ansigray ansiblack",
518        Token.Menu.Completions.Completion: "",
519        Token.Menu.Completions.Completion.Current: "bg:ansibrightblack ansiwhite",
520        Token.Scrollbar: "bg:ansibrightblack",
521        Token.Scrollbar.Button: "bg:ansiblack",
522        Token.Scrollbar.Arrow: "bg:ansiblack ansiwhite bold",
523        Token.AutoSuggestion: "ansibrightblack",
524        Token.Aborted: "ansibrightblack",
525    },
526    globals(),
527    "PTK_STYLE",
528)
529
530
531XONSH_BASE_STYLE = LazyObject(
532    lambda: {
533        Whitespace: "ansigray",
534        Comment: "underline ansicyan",
535        Comment.Preproc: "underline ansiyellow",
536        Keyword: "bold ansigreen",
537        Keyword.Pseudo: "nobold",
538        Keyword.Type: "nobold ansired",
539        Operator: "ansibrightblack",
540        Operator.Word: "bold ansimagenta",
541        Name.Builtin: "ansigreen",
542        Name.Function: "ansibrightblue",
543        Name.Class: "bold ansibrightblue",
544        Name.Namespace: "bold ansibrightblue",
545        Name.Exception: "bold ansibrightred",
546        Name.Variable: "ansiblue",
547        Name.Constant: "ansired",
548        Name.Label: "ansibrightyellow",
549        Name.Entity: "bold ansigray",
550        Name.Attribute: "ansibrightyellow",
551        Name.Tag: "bold ansigreen",
552        Name.Decorator: "ansibrightmagenta",
553        String: "ansibrightred",
554        String.Doc: "underline",
555        String.Interpol: "bold ansimagenta",
556        String.Escape: "bold ansiyellow",
557        String.Regex: "ansimagenta",
558        String.Symbol: "ansiyellow",
559        String.Other: "ansigreen",
560        Number: "ansibrightblack",
561        Generic.Heading: "bold ansiblue",
562        Generic.Subheading: "bold ansimagenta",
563        Generic.Deleted: "ansired",
564        Generic.Inserted: "ansibrightgreen",
565        Generic.Error: "bold ansibrightred",
566        Generic.Emph: "underline",
567        Generic.Prompt: "bold ansiblue",
568        Generic.Output: "ansiblue",
569        Generic.Traceback: "ansiblue",
570        Error: "ansibrightred",
571    },
572    globals(),
573    "XONSH_BASE_STYLE",
574)
575
576
577KNOWN_COLORS = LazyObject(
578    lambda: frozenset(
579        [
580            "BACKGROUND_BLACK",
581            "BACKGROUND_BLUE",
582            "BACKGROUND_CYAN",
583            "BACKGROUND_GREEN",
584            "BACKGROUND_INTENSE_BLACK",
585            "BACKGROUND_INTENSE_BLUE",
586            "BACKGROUND_INTENSE_CYAN",
587            "BACKGROUND_INTENSE_GREEN",
588            "BACKGROUND_INTENSE_PURPLE",
589            "BACKGROUND_INTENSE_RED",
590            "BACKGROUND_INTENSE_WHITE",
591            "BACKGROUND_INTENSE_YELLOW",
592            "BACKGROUND_PURPLE",
593            "BACKGROUND_RED",
594            "BACKGROUND_WHITE",
595            "BACKGROUND_YELLOW",
596            "BLACK",
597            "BLUE",
598            "BOLD_BLACK",
599            "BOLD_BLUE",
600            "BOLD_CYAN",
601            "BOLD_GREEN",
602            "BOLD_INTENSE_BLACK",
603            "BOLD_INTENSE_BLUE",
604            "BOLD_INTENSE_CYAN",
605            "BOLD_INTENSE_GREEN",
606            "BOLD_INTENSE_PURPLE",
607            "BOLD_INTENSE_RED",
608            "BOLD_INTENSE_WHITE",
609            "BOLD_INTENSE_YELLOW",
610            "BOLD_PURPLE",
611            "BOLD_RED",
612            "BOLD_UNDERLINE_BLACK",
613            "BOLD_UNDERLINE_BLUE",
614            "BOLD_UNDERLINE_CYAN",
615            "BOLD_UNDERLINE_GREEN",
616            "BOLD_UNDERLINE_INTENSE_BLACK",
617            "BOLD_UNDERLINE_INTENSE_BLUE",
618            "BOLD_UNDERLINE_INTENSE_CYAN",
619            "BOLD_UNDERLINE_INTENSE_GREEN",
620            "BOLD_UNDERLINE_INTENSE_PURPLE",
621            "BOLD_UNDERLINE_INTENSE_RED",
622            "BOLD_UNDERLINE_INTENSE_WHITE",
623            "BOLD_UNDERLINE_INTENSE_YELLOW",
624            "BOLD_UNDERLINE_PURPLE",
625            "BOLD_UNDERLINE_RED",
626            "BOLD_UNDERLINE_WHITE",
627            "BOLD_UNDERLINE_YELLOW",
628            "BOLD_WHITE",
629            "BOLD_YELLOW",
630            "CYAN",
631            "GREEN",
632            "INTENSE_BLACK",
633            "INTENSE_BLUE",
634            "INTENSE_CYAN",
635            "INTENSE_GREEN",
636            "INTENSE_PURPLE",
637            "INTENSE_RED",
638            "INTENSE_WHITE",
639            "INTENSE_YELLOW",
640            "NO_COLOR",
641            "PURPLE",
642            "RED",
643            "UNDERLINE_BLACK",
644            "UNDERLINE_BLUE",
645            "UNDERLINE_CYAN",
646            "UNDERLINE_GREEN",
647            "UNDERLINE_INTENSE_BLACK",
648            "UNDERLINE_INTENSE_BLUE",
649            "UNDERLINE_INTENSE_CYAN",
650            "UNDERLINE_INTENSE_GREEN",
651            "UNDERLINE_INTENSE_PURPLE",
652            "UNDERLINE_INTENSE_RED",
653            "UNDERLINE_INTENSE_WHITE",
654            "UNDERLINE_INTENSE_YELLOW",
655            "UNDERLINE_PURPLE",
656            "UNDERLINE_RED",
657            "UNDERLINE_WHITE",
658            "UNDERLINE_YELLOW",
659            "WHITE",
660            "YELLOW",
661        ]
662    ),
663    globals(),
664    "KNOWN_COLORS",
665)
666
667
668def _expand_style(cmap):
669    """Expands a style in order to more quickly make color map changes."""
670    for key, val in list(cmap.items()):
671        if key is Color.NO_COLOR:
672            continue
673        _, _, key = str(key).rpartition(".")
674        cmap[getattr(Color, "BOLD_" + key)] = "bold " + val
675        cmap[getattr(Color, "UNDERLINE_" + key)] = "underline " + val
676        cmap[getattr(Color, "BOLD_UNDERLINE_" + key)] = "bold underline " + val
677        if val == "noinherit":
678            cmap[getattr(Color, "BACKGROUND_" + key)] = val
679        else:
680            cmap[getattr(Color, "BACKGROUND_" + key)] = "bg:" + val
681
682
683def _bw_style():
684    style = {
685        Color.BLACK: "noinherit",
686        Color.BLUE: "noinherit",
687        Color.CYAN: "noinherit",
688        Color.GREEN: "noinherit",
689        Color.INTENSE_BLACK: "noinherit",
690        Color.INTENSE_BLUE: "noinherit",
691        Color.INTENSE_CYAN: "noinherit",
692        Color.INTENSE_GREEN: "noinherit",
693        Color.INTENSE_PURPLE: "noinherit",
694        Color.INTENSE_RED: "noinherit",
695        Color.INTENSE_WHITE: "noinherit",
696        Color.INTENSE_YELLOW: "noinherit",
697        Color.NO_COLOR: "noinherit",
698        Color.PURPLE: "noinherit",
699        Color.RED: "noinherit",
700        Color.WHITE: "noinherit",
701        Color.YELLOW: "noinherit",
702    }
703    _expand_style(style)
704    return style
705
706
707def _default_style():
708    style = {
709        Color.BLACK: "ansiblack",
710        Color.BLUE: "ansiblue",
711        Color.CYAN: "ansicyan",
712        Color.GREEN: "ansigreen",
713        Color.INTENSE_BLACK: "ansibrightblack",
714        Color.INTENSE_BLUE: "ansibrightblue",
715        Color.INTENSE_CYAN: "ansibrightcyan",
716        Color.INTENSE_GREEN: "ansibrightgreen",
717        Color.INTENSE_PURPLE: "ansibrightmagenta",
718        Color.INTENSE_RED: "ansibrightred",
719        Color.INTENSE_WHITE: "ansiwhite",
720        Color.INTENSE_YELLOW: "ansibrightyellow",
721        Color.NO_COLOR: "noinherit",
722        Color.PURPLE: "ansimagenta",
723        Color.RED: "ansired",
724        Color.WHITE: "ansigray",
725        Color.YELLOW: "ansiyellow",
726    }
727    _expand_style(style)
728    return style
729
730
731def _monokai_style():
732    style = {
733        Color.BLACK: "#1e0010",
734        Color.BLUE: "#6666ef",
735        Color.CYAN: "#66d9ef",
736        Color.GREEN: "#2ee22e",
737        Color.INTENSE_BLACK: "#5e5e5e",
738        Color.INTENSE_BLUE: "#2626d7",
739        Color.INTENSE_CYAN: "#2ed9d9",
740        Color.INTENSE_GREEN: "#a6e22e",
741        Color.INTENSE_PURPLE: "#ae81ff",
742        Color.INTENSE_RED: "#f92672",
743        Color.INTENSE_WHITE: "#f8f8f2",
744        Color.INTENSE_YELLOW: "#e6db74",
745        Color.NO_COLOR: "noinherit",
746        Color.PURPLE: "#960050",
747        Color.RED: "#AF0000",
748        Color.WHITE: "#d7d7d7",
749        Color.YELLOW: "#e2e22e",
750    }
751    _expand_style(style)
752    return style
753
754
755######################################
756#   Auto-generated below this line   #
757######################################
758def _algol_style():
759    style = {
760        Color.BLACK: "#666",
761        Color.BLUE: "#666",
762        Color.CYAN: "#666",
763        Color.GREEN: "#666",
764        Color.INTENSE_BLACK: "#666",
765        Color.INTENSE_BLUE: "#888",
766        Color.INTENSE_CYAN: "#888",
767        Color.INTENSE_GREEN: "#888",
768        Color.INTENSE_PURPLE: "#888",
769        Color.INTENSE_RED: "#FF0000",
770        Color.INTENSE_WHITE: "#888",
771        Color.INTENSE_YELLOW: "#888",
772        Color.NO_COLOR: "noinherit",
773        Color.PURPLE: "#666",
774        Color.RED: "#FF0000",
775        Color.WHITE: "#888",
776        Color.YELLOW: "#FF0000",
777    }
778    _expand_style(style)
779    return style
780
781
782def _algol_nu_style():
783    style = {
784        Color.BLACK: "#666",
785        Color.BLUE: "#666",
786        Color.CYAN: "#666",
787        Color.GREEN: "#666",
788        Color.INTENSE_BLACK: "#666",
789        Color.INTENSE_BLUE: "#888",
790        Color.INTENSE_CYAN: "#888",
791        Color.INTENSE_GREEN: "#888",
792        Color.INTENSE_PURPLE: "#888",
793        Color.INTENSE_RED: "#FF0000",
794        Color.INTENSE_WHITE: "#888",
795        Color.INTENSE_YELLOW: "#888",
796        Color.NO_COLOR: "noinherit",
797        Color.PURPLE: "#666",
798        Color.RED: "#FF0000",
799        Color.WHITE: "#888",
800        Color.YELLOW: "#FF0000",
801    }
802    _expand_style(style)
803    return style
804
805
806def _autumn_style():
807    style = {
808        Color.BLACK: "#000080",
809        Color.BLUE: "#0000aa",
810        Color.CYAN: "#00aaaa",
811        Color.GREEN: "#00aa00",
812        Color.INTENSE_BLACK: "#555555",
813        Color.INTENSE_BLUE: "#1e90ff",
814        Color.INTENSE_CYAN: "#1e90ff",
815        Color.INTENSE_GREEN: "#4c8317",
816        Color.INTENSE_PURPLE: "#FAA",
817        Color.INTENSE_RED: "#aa5500",
818        Color.INTENSE_WHITE: "#bbbbbb",
819        Color.INTENSE_YELLOW: "#FAA",
820        Color.NO_COLOR: "noinherit",
821        Color.PURPLE: "#800080",
822        Color.RED: "#aa0000",
823        Color.WHITE: "#aaaaaa",
824        Color.YELLOW: "#aa5500",
825    }
826    _expand_style(style)
827    return style
828
829
830def _borland_style():
831    style = {
832        Color.BLACK: "#000000",
833        Color.BLUE: "#000080",
834        Color.CYAN: "#008080",
835        Color.GREEN: "#008800",
836        Color.INTENSE_BLACK: "#555555",
837        Color.INTENSE_BLUE: "#0000FF",
838        Color.INTENSE_CYAN: "#ddffdd",
839        Color.INTENSE_GREEN: "#888888",
840        Color.INTENSE_PURPLE: "#e3d2d2",
841        Color.INTENSE_RED: "#FF0000",
842        Color.INTENSE_WHITE: "#ffdddd",
843        Color.INTENSE_YELLOW: "#e3d2d2",
844        Color.NO_COLOR: "noinherit",
845        Color.PURPLE: "#800080",
846        Color.RED: "#aa0000",
847        Color.WHITE: "#aaaaaa",
848        Color.YELLOW: "#a61717",
849    }
850    _expand_style(style)
851    return style
852
853
854def _colorful_style():
855    style = {
856        Color.BLACK: "#000",
857        Color.BLUE: "#00C",
858        Color.CYAN: "#0e84b5",
859        Color.GREEN: "#00A000",
860        Color.INTENSE_BLACK: "#555",
861        Color.INTENSE_BLUE: "#33B",
862        Color.INTENSE_CYAN: "#bbbbbb",
863        Color.INTENSE_GREEN: "#888",
864        Color.INTENSE_PURPLE: "#FAA",
865        Color.INTENSE_RED: "#D42",
866        Color.INTENSE_WHITE: "#fff0ff",
867        Color.INTENSE_YELLOW: "#FAA",
868        Color.NO_COLOR: "noinherit",
869        Color.PURPLE: "#800080",
870        Color.RED: "#A00000",
871        Color.WHITE: "#bbbbbb",
872        Color.YELLOW: "#A60",
873    }
874    _expand_style(style)
875    return style
876
877
878def _emacs_style():
879    style = {
880        Color.BLACK: "#008000",
881        Color.BLUE: "#000080",
882        Color.CYAN: "#04D",
883        Color.GREEN: "#00A000",
884        Color.INTENSE_BLACK: "#666666",
885        Color.INTENSE_BLUE: "#04D",
886        Color.INTENSE_CYAN: "#bbbbbb",
887        Color.INTENSE_GREEN: "#00BB00",
888        Color.INTENSE_PURPLE: "#AA22FF",
889        Color.INTENSE_RED: "#D2413A",
890        Color.INTENSE_WHITE: "#bbbbbb",
891        Color.INTENSE_YELLOW: "#bbbbbb",
892        Color.NO_COLOR: "noinherit",
893        Color.PURPLE: "#800080",
894        Color.RED: "#A00000",
895        Color.WHITE: "#bbbbbb",
896        Color.YELLOW: "#BB6622",
897    }
898    _expand_style(style)
899    return style
900
901
902def _friendly_style():
903    style = {
904        Color.BLACK: "#007020",
905        Color.BLUE: "#000080",
906        Color.CYAN: "#0e84b5",
907        Color.GREEN: "#00A000",
908        Color.INTENSE_BLACK: "#555555",
909        Color.INTENSE_BLUE: "#70a0d0",
910        Color.INTENSE_CYAN: "#60add5",
911        Color.INTENSE_GREEN: "#40a070",
912        Color.INTENSE_PURPLE: "#bb60d5",
913        Color.INTENSE_RED: "#d55537",
914        Color.INTENSE_WHITE: "#fff0f0",
915        Color.INTENSE_YELLOW: "#bbbbbb",
916        Color.NO_COLOR: "noinherit",
917        Color.PURPLE: "#800080",
918        Color.RED: "#A00000",
919        Color.WHITE: "#bbbbbb",
920        Color.YELLOW: "#c65d09",
921    }
922    _expand_style(style)
923    return style
924
925
926def _fruity_style():
927    style = {
928        Color.BLACK: "#0f140f",
929        Color.BLUE: "#0086d2",
930        Color.CYAN: "#0086d2",
931        Color.GREEN: "#008800",
932        Color.INTENSE_BLACK: "#444444",
933        Color.INTENSE_BLUE: "#0086f7",
934        Color.INTENSE_CYAN: "#0086f7",
935        Color.INTENSE_GREEN: "#888888",
936        Color.INTENSE_PURPLE: "#ff0086",
937        Color.INTENSE_RED: "#fb660a",
938        Color.INTENSE_WHITE: "#ffffff",
939        Color.INTENSE_YELLOW: "#cdcaa9",
940        Color.NO_COLOR: "noinherit",
941        Color.PURPLE: "#ff0086",
942        Color.RED: "#ff0007",
943        Color.WHITE: "#cdcaa9",
944        Color.YELLOW: "#fb660a",
945    }
946    _expand_style(style)
947    return style
948
949
950def _igor_style():
951    style = {
952        Color.BLACK: "#009C00",
953        Color.BLUE: "#0000FF",
954        Color.CYAN: "#007575",
955        Color.GREEN: "#009C00",
956        Color.INTENSE_BLACK: "#007575",
957        Color.INTENSE_BLUE: "#0000FF",
958        Color.INTENSE_CYAN: "#007575",
959        Color.INTENSE_GREEN: "#009C00",
960        Color.INTENSE_PURPLE: "#CC00A3",
961        Color.INTENSE_RED: "#C34E00",
962        Color.INTENSE_WHITE: "#CC00A3",
963        Color.INTENSE_YELLOW: "#C34E00",
964        Color.NO_COLOR: "noinherit",
965        Color.PURPLE: "#CC00A3",
966        Color.RED: "#C34E00",
967        Color.WHITE: "#CC00A3",
968        Color.YELLOW: "#C34E00",
969    }
970    _expand_style(style)
971    return style
972
973
974def _lovelace_style():
975    style = {
976        Color.BLACK: "#444444",
977        Color.BLUE: "#2838b0",
978        Color.CYAN: "#289870",
979        Color.GREEN: "#388038",
980        Color.INTENSE_BLACK: "#666666",
981        Color.INTENSE_BLUE: "#2838b0",
982        Color.INTENSE_CYAN: "#888888",
983        Color.INTENSE_GREEN: "#289870",
984        Color.INTENSE_PURPLE: "#a848a8",
985        Color.INTENSE_RED: "#b83838",
986        Color.INTENSE_WHITE: "#888888",
987        Color.INTENSE_YELLOW: "#a89028",
988        Color.NO_COLOR: "noinherit",
989        Color.PURPLE: "#a848a8",
990        Color.RED: "#c02828",
991        Color.WHITE: "#888888",
992        Color.YELLOW: "#b85820",
993    }
994    _expand_style(style)
995    return style
996
997
998def _manni_style():
999    style = {
1000        Color.BLACK: "#000000",
1001        Color.BLUE: "#000099",
1002        Color.CYAN: "#009999",
1003        Color.GREEN: "#00CC00",
1004        Color.INTENSE_BLACK: "#555555",
1005        Color.INTENSE_BLUE: "#9999FF",
1006        Color.INTENSE_CYAN: "#00CCFF",
1007        Color.INTENSE_GREEN: "#99CC66",
1008        Color.INTENSE_PURPLE: "#CC00FF",
1009        Color.INTENSE_RED: "#FF6600",
1010        Color.INTENSE_WHITE: "#FFCCCC",
1011        Color.INTENSE_YELLOW: "#FFCC33",
1012        Color.NO_COLOR: "noinherit",
1013        Color.PURPLE: "#CC00FF",
1014        Color.RED: "#AA0000",
1015        Color.WHITE: "#AAAAAA",
1016        Color.YELLOW: "#CC3300",
1017    }
1018    _expand_style(style)
1019    return style
1020
1021
1022def _murphy_style():
1023    style = {
1024        Color.BLACK: "#000",
1025        Color.BLUE: "#000080",
1026        Color.CYAN: "#0e84b5",
1027        Color.GREEN: "#00A000",
1028        Color.INTENSE_BLACK: "#555",
1029        Color.INTENSE_BLUE: "#66f",
1030        Color.INTENSE_CYAN: "#5ed",
1031        Color.INTENSE_GREEN: "#5ed",
1032        Color.INTENSE_PURPLE: "#e9e",
1033        Color.INTENSE_RED: "#f84",
1034        Color.INTENSE_WHITE: "#eee",
1035        Color.INTENSE_YELLOW: "#fc8",
1036        Color.NO_COLOR: "noinherit",
1037        Color.PURPLE: "#800080",
1038        Color.RED: "#A00000",
1039        Color.WHITE: "#bbbbbb",
1040        Color.YELLOW: "#c65d09",
1041    }
1042    _expand_style(style)
1043    return style
1044
1045
1046def _native_style():
1047    style = {
1048        Color.BLACK: "#520000",
1049        Color.BLUE: "#3677a9",
1050        Color.CYAN: "#24909d",
1051        Color.GREEN: "#589819",
1052        Color.INTENSE_BLACK: "#666666",
1053        Color.INTENSE_BLUE: "#447fcf",
1054        Color.INTENSE_CYAN: "#40ffff",
1055        Color.INTENSE_GREEN: "#6ab825",
1056        Color.INTENSE_PURPLE: "#e3d2d2",
1057        Color.INTENSE_RED: "#cd2828",
1058        Color.INTENSE_WHITE: "#ffffff",
1059        Color.INTENSE_YELLOW: "#ed9d13",
1060        Color.NO_COLOR: "noinherit",
1061        Color.PURPLE: "#666666",
1062        Color.RED: "#a61717",
1063        Color.WHITE: "#aaaaaa",
1064        Color.YELLOW: "#a61717",
1065    }
1066    _expand_style(style)
1067    return style
1068
1069
1070def _paraiso_dark_style():
1071    style = {
1072        Color.BLACK: "#776e71",
1073        Color.BLUE: "#815ba4",
1074        Color.CYAN: "#06b6ef",
1075        Color.GREEN: "#48b685",
1076        Color.INTENSE_BLACK: "#776e71",
1077        Color.INTENSE_BLUE: "#815ba4",
1078        Color.INTENSE_CYAN: "#5bc4bf",
1079        Color.INTENSE_GREEN: "#48b685",
1080        Color.INTENSE_PURPLE: "#e7e9db",
1081        Color.INTENSE_RED: "#ef6155",
1082        Color.INTENSE_WHITE: "#e7e9db",
1083        Color.INTENSE_YELLOW: "#fec418",
1084        Color.NO_COLOR: "noinherit",
1085        Color.PURPLE: "#815ba4",
1086        Color.RED: "#ef6155",
1087        Color.WHITE: "#5bc4bf",
1088        Color.YELLOW: "#f99b15",
1089    }
1090    _expand_style(style)
1091    return style
1092
1093
1094def _paraiso_light_style():
1095    style = {
1096        Color.BLACK: "#2f1e2e",
1097        Color.BLUE: "#2f1e2e",
1098        Color.CYAN: "#06b6ef",
1099        Color.GREEN: "#48b685",
1100        Color.INTENSE_BLACK: "#2f1e2e",
1101        Color.INTENSE_BLUE: "#815ba4",
1102        Color.INTENSE_CYAN: "#5bc4bf",
1103        Color.INTENSE_GREEN: "#48b685",
1104        Color.INTENSE_PURPLE: "#815ba4",
1105        Color.INTENSE_RED: "#ef6155",
1106        Color.INTENSE_WHITE: "#5bc4bf",
1107        Color.INTENSE_YELLOW: "#fec418",
1108        Color.NO_COLOR: "noinherit",
1109        Color.PURPLE: "#815ba4",
1110        Color.RED: "#2f1e2e",
1111        Color.WHITE: "#8d8687",
1112        Color.YELLOW: "#f99b15",
1113    }
1114    _expand_style(style)
1115    return style
1116
1117
1118def _pastie_style():
1119    style = {
1120        Color.BLACK: "#000000",
1121        Color.BLUE: "#0000DD",
1122        Color.CYAN: "#0066bb",
1123        Color.GREEN: "#008800",
1124        Color.INTENSE_BLACK: "#555555",
1125        Color.INTENSE_BLUE: "#3333bb",
1126        Color.INTENSE_CYAN: "#ddffdd",
1127        Color.INTENSE_GREEN: "#22bb22",
1128        Color.INTENSE_PURPLE: "#e3d2d2",
1129        Color.INTENSE_RED: "#dd7700",
1130        Color.INTENSE_WHITE: "#fff0ff",
1131        Color.INTENSE_YELLOW: "#e3d2d2",
1132        Color.NO_COLOR: "noinherit",
1133        Color.PURPLE: "#bb0066",
1134        Color.RED: "#aa0000",
1135        Color.WHITE: "#bbbbbb",
1136        Color.YELLOW: "#aa6600",
1137    }
1138    _expand_style(style)
1139    return style
1140
1141
1142def _perldoc_style():
1143    style = {
1144        Color.BLACK: "#000080",
1145        Color.BLUE: "#000080",
1146        Color.CYAN: "#1e889b",
1147        Color.GREEN: "#00aa00",
1148        Color.INTENSE_BLACK: "#555555",
1149        Color.INTENSE_BLUE: "#B452CD",
1150        Color.INTENSE_CYAN: "#bbbbbb",
1151        Color.INTENSE_GREEN: "#228B22",
1152        Color.INTENSE_PURPLE: "#B452CD",
1153        Color.INTENSE_RED: "#CD5555",
1154        Color.INTENSE_WHITE: "#e3d2d2",
1155        Color.INTENSE_YELLOW: "#e3d2d2",
1156        Color.NO_COLOR: "noinherit",
1157        Color.PURPLE: "#8B008B",
1158        Color.RED: "#aa0000",
1159        Color.WHITE: "#a7a7a7",
1160        Color.YELLOW: "#cb6c20",
1161    }
1162    _expand_style(style)
1163    return style
1164
1165
1166def _rrt_style():
1167    style = {
1168        Color.BLACK: "#ff0000",
1169        Color.BLUE: "#87ceeb",
1170        Color.CYAN: "#87ceeb",
1171        Color.GREEN: "#00ff00",
1172        Color.INTENSE_BLACK: "#87ceeb",
1173        Color.INTENSE_BLUE: "#87ceeb",
1174        Color.INTENSE_CYAN: "#7fffd4",
1175        Color.INTENSE_GREEN: "#00ff00",
1176        Color.INTENSE_PURPLE: "#ee82ee",
1177        Color.INTENSE_RED: "#ff0000",
1178        Color.INTENSE_WHITE: "#e5e5e5",
1179        Color.INTENSE_YELLOW: "#eedd82",
1180        Color.NO_COLOR: "noinherit",
1181        Color.PURPLE: "#ee82ee",
1182        Color.RED: "#ff0000",
1183        Color.WHITE: "#87ceeb",
1184        Color.YELLOW: "#ff0000",
1185    }
1186    _expand_style(style)
1187    return style
1188
1189
1190def _tango_style():
1191    style = {
1192        Color.BLACK: "#000000",
1193        Color.BLUE: "#0000cf",
1194        Color.CYAN: "#3465a4",
1195        Color.GREEN: "#00A000",
1196        Color.INTENSE_BLACK: "#204a87",
1197        Color.INTENSE_BLUE: "#5c35cc",
1198        Color.INTENSE_CYAN: "#f8f8f8",
1199        Color.INTENSE_GREEN: "#4e9a06",
1200        Color.INTENSE_PURPLE: "#f8f8f8",
1201        Color.INTENSE_RED: "#ef2929",
1202        Color.INTENSE_WHITE: "#f8f8f8",
1203        Color.INTENSE_YELLOW: "#c4a000",
1204        Color.NO_COLOR: "noinherit",
1205        Color.PURPLE: "#800080",
1206        Color.RED: "#a40000",
1207        Color.WHITE: "#f8f8f8",
1208        Color.YELLOW: "#8f5902",
1209    }
1210    _expand_style(style)
1211    return style
1212
1213
1214def _trac_style():
1215    style = {
1216        Color.BLACK: "#000000",
1217        Color.BLUE: "#000080",
1218        Color.CYAN: "#009999",
1219        Color.GREEN: "#808000",
1220        Color.INTENSE_BLACK: "#555555",
1221        Color.INTENSE_BLUE: "#445588",
1222        Color.INTENSE_CYAN: "#ddffdd",
1223        Color.INTENSE_GREEN: "#999988",
1224        Color.INTENSE_PURPLE: "#e3d2d2",
1225        Color.INTENSE_RED: "#bb8844",
1226        Color.INTENSE_WHITE: "#ffdddd",
1227        Color.INTENSE_YELLOW: "#e3d2d2",
1228        Color.NO_COLOR: "noinherit",
1229        Color.PURPLE: "#800080",
1230        Color.RED: "#aa0000",
1231        Color.WHITE: "#aaaaaa",
1232        Color.YELLOW: "#808000",
1233    }
1234    _expand_style(style)
1235    return style
1236
1237
1238def _vim_style():
1239    style = {
1240        Color.BLACK: "#000080",
1241        Color.BLUE: "#000080",
1242        Color.CYAN: "#00cdcd",
1243        Color.GREEN: "#00cd00",
1244        Color.INTENSE_BLACK: "#666699",
1245        Color.INTENSE_BLUE: "#3399cc",
1246        Color.INTENSE_CYAN: "#00cdcd",
1247        Color.INTENSE_GREEN: "#00cd00",
1248        Color.INTENSE_PURPLE: "#cd00cd",
1249        Color.INTENSE_RED: "#FF0000",
1250        Color.INTENSE_WHITE: "#cccccc",
1251        Color.INTENSE_YELLOW: "#cdcd00",
1252        Color.NO_COLOR: "noinherit",
1253        Color.PURPLE: "#cd00cd",
1254        Color.RED: "#cd0000",
1255        Color.WHITE: "#cccccc",
1256        Color.YELLOW: "#cd0000",
1257    }
1258    _expand_style(style)
1259    return style
1260
1261
1262def _vs_style():
1263    style = {
1264        Color.BLACK: "#008000",
1265        Color.BLUE: "#0000ff",
1266        Color.CYAN: "#2b91af",
1267        Color.GREEN: "#008000",
1268        Color.INTENSE_BLACK: "#2b91af",
1269        Color.INTENSE_BLUE: "#2b91af",
1270        Color.INTENSE_CYAN: "#2b91af",
1271        Color.INTENSE_GREEN: "#2b91af",
1272        Color.INTENSE_PURPLE: "#2b91af",
1273        Color.INTENSE_RED: "#FF0000",
1274        Color.INTENSE_WHITE: "#2b91af",
1275        Color.INTENSE_YELLOW: "#2b91af",
1276        Color.NO_COLOR: "noinherit",
1277        Color.PURPLE: "#a31515",
1278        Color.RED: "#a31515",
1279        Color.WHITE: "#2b91af",
1280        Color.YELLOW: "#a31515",
1281    }
1282    _expand_style(style)
1283    return style
1284
1285
1286def _xcode_style():
1287    style = {
1288        Color.BLACK: "#000000",
1289        Color.BLUE: "#1C01CE",
1290        Color.CYAN: "#3F6E75",
1291        Color.GREEN: "#177500",
1292        Color.INTENSE_BLACK: "#3F6E75",
1293        Color.INTENSE_BLUE: "#2300CE",
1294        Color.INTENSE_CYAN: "#3F6E75",
1295        Color.INTENSE_GREEN: "#3F6E75",
1296        Color.INTENSE_PURPLE: "#A90D91",
1297        Color.INTENSE_RED: "#C41A16",
1298        Color.INTENSE_WHITE: "#3F6E75",
1299        Color.INTENSE_YELLOW: "#836C28",
1300        Color.NO_COLOR: "noinherit",
1301        Color.PURPLE: "#A90D91",
1302        Color.RED: "#C41A16",
1303        Color.WHITE: "#3F6E75",
1304        Color.YELLOW: "#836C28",
1305    }
1306    _expand_style(style)
1307    return style
1308
1309
1310STYLES = LazyDict(
1311    {
1312        "algol": _algol_style,
1313        "algol_nu": _algol_nu_style,
1314        "autumn": _autumn_style,
1315        "borland": _borland_style,
1316        "bw": _bw_style,
1317        "colorful": _colorful_style,
1318        "default": _default_style,
1319        "emacs": _emacs_style,
1320        "friendly": _friendly_style,
1321        "fruity": _fruity_style,
1322        "igor": _igor_style,
1323        "lovelace": _lovelace_style,
1324        "manni": _manni_style,
1325        "monokai": _monokai_style,
1326        "murphy": _murphy_style,
1327        "native": _native_style,
1328        "paraiso-dark": _paraiso_dark_style,
1329        "paraiso-light": _paraiso_light_style,
1330        "pastie": _pastie_style,
1331        "perldoc": _perldoc_style,
1332        "rrt": _rrt_style,
1333        "tango": _tango_style,
1334        "trac": _trac_style,
1335        "vim": _vim_style,
1336        "vs": _vs_style,
1337        "xcode": _xcode_style,
1338    },
1339    globals(),
1340    "STYLES",
1341)
1342
1343del (
1344    _algol_style,
1345    _algol_nu_style,
1346    _autumn_style,
1347    _borland_style,
1348    _bw_style,
1349    _colorful_style,
1350    _default_style,
1351    _emacs_style,
1352    _friendly_style,
1353    _fruity_style,
1354    _igor_style,
1355    _lovelace_style,
1356    _manni_style,
1357    _monokai_style,
1358    _murphy_style,
1359    _native_style,
1360    _paraiso_dark_style,
1361    _paraiso_light_style,
1362    _pastie_style,
1363    _perldoc_style,
1364    _rrt_style,
1365    _tango_style,
1366    _trac_style,
1367    _vim_style,
1368    _vs_style,
1369    _xcode_style,
1370)
1371
1372
1373# dynamic styles
1374def make_pygments_style(palette):
1375    """Makes a pygments style based on a color palette."""
1376    global Color
1377    style = {getattr(Color, "NO_COLOR"): "noinherit"}
1378    for name, t in BASE_XONSH_COLORS.items():
1379        color = find_closest_color(t, palette)
1380        style[getattr(Color, name)] = "#" + color
1381        style[getattr(Color, "BOLD_" + name)] = "bold #" + color
1382        style[getattr(Color, "UNDERLINE_" + name)] = "underline #" + color
1383        style[getattr(Color, "BOLD_UNDERLINE_" + name)] = "bold underline #" + color
1384        style[getattr(Color, "BACKGROUND_" + name)] = "bg:#" + color
1385    return style
1386
1387
1388def pygments_style_by_name(name):
1389    """Gets or makes a pygments color style by its name."""
1390    if name in STYLES:
1391        return STYLES[name]
1392    pstyle = get_style_by_name(name)
1393    palette = make_palette(pstyle.styles.values())
1394    astyle = make_pygments_style(palette)
1395    STYLES[name] = astyle
1396    return astyle
1397
1398
1399def _monkey_patch_pygments_codes():
1400    """ Monky patch pygments' dict of console codes,
1401        with new color names
1402    """
1403    import pygments.console
1404
1405    if "brightblack" in pygments.console.codes:
1406        # Assume that colors are already fixed in pygments
1407        # for example when using pygments from source
1408        return
1409
1410    if not getattr(pygments.console, "_xonsh_patched", False):
1411        patched_codes = {}
1412        for new, old in PTK_NEW_OLD_COLOR_MAP.items():
1413            if old in pygments.console.codes:
1414                patched_codes[new[1:]] = pygments.console.codes[old]
1415        pygments.console.codes.update(patched_codes)
1416        pygments.console._xonsh_patched = True
1417
1418
1419#
1420# Formatter
1421#
1422
1423
1424@lazyobject
1425def XonshTerminal256Formatter():
1426
1427    if (
1428        ptk_version_info()
1429        and ptk_version_info() > (2, 0)
1430        and pygments_version_info()
1431        and (2, 2) <= pygments_version_info() < (2, 3)
1432    ):
1433        # Monky patch pygments' dict of console codes
1434        # with the new color names used by PTK2
1435        # Can be removed once pygment names get fixed.
1436        _monkey_patch_pygments_codes()
1437
1438    class XonshTerminal256FormatterProxy(terminal256.Terminal256Formatter):
1439        """Proxy class for xonsh terminal256 formatting that understands.
1440        xonsh color tokens.
1441        """
1442
1443        def __init__(self, *args, **kwargs):
1444            super().__init__(*args, **kwargs)
1445            # just keep the opening token for colors.
1446            color_names = set(map(str, Color.subtypes))
1447            for name, (opener, closer) in self.style_string.items():
1448                if name in color_names:
1449                    self.style_string[name] = (opener, "")
1450            # special case NO_COLOR, because it is special.
1451            self.style_string["Token.Color.NO_COLOR"] = ("\x1b[39m", "")
1452
1453    return XonshTerminal256FormatterProxy
1454