blob: d3a443737a5297320e8ca6acaa0c7a6f496d8297 [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
Georg Brandl1a3284e2007-12-02 09:40:06 +000032import builtins
Guido van Rossum2781fbe1997-09-26 22:04:56 +000033import __main__
Guido van Rossum2781fbe1997-09-26 22:04:56 +000034
Skip Montanaro0de65802001-02-15 22:15:14 +000035__all__ = ["Completer"]
36
Guido van Rossum2781fbe1997-09-26 22:04:56 +000037class Completer:
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000038 def __init__(self, namespace = None):
39 """Create a new completer for the command line.
40
41 Completer([namespace]) -> completer instance.
42
43 If unspecified, the default namespace where completions are performed
44 is __main__ (technically, __main__.__dict__). Namespaces should be
45 given as dictionaries.
46
47 Completer instances should be used as the completion mechanism of
48 readline via the set_completer() call:
49
50 readline.set_completer(Completer(my_namespace).complete)
51 """
Tim Peters863ac442002-04-16 01:38:40 +000052
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000053 if namespace and not isinstance(namespace, dict):
Collin Winterce36ad82007-08-30 01:19:48 +000054 raise TypeError('namespace must be a dictionary')
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000055
56 # Don't bind to namespace quite yet, but flag whether the user wants a
57 # specific namespace or to use __main__.__dict__. This will allow us
58 # to bind to __main__.__dict__ at completion time, not now.
59 if namespace is None:
60 self.use_main_ns = 1
61 else:
62 self.use_main_ns = 0
63 self.namespace = namespace
Guido van Rossum2781fbe1997-09-26 22:04:56 +000064
65 def complete(self, text, state):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000066 """Return the next possible completion for 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000067
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000068 This is called successively with state == 0, 1, 2, ... until it
69 returns None. The completion should begin with 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000070
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000071 """
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000072 if self.use_main_ns:
73 self.namespace = __main__.__dict__
Tim Peters863ac442002-04-16 01:38:40 +000074
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000075 if state == 0:
76 if "." in text:
77 self.matches = self.attr_matches(text)
78 else:
79 self.matches = self.global_matches(text)
Guido van Rossumd458faa1998-06-12 19:42:14 +000080 try:
81 return self.matches[state]
82 except IndexError:
83 return None
Guido van Rossum2781fbe1997-09-26 22:04:56 +000084
Benjamin Peterson41181742008-07-02 20:22:54 +000085 def _callable_postfix(self, val, word):
Florent Xicluna5d1155c2011-10-28 14:45:05 +020086 if callable(val):
Benjamin Peterson41181742008-07-02 20:22:54 +000087 word = word + "("
88 return word
89
Guido van Rossum2781fbe1997-09-26 22:04:56 +000090 def global_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000091 """Compute matches when text is a simple name.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000092
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000093 Return a list of all keywords, built-in functions and names currently
94 defined in self.namespace that match.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000095
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000096 """
97 import keyword
98 matches = []
99 n = len(text)
Benjamin Peterson41181742008-07-02 20:22:54 +0000100 for word in keyword.kwlist:
101 if word[:n] == text:
102 matches.append(word)
103 for nspace in [builtins.__dict__, self.namespace]:
104 for word, val in nspace.items():
Benjamin Petersonf3854852008-07-05 20:59:18 +0000105 if word[:n] == text and word != "__builtins__":
Benjamin Peterson41181742008-07-02 20:22:54 +0000106 matches.append(self._callable_postfix(val, word))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000107 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000108
109 def attr_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000110 """Compute matches when text contains a dot.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000111
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000112 Assuming the text is of the form NAME.NAME....[NAME], and is
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000113 evaluatable in self.namespace, it will be evaluated and its attributes
114 (as revealed by dir()) are used as possible completions. (For class
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000115 instances, class members are also considered.)
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000116
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000117 WARNING: this can still invoke arbitrary C code, if an object
118 with a __getattr__ hook is evaluated.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000119
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000120 """
121 import re
122 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
123 if not m:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000124 return []
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000125 expr, attr = m.group(1, 3)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000126 try:
Benjamin Peterson095c1192008-07-21 16:32:10 +0000127 thisobject = eval(expr, self.namespace)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000128 except Exception:
129 return []
Benjamin Peterson095c1192008-07-21 16:32:10 +0000130
131 # get the content of the object, except __builtins__
132 words = dir(thisobject)
133 if "__builtins__" in words:
134 words.remove("__builtins__")
135
136 if hasattr(thisobject, '__class__'):
Guido van Rossum4e20de51999-10-26 13:09:08 +0000137 words.append('__class__')
Benjamin Peterson095c1192008-07-21 16:32:10 +0000138 words.extend(get_class_members(thisobject.__class__))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 matches = []
140 n = len(attr)
141 for word in words:
Benjamin Peterson095c1192008-07-21 16:32:10 +0000142 if word[:n] == attr and hasattr(thisobject, word):
143 val = getattr(thisobject, word)
Benjamin Peterson41181742008-07-02 20:22:54 +0000144 word = self._callable_postfix(val, "%s.%s" % (expr, word))
145 matches.append(word)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000146 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000147
Guido van Rossum4e20de51999-10-26 13:09:08 +0000148def get_class_members(klass):
149 ret = dir(klass)
150 if hasattr(klass,'__bases__'):
151 for base in klass.__bases__:
152 ret = ret + get_class_members(base)
153 return ret
154
Thomas Wouters477c8d52006-05-27 19:21:47 +0000155try:
156 import readline
157except ImportError:
158 pass
159else:
160 readline.set_completer(Completer().complete)