Georg Brandl | d864407 | 2012-03-27 07:46:46 +0200 | [diff] [blame] | 1 | """Word completion for GNU readline. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 2 | |
Georg Brandl | d864407 | 2012-03-27 07:46:46 +0200 | [diff] [blame] | 3 | The completer completes keywords, built-ins and globals in a selectable |
| 4 | namespace (which defaults to __main__); when completing NAME.NAME..., it |
| 5 | evaluates (!) the expression up to the last dot and completes its attributes. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 6 | |
Georg Brandl | d864407 | 2012-03-27 07:46:46 +0200 | [diff] [blame] | 7 | It's very cool to do "import sys" type "sys.", hit the completion key (twice), |
| 8 | and see the list of names defined by the sys module! |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 9 | |
| 10 | Tip: to use the tab key as the completion key, call |
| 11 | |
| 12 | readline.parse_and_bind("tab: complete") |
| 13 | |
| 14 | Notes: |
| 15 | |
Georg Brandl | d864407 | 2012-03-27 07:46:46 +0200 | [diff] [blame] | 16 | - Exceptions raised by the completer function are *ignored* (and generally cause |
| 17 | the completion to fail). This is a feature -- since readline sets the tty |
| 18 | device in raw (or cbreak) mode, printing a traceback wouldn't work well |
| 19 | without some complicated hoopla to save, reset and restore the tty state. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 20 | |
Georg Brandl | d864407 | 2012-03-27 07:46:46 +0200 | [diff] [blame] | 21 | - The evaluation of the NAME.NAME... form may cause arbitrary application |
| 22 | defined code to be executed if an object with a __getattr__ hook is found. |
| 23 | Since it is the responsibility of the application (or the user) to enable this |
| 24 | feature, I consider this an acceptable risk. More complicated expressions |
| 25 | (e.g. function calls or indexing operations) are *not* evaluated. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 26 | |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 27 | - When the original stdin is not a tty device, GNU readline is never |
Georg Brandl | d864407 | 2012-03-27 07:46:46 +0200 | [diff] [blame] | 28 | used, and this module (and the readline module) are silently inactive. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 29 | |
| 30 | """ |
| 31 | |
Antoine Pitrou | dcedaf6 | 2013-07-31 23:14:08 +0200 | [diff] [blame] | 32 | import atexit |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 33 | import builtins |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 34 | import __main__ |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 35 | |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 36 | __all__ = ["Completer"] |
| 37 | |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 38 | class Completer: |
Neil Schemenauer | dbab3e3 | 2002-03-23 23:44:51 +0000 | [diff] [blame] | 39 | def __init__(self, namespace = None): |
| 40 | """Create a new completer for the command line. |
| 41 | |
| 42 | Completer([namespace]) -> completer instance. |
| 43 | |
| 44 | If unspecified, the default namespace where completions are performed |
| 45 | is __main__ (technically, __main__.__dict__). Namespaces should be |
| 46 | given as dictionaries. |
| 47 | |
| 48 | Completer instances should be used as the completion mechanism of |
| 49 | readline via the set_completer() call: |
| 50 | |
| 51 | readline.set_completer(Completer(my_namespace).complete) |
| 52 | """ |
Tim Peters | 863ac44 | 2002-04-16 01:38:40 +0000 | [diff] [blame] | 53 | |
Neil Schemenauer | dbab3e3 | 2002-03-23 23:44:51 +0000 | [diff] [blame] | 54 | if namespace and not isinstance(namespace, dict): |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 55 | raise TypeError('namespace must be a dictionary') |
Neil Schemenauer | dbab3e3 | 2002-03-23 23:44:51 +0000 | [diff] [blame] | 56 | |
| 57 | # Don't bind to namespace quite yet, but flag whether the user wants a |
| 58 | # specific namespace or to use __main__.__dict__. This will allow us |
| 59 | # to bind to __main__.__dict__ at completion time, not now. |
| 60 | if namespace is None: |
| 61 | self.use_main_ns = 1 |
| 62 | else: |
| 63 | self.use_main_ns = 0 |
| 64 | self.namespace = namespace |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 65 | |
| 66 | def complete(self, text, state): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 67 | """Return the next possible completion for 'text'. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 68 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 69 | This is called successively with state == 0, 1, 2, ... until it |
| 70 | returns None. The completion should begin with 'text'. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 71 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 72 | """ |
Neil Schemenauer | dbab3e3 | 2002-03-23 23:44:51 +0000 | [diff] [blame] | 73 | if self.use_main_ns: |
| 74 | self.namespace = __main__.__dict__ |
Tim Peters | 863ac44 | 2002-04-16 01:38:40 +0000 | [diff] [blame] | 75 | |
Berker Peksag | aaf6114 | 2015-07-28 00:06:31 +0300 | [diff] [blame] | 76 | if not text.strip(): |
| 77 | if state == 0: |
Yury Selivanov | 46f7785 | 2016-02-04 14:00:26 -0500 | [diff] [blame] | 78 | if _readline_available: |
| 79 | readline.insert_text('\t') |
| 80 | readline.redisplay() |
| 81 | return '' |
| 82 | else: |
| 83 | return '\t' |
Berker Peksag | aaf6114 | 2015-07-28 00:06:31 +0300 | [diff] [blame] | 84 | else: |
| 85 | return None |
| 86 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 87 | if state == 0: |
| 88 | if "." in text: |
| 89 | self.matches = self.attr_matches(text) |
| 90 | else: |
| 91 | self.matches = self.global_matches(text) |
Guido van Rossum | d458faa | 1998-06-12 19:42:14 +0000 | [diff] [blame] | 92 | try: |
| 93 | return self.matches[state] |
| 94 | except IndexError: |
| 95 | return None |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 96 | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 97 | def _callable_postfix(self, val, word): |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 98 | if callable(val): |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 99 | word = word + "(" |
| 100 | return word |
| 101 | |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 102 | def global_matches(self, text): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 103 | """Compute matches when text is a simple name. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 104 | |
Neil Schemenauer | dbab3e3 | 2002-03-23 23:44:51 +0000 | [diff] [blame] | 105 | Return a list of all keywords, built-in functions and names currently |
| 106 | defined in self.namespace that match. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 107 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 108 | """ |
| 109 | import keyword |
| 110 | matches = [] |
Martin Panter | ed92910 | 2015-11-23 23:50:26 +0000 | [diff] [blame] | 111 | seen = {"__builtins__"} |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 112 | n = len(text) |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 113 | for word in keyword.kwlist: |
| 114 | if word[:n] == text: |
Martin Panter | ed92910 | 2015-11-23 23:50:26 +0000 | [diff] [blame] | 115 | seen.add(word) |
Serhiy Storchaka | 8ace8e9 | 2015-09-27 13:26:03 +0300 | [diff] [blame] | 116 | if word in {'finally', 'try'}: |
| 117 | word = word + ':' |
| 118 | elif word not in {'False', 'None', 'True', |
| 119 | 'break', 'continue', 'pass', |
| 120 | 'else'}: |
| 121 | word = word + ' ' |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 122 | matches.append(word) |
Martin Panter | ed92910 | 2015-11-23 23:50:26 +0000 | [diff] [blame] | 123 | for nspace in [self.namespace, builtins.__dict__]: |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 124 | for word, val in nspace.items(): |
Martin Panter | ed92910 | 2015-11-23 23:50:26 +0000 | [diff] [blame] | 125 | if word[:n] == text and word not in seen: |
| 126 | seen.add(word) |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 127 | matches.append(self._callable_postfix(val, word)) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 128 | return matches |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 129 | |
| 130 | def attr_matches(self, text): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 131 | """Compute matches when text contains a dot. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 132 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 133 | Assuming the text is of the form NAME.NAME....[NAME], and is |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 134 | evaluable in self.namespace, it will be evaluated and its attributes |
Neil Schemenauer | dbab3e3 | 2002-03-23 23:44:51 +0000 | [diff] [blame] | 135 | (as revealed by dir()) are used as possible completions. (For class |
Walter Dörwald | f0dfc7a | 2003-10-20 14:01:56 +0000 | [diff] [blame] | 136 | instances, class members are also considered.) |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 137 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 138 | WARNING: this can still invoke arbitrary C code, if an object |
| 139 | with a __getattr__ hook is evaluated. |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 140 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 141 | """ |
| 142 | import re |
| 143 | m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) |
| 144 | if not m: |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 145 | return [] |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 146 | expr, attr = m.group(1, 3) |
Alexandre Vassalotti | 8ae3e05 | 2008-05-16 00:41:41 +0000 | [diff] [blame] | 147 | try: |
Benjamin Peterson | 095c119 | 2008-07-21 16:32:10 +0000 | [diff] [blame] | 148 | thisobject = eval(expr, self.namespace) |
Alexandre Vassalotti | 8ae3e05 | 2008-05-16 00:41:41 +0000 | [diff] [blame] | 149 | except Exception: |
| 150 | return [] |
Benjamin Peterson | 095c119 | 2008-07-21 16:32:10 +0000 | [diff] [blame] | 151 | |
| 152 | # get the content of the object, except __builtins__ |
Serhiy Storchaka | ab82422 | 2015-09-27 13:43:50 +0300 | [diff] [blame] | 153 | words = set(dir(thisobject)) |
| 154 | words.discard("__builtins__") |
Benjamin Peterson | 095c119 | 2008-07-21 16:32:10 +0000 | [diff] [blame] | 155 | |
| 156 | if hasattr(thisobject, '__class__'): |
Serhiy Storchaka | ab82422 | 2015-09-27 13:43:50 +0300 | [diff] [blame] | 157 | words.add('__class__') |
| 158 | words.update(get_class_members(thisobject.__class__)) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 159 | matches = [] |
| 160 | n = len(attr) |
Serhiy Storchaka | ab82422 | 2015-09-27 13:43:50 +0300 | [diff] [blame] | 161 | if attr == '': |
| 162 | noprefix = '_' |
| 163 | elif attr == '_': |
| 164 | noprefix = '__' |
| 165 | else: |
| 166 | noprefix = None |
| 167 | while True: |
| 168 | for word in words: |
| 169 | if (word[:n] == attr and |
Martin Panter | f4ad5f5 | 2015-11-13 23:48:17 +0000 | [diff] [blame] | 170 | not (noprefix and word[:n+1] == noprefix)): |
Martin Panter | 6fe3926 | 2015-11-13 23:54:02 +0000 | [diff] [blame] | 171 | match = "%s.%s" % (expr, word) |
Martin Panter | f4ad5f5 | 2015-11-13 23:48:17 +0000 | [diff] [blame] | 172 | try: |
| 173 | val = getattr(thisobject, word) |
| 174 | except Exception: |
Martin Panter | 6fe3926 | 2015-11-13 23:54:02 +0000 | [diff] [blame] | 175 | pass # Include even if attribute not set |
| 176 | else: |
| 177 | match = self._callable_postfix(val, match) |
| 178 | matches.append(match) |
Serhiy Storchaka | ab82422 | 2015-09-27 13:43:50 +0300 | [diff] [blame] | 179 | if matches or not noprefix: |
| 180 | break |
| 181 | if noprefix == '_': |
| 182 | noprefix = '__' |
| 183 | else: |
| 184 | noprefix = None |
| 185 | matches.sort() |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 186 | return matches |
Guido van Rossum | 2781fbe | 1997-09-26 22:04:56 +0000 | [diff] [blame] | 187 | |
Guido van Rossum | 4e20de5 | 1999-10-26 13:09:08 +0000 | [diff] [blame] | 188 | def get_class_members(klass): |
| 189 | ret = dir(klass) |
| 190 | if hasattr(klass,'__bases__'): |
| 191 | for base in klass.__bases__: |
| 192 | ret = ret + get_class_members(base) |
| 193 | return ret |
| 194 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 195 | try: |
| 196 | import readline |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 197 | except ImportError: |
Yury Selivanov | 46f7785 | 2016-02-04 14:00:26 -0500 | [diff] [blame] | 198 | _readline_available = False |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 199 | else: |
| 200 | readline.set_completer(Completer().complete) |
Antoine Pitrou | dcedaf6 | 2013-07-31 23:14:08 +0200 | [diff] [blame] | 201 | # Release references early at shutdown (the readline module's |
| 202 | # contents are quasi-immortal, and the completer function holds a |
| 203 | # reference to globals). |
| 204 | atexit.register(lambda: readline.set_completer(None)) |
Yury Selivanov | 46f7785 | 2016-02-04 14:00:26 -0500 | [diff] [blame] | 205 | _readline_available = True |