|
| 1 | +# Copyright 2010-2025 Antonio Cuni |
| 2 | +# Daniel Hahler |
| 3 | +# |
| 4 | +# All Rights Reserved |
| 5 | +"""Colorful tab completion for Python prompt""" |
| 6 | +from _colorize import ANSIColors, get_colors, get_theme |
| 7 | +import rlcompleter |
| 8 | +import keyword |
| 9 | +import types |
| 10 | + |
| 11 | +class Completer(rlcompleter.Completer): |
| 12 | + """ |
| 13 | + When doing something like a.b.<tab>, keep the full a.b.attr completion |
| 14 | + stem so readline-style completion can keep refining the menu as you type. |
| 15 | +
|
| 16 | + Optionally, display the various completions in different colors |
| 17 | + depending on the type. |
| 18 | + """ |
| 19 | + def __init__( |
| 20 | + self, |
| 21 | + namespace=None, |
| 22 | + *, |
| 23 | + use_colors='auto', |
| 24 | + consider_getitems=True, |
| 25 | + ): |
| 26 | + from _pyrepl import readline |
| 27 | + rlcompleter.Completer.__init__(self, namespace) |
| 28 | + if use_colors == 'auto': |
| 29 | + # use colors only if we can |
| 30 | + use_colors = get_colors().RED != "" |
| 31 | + self.use_colors = use_colors |
| 32 | + self.consider_getitems = consider_getitems |
| 33 | + |
| 34 | + if self.use_colors: |
| 35 | + # In GNU readline, this prevents escaping of ANSI control |
| 36 | + # characters in completion results. pyrepl's parse_and_bind() |
| 37 | + # is a no-op, but pyrepl handles ANSI sequences natively |
| 38 | + # via real_len()/stripcolor(). |
| 39 | + readline.parse_and_bind('set dont-escape-ctrl-chars on') |
| 40 | + self.theme = get_theme() |
| 41 | + else: |
| 42 | + self.theme = None |
| 43 | + |
| 44 | + if self.consider_getitems: |
| 45 | + delims = readline.get_completer_delims() |
| 46 | + delims = delims.replace('[', '') |
| 47 | + delims = delims.replace(']', '') |
| 48 | + readline.set_completer_delims(delims) |
| 49 | + |
| 50 | + def complete(self, text, state): |
| 51 | + # if you press <tab> at the beginning of a line, insert an actual |
| 52 | + # \t. Else, trigger completion. |
| 53 | + if text == "": |
| 54 | + return ('\t', None)[state] |
| 55 | + else: |
| 56 | + return rlcompleter.Completer.complete(self, text, state) |
| 57 | + |
| 58 | + def _callable_postfix(self, val, word): |
| 59 | + # disable automatic insertion of '(' for global callables |
| 60 | + return word |
| 61 | + |
| 62 | + def _callable_attr_postfix(self, val, word): |
| 63 | + return rlcompleter.Completer._callable_postfix(self, val, word) |
| 64 | + |
| 65 | + def global_matches(self, text): |
| 66 | + names = rlcompleter.Completer.global_matches(self, text) |
| 67 | + prefix = commonprefix(names) |
| 68 | + if prefix and prefix != text: |
| 69 | + return [prefix] |
| 70 | + |
| 71 | + names.sort() |
| 72 | + values = [] |
| 73 | + for name in names: |
| 74 | + clean_name = name.rstrip(': ') |
| 75 | + if keyword.iskeyword(clean_name) or keyword.issoftkeyword(clean_name): |
| 76 | + values.append(None) |
| 77 | + else: |
| 78 | + try: |
| 79 | + values.append(eval(name, self.namespace)) |
| 80 | + except Exception: |
| 81 | + values.append(None) |
| 82 | + if self.use_colors and names: |
| 83 | + return self.colorize_matches(names, values) |
| 84 | + return names |
| 85 | + |
| 86 | + def attr_matches(self, text): |
| 87 | + try: |
| 88 | + expr, attr, names, values = self._attr_matches(text) |
| 89 | + except ValueError: |
| 90 | + return [] |
| 91 | + |
| 92 | + if not names: |
| 93 | + return [] |
| 94 | + |
| 95 | + if len(names) == 1: |
| 96 | + # No coloring: when returning a single completion, readline |
| 97 | + # inserts it directly into the prompt, so ANSI codes would |
| 98 | + # appear as literal characters. |
| 99 | + return [self._callable_attr_postfix(values[0], f'{expr}.{names[0]}')] |
| 100 | + |
| 101 | + prefix = commonprefix(names) |
| 102 | + if prefix and prefix != attr: |
| 103 | + return [f'{expr}.{prefix}'] # autocomplete prefix |
| 104 | + |
| 105 | + names = [f'{expr}.{name}' for name in names] |
| 106 | + if self.use_colors: |
| 107 | + return self.colorize_matches(names, values) |
| 108 | + |
| 109 | + if prefix: |
| 110 | + names.append(' ') |
| 111 | + return names |
| 112 | + |
| 113 | + def _attr_matches(self, text): |
| 114 | + expr, attr = text.rsplit('.', 1) |
| 115 | + if '(' in expr or ')' in expr: # don't call functions |
| 116 | + return expr, attr, [], [] |
| 117 | + try: |
| 118 | + thisobject = eval(expr, self.namespace) |
| 119 | + except Exception: |
| 120 | + return expr, attr, [], [] |
| 121 | + |
| 122 | + # get the content of the object, except __builtins__ |
| 123 | + words = set(dir(thisobject)) - {'__builtins__'} |
| 124 | + |
| 125 | + if hasattr(thisobject, '__class__'): |
| 126 | + words.add('__class__') |
| 127 | + words.update(rlcompleter.get_class_members(thisobject.__class__)) |
| 128 | + names = [] |
| 129 | + values = [] |
| 130 | + n = len(attr) |
| 131 | + if attr == '': |
| 132 | + noprefix = '_' |
| 133 | + elif attr == '_': |
| 134 | + noprefix = '__' |
| 135 | + else: |
| 136 | + noprefix = None |
| 137 | + |
| 138 | + # sort the words now to make sure to return completions in |
| 139 | + # alphabetical order. It's easier to do it now, else we would need to |
| 140 | + # sort 'names' later but make sure that 'values' in kept in sync, |
| 141 | + # which is annoying. |
| 142 | + words = sorted(words) |
| 143 | + while True: |
| 144 | + for word in words: |
| 145 | + if ( |
| 146 | + word[:n] == attr |
| 147 | + and not (noprefix and word[:n+1] == noprefix) |
| 148 | + ): |
| 149 | + # Mirror rlcompleter's safeguards so completion does not |
| 150 | + # call properties or reify lazy module attributes. |
| 151 | + if isinstance(getattr(type(thisobject), word, None), property): |
| 152 | + value = None |
| 153 | + elif ( |
| 154 | + isinstance(thisobject, types.ModuleType) |
| 155 | + and isinstance( |
| 156 | + thisobject.__dict__.get(word), |
| 157 | + types.LazyImportType, |
| 158 | + ) |
| 159 | + ): |
| 160 | + value = thisobject.__dict__.get(word) |
| 161 | + else: |
| 162 | + value = getattr(thisobject, word, None) |
| 163 | + |
| 164 | + names.append(word) |
| 165 | + values.append(value) |
| 166 | + if names or not noprefix: |
| 167 | + break |
| 168 | + if noprefix == '_': |
| 169 | + noprefix = '__' |
| 170 | + else: |
| 171 | + noprefix = None |
| 172 | + |
| 173 | + return expr, attr, names, values |
| 174 | + |
| 175 | + def colorize_matches(self, names, values): |
| 176 | + matches = [self._color_for_obj(i, name, obj) |
| 177 | + for i, (name, obj) |
| 178 | + in enumerate(zip(names, values))] |
| 179 | + # We add a space at the end to prevent the automatic completion of the |
| 180 | + # common prefix, which is the ANSI escape sequence. |
| 181 | + matches.append(' ') |
| 182 | + return matches |
| 183 | + |
| 184 | + def _color_for_obj(self, i, name, value): |
| 185 | + t = type(value) |
| 186 | + color = self._color_by_type(t) |
| 187 | + # Encode the match index into a fake escape sequence that |
| 188 | + # stripcolor() can still remove once i reaches four digits. |
| 189 | + N = f"\x1b[{i // 100:03d};{i % 100:02d}m" |
| 190 | + return f"{N}{color}{name}{ANSIColors.RESET}" |
| 191 | + |
| 192 | + def _color_by_type(self, t): |
| 193 | + typename = t.__name__ |
| 194 | + # this is needed e.g. to turn method-wrapper into method_wrapper, |
| 195 | + # because if we want _colorize.FancyCompleter to be "dataclassable" |
| 196 | + # our keys need to be valid identifiers. |
| 197 | + typename = typename.replace('-', '_').replace('.', '_') |
| 198 | + return getattr(self.theme.fancycompleter, typename, ANSIColors.RESET) |
| 199 | + |
| 200 | + |
| 201 | +def commonprefix(names): |
| 202 | + """Return the common prefix of all 'names'""" |
| 203 | + if not names: |
| 204 | + return '' |
| 205 | + s1 = min(names) |
| 206 | + s2 = max(names) |
| 207 | + for i, c in enumerate(s1): |
| 208 | + if c != s2[i]: |
| 209 | + return s1[:i] |
| 210 | + return s1 |
0 commit comments