blob: 98b7930b32fab32e387500dee01c7a2a68eb2e3a [file] [log] [blame]
Georg Brandld8644072012-03-27 07:46:46 +02001"""Word completion for GNU readline.
Guido van Rossum2781fbe1997-09-26 22:04:56 +00002
Georg Brandld8644072012-03-27 07:46:46 +02003The completer completes keywords, built-ins and globals in a selectable
4namespace (which defaults to __main__); when completing NAME.NAME..., it
5evaluates (!) the expression up to the last dot and completes its attributes.
Guido van Rossum2781fbe1997-09-26 22:04:56 +00006
Georg Brandld8644072012-03-27 07:46:46 +02007It's very cool to do "import sys" type "sys.", hit the completion key (twice),
8and see the list of names defined by the sys module!
Guido van Rossum2781fbe1997-09-26 22:04:56 +00009
10Tip: to use the tab key as the completion key, call
11
12 readline.parse_and_bind("tab: complete")
13
14Notes:
15
Georg Brandld8644072012-03-27 07:46:46 +020016- 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 Rossum2781fbe1997-09-26 22:04:56 +000020
Georg Brandld8644072012-03-27 07:46:46 +020021- 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 Rossum2781fbe1997-09-26 22:04:56 +000026
Guido van Rossum2781fbe1997-09-26 22:04:56 +000027- When the original stdin is not a tty device, GNU readline is never
Georg Brandld8644072012-03-27 07:46:46 +020028 used, and this module (and the readline module) are silently inactive.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000029
30"""
31
Antoine Pitroudcedaf62013-07-31 23:14:08 +020032import atexit
Georg Brandl1a3284e2007-12-02 09:40:06 +000033import builtins
Rémi Lapeyrebd4a3f22020-06-30 15:48:15 +020034import inspect
Guido van Rossum2781fbe1997-09-26 22:04:56 +000035import __main__
Guido van Rossum2781fbe1997-09-26 22:04:56 +000036
Skip Montanaro0de65802001-02-15 22:15:14 +000037__all__ = ["Completer"]
38
Guido van Rossum2781fbe1997-09-26 22:04:56 +000039class Completer:
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000040 def __init__(self, namespace = None):
41 """Create a new completer for the command line.
42
43 Completer([namespace]) -> completer instance.
44
45 If unspecified, the default namespace where completions are performed
46 is __main__ (technically, __main__.__dict__). Namespaces should be
47 given as dictionaries.
48
49 Completer instances should be used as the completion mechanism of
50 readline via the set_completer() call:
51
52 readline.set_completer(Completer(my_namespace).complete)
53 """
Tim Peters863ac442002-04-16 01:38:40 +000054
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000055 if namespace and not isinstance(namespace, dict):
Collin Winterce36ad82007-08-30 01:19:48 +000056 raise TypeError('namespace must be a dictionary')
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000057
58 # Don't bind to namespace quite yet, but flag whether the user wants a
59 # specific namespace or to use __main__.__dict__. This will allow us
60 # to bind to __main__.__dict__ at completion time, not now.
61 if namespace is None:
62 self.use_main_ns = 1
63 else:
64 self.use_main_ns = 0
65 self.namespace = namespace
Guido van Rossum2781fbe1997-09-26 22:04:56 +000066
67 def complete(self, text, state):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000068 """Return the next possible completion for 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000069
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000070 This is called successively with state == 0, 1, 2, ... until it
71 returns None. The completion should begin with 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000072
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000073 """
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000074 if self.use_main_ns:
75 self.namespace = __main__.__dict__
Tim Peters863ac442002-04-16 01:38:40 +000076
Berker Peksagaaf61142015-07-28 00:06:31 +030077 if not text.strip():
78 if state == 0:
Yury Selivanov46f77852016-02-04 14:00:26 -050079 if _readline_available:
80 readline.insert_text('\t')
81 readline.redisplay()
82 return ''
83 else:
84 return '\t'
Berker Peksagaaf61142015-07-28 00:06:31 +030085 else:
86 return None
87
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000088 if state == 0:
89 if "." in text:
90 self.matches = self.attr_matches(text)
91 else:
92 self.matches = self.global_matches(text)
Guido van Rossumd458faa1998-06-12 19:42:14 +000093 try:
94 return self.matches[state]
95 except IndexError:
96 return None
Guido van Rossum2781fbe1997-09-26 22:04:56 +000097
Benjamin Peterson41181742008-07-02 20:22:54 +000098 def _callable_postfix(self, val, word):
Florent Xicluna5d1155c2011-10-28 14:45:05 +020099 if callable(val):
Rémi Lapeyrebd4a3f22020-06-30 15:48:15 +0200100 word += "("
101 try:
102 if not inspect.signature(val).parameters:
103 word += ")"
104 except ValueError:
105 pass
106
Benjamin Peterson41181742008-07-02 20:22:54 +0000107 return word
108
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000109 def global_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000110 """Compute matches when text is a simple name.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000111
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000112 Return a list of all keywords, built-in functions and names currently
113 defined in self.namespace that match.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000114
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000115 """
116 import keyword
117 matches = []
Martin Pantered929102015-11-23 23:50:26 +0000118 seen = {"__builtins__"}
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000119 n = len(text)
Benjamin Peterson41181742008-07-02 20:22:54 +0000120 for word in keyword.kwlist:
121 if word[:n] == text:
Martin Pantered929102015-11-23 23:50:26 +0000122 seen.add(word)
Serhiy Storchaka8ace8e92015-09-27 13:26:03 +0300123 if word in {'finally', 'try'}:
124 word = word + ':'
125 elif word not in {'False', 'None', 'True',
126 'break', 'continue', 'pass',
127 'else'}:
128 word = word + ' '
Benjamin Peterson41181742008-07-02 20:22:54 +0000129 matches.append(word)
Martin Pantered929102015-11-23 23:50:26 +0000130 for nspace in [self.namespace, builtins.__dict__]:
Benjamin Peterson41181742008-07-02 20:22:54 +0000131 for word, val in nspace.items():
Martin Pantered929102015-11-23 23:50:26 +0000132 if word[:n] == text and word not in seen:
133 seen.add(word)
Benjamin Peterson41181742008-07-02 20:22:54 +0000134 matches.append(self._callable_postfix(val, word))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000135 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000136
137 def attr_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000138 """Compute matches when text contains a dot.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000139
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000140 Assuming the text is of the form NAME.NAME....[NAME], and is
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300141 evaluable in self.namespace, it will be evaluated and its attributes
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000142 (as revealed by dir()) are used as possible completions. (For class
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000143 instances, class members are also considered.)
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000144
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000145 WARNING: this can still invoke arbitrary C code, if an object
146 with a __getattr__ hook is evaluated.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000147
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000148 """
149 import re
150 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
151 if not m:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000152 return []
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000153 expr, attr = m.group(1, 3)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000154 try:
Benjamin Peterson095c1192008-07-21 16:32:10 +0000155 thisobject = eval(expr, self.namespace)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000156 except Exception:
157 return []
Benjamin Peterson095c1192008-07-21 16:32:10 +0000158
159 # get the content of the object, except __builtins__
Serhiy Storchakaab824222015-09-27 13:43:50 +0300160 words = set(dir(thisobject))
161 words.discard("__builtins__")
Benjamin Peterson095c1192008-07-21 16:32:10 +0000162
163 if hasattr(thisobject, '__class__'):
Serhiy Storchakaab824222015-09-27 13:43:50 +0300164 words.add('__class__')
165 words.update(get_class_members(thisobject.__class__))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 matches = []
167 n = len(attr)
Serhiy Storchakaab824222015-09-27 13:43:50 +0300168 if attr == '':
169 noprefix = '_'
170 elif attr == '_':
171 noprefix = '__'
172 else:
173 noprefix = None
174 while True:
175 for word in words:
176 if (word[:n] == attr and
Martin Panterf4ad5f52015-11-13 23:48:17 +0000177 not (noprefix and word[:n+1] == noprefix)):
Martin Panter6fe39262015-11-13 23:54:02 +0000178 match = "%s.%s" % (expr, word)
Miss Islington (bot)d20f1092021-07-29 05:07:00 -0700179 if isinstance(getattr(type(thisobject), word, None),
180 property):
181 # bpo-44752: thisobject.word is a method decorated by
182 # `@property`. What follows applies a postfix if
183 # thisobject.word is callable, but know we know that
184 # this is not callable (because it is a property).
185 # Also, getattr(thisobject, word) will evaluate the
186 # property method, which is not desirable.
187 matches.append(match)
188 continue
Miss Islington (bot)f8e13e32021-07-29 08:44:42 -0700189 if (value := getattr(thisobject, word, None)) is not None:
190 matches.append(self._callable_postfix(value, match))
Martin Panter6fe39262015-11-13 23:54:02 +0000191 else:
Miss Islington (bot)f8e13e32021-07-29 08:44:42 -0700192 matches.append(match)
Serhiy Storchakaab824222015-09-27 13:43:50 +0300193 if matches or not noprefix:
194 break
195 if noprefix == '_':
196 noprefix = '__'
197 else:
198 noprefix = None
199 matches.sort()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000201
Guido van Rossum4e20de51999-10-26 13:09:08 +0000202def get_class_members(klass):
203 ret = dir(klass)
204 if hasattr(klass,'__bases__'):
205 for base in klass.__bases__:
206 ret = ret + get_class_members(base)
207 return ret
208
Thomas Wouters477c8d52006-05-27 19:21:47 +0000209try:
210 import readline
Brett Cannoncd171c82013-07-04 17:43:24 -0400211except ImportError:
Yury Selivanov46f77852016-02-04 14:00:26 -0500212 _readline_available = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000213else:
214 readline.set_completer(Completer().complete)
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200215 # Release references early at shutdown (the readline module's
216 # contents are quasi-immortal, and the completer function holds a
217 # reference to globals).
218 atexit.register(lambda: readline.set_completer(None))
Yury Selivanov46f77852016-02-04 14:00:26 -0500219 _readline_available = True