| 40 | __all__ = ["Completer"] |
| 41 | |
| 42 | class Completer: |
| 43 | def __init__(self, namespace = None): |
| 44 | """Create a new completer for the command line. |
| 45 | |
| 46 | Completer([namespace]) -> completer instance. |
| 47 | |
| 48 | If unspecified, the default namespace where completions are performed |
| 49 | is __main__ (technically, __main__.__dict__). Namespaces should be |
| 50 | given as dictionaries. |
| 51 | |
| 52 | Completer instances should be used as the completion mechanism of |
| 53 | readline via the set_completer() call: |
| 54 | |
| 55 | readline.set_completer(Completer(my_namespace).complete) |
| 56 | """ |
| 57 | |
| 58 | if namespace and not isinstance(namespace, dict): |
| 59 | raise TypeError('namespace must be a dictionary') |
| 60 | |
| 61 | # Don't bind to namespace quite yet, but flag whether the user wants a |
| 62 | # specific namespace or to use __main__.__dict__. This will allow us |
| 63 | # to bind to __main__.__dict__ at completion time, not now. |
| 64 | if namespace is None: |
| 65 | self.use_main_ns = 1 |
| 66 | else: |
| 67 | self.use_main_ns = 0 |
| 68 | self.namespace = namespace |
| 69 | |
| 70 | def complete(self, text, state): |
| 71 | """Return the next possible completion for 'text'. |
| 72 | |
| 73 | This is called successively with state == 0, 1, 2, ... until it |
| 74 | returns None. The completion should begin with 'text'. |
| 75 | |
| 76 | """ |
| 77 | if self.use_main_ns: |
| 78 | self.namespace = __main__.__dict__ |
| 79 | |
| 80 | if not text.strip(): |
| 81 | if state == 0: |
| 82 | if _readline_available: |
| 83 | readline.insert_text('\t') |
| 84 | readline.redisplay() |
| 85 | return '' |
| 86 | else: |
| 87 | return '\t' |
| 88 | else: |
| 89 | return None |
| 90 | |
| 91 | if state == 0: |
| 92 | with warnings.catch_warnings(action="ignore"): |
| 93 | if "." in text: |
| 94 | self.matches = self.attr_matches(text) |
| 95 | else: |
| 96 | self.matches = self.global_matches(text) |
| 97 | try: |
| 98 | return self.matches[state] |
| 99 | except IndexError: |