blob: 53de2969df57ca67a0e0d4933a647ffa62ccb466 [file] [log] [blame]
Guido van Rossum2781fbe1997-09-26 22:04:56 +00001"""Word completion for GNU readline 2.0.
2
Neil Schemenauerdbab3e32002-03-23 23:44:51 +00003This requires the latest extension to the readline module. The completer
4completes keywords, built-ins and globals in a selectable namespace (which
5defaults to __main__); when completing NAME.NAME..., it evaluates (!) the
6expression up to the last dot and completes its attributes.
Guido van Rossum2781fbe1997-09-26 22:04:56 +00007
Walter Dörwald65230a22002-06-03 15:58:32 +00008It's very cool to do "import sys" type "sys.", hit the
Guido van Rossum2781fbe1997-09-26 22:04:56 +00009completion key (twice), and see the list of names defined by the
Walter Dörwald65230a22002-06-03 15:58:32 +000010sys module!
Guido van Rossum2781fbe1997-09-26 22:04:56 +000011
12Tip: to use the tab key as the completion key, call
13
14 readline.parse_and_bind("tab: complete")
15
16Notes:
17
18- Exceptions raised by the completer function are *ignored* (and
19generally cause the completion to fail). This is a feature -- since
20readline sets the tty device in raw (or cbreak) mode, printing a
21traceback wouldn't work well without some complicated hoopla to save,
22reset and restore the tty state.
23
24- The evaluation of the NAME.NAME... form may cause arbitrary
25application defined code to be executed if an object with a
26__getattr__ hook is found. Since it is the responsibility of the
27application (or the user) to enable this feature, I consider this an
28acceptable risk. More complicated expressions (e.g. function calls or
29indexing operations) are *not* evaluated.
30
31- GNU readline is also used by the built-in functions input() and
32raw_input(), and thus these also benefit/suffer from the completer
33features. Clearly an interactive application can benefit by
34specifying its own completer function and using raw_input() for all
35its input.
36
37- When the original stdin is not a tty device, GNU readline is never
38used, and this module (and the readline module) are silently inactive.
39
40"""
41
Guido van Rossum2781fbe1997-09-26 22:04:56 +000042import __builtin__
43import __main__
Guido van Rossum2781fbe1997-09-26 22:04:56 +000044
Skip Montanaro0de65802001-02-15 22:15:14 +000045__all__ = ["Completer"]
46
Guido van Rossum2781fbe1997-09-26 22:04:56 +000047class Completer:
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000048 def __init__(self, namespace = None):
49 """Create a new completer for the command line.
50
51 Completer([namespace]) -> completer instance.
52
53 If unspecified, the default namespace where completions are performed
54 is __main__ (technically, __main__.__dict__). Namespaces should be
55 given as dictionaries.
56
57 Completer instances should be used as the completion mechanism of
58 readline via the set_completer() call:
59
60 readline.set_completer(Completer(my_namespace).complete)
61 """
Tim Peters863ac442002-04-16 01:38:40 +000062
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000063 if namespace and not isinstance(namespace, dict):
64 raise TypeError,'namespace must be a dictionary'
65
66 # Don't bind to namespace quite yet, but flag whether the user wants a
67 # specific namespace or to use __main__.__dict__. This will allow us
68 # to bind to __main__.__dict__ at completion time, not now.
69 if namespace is None:
70 self.use_main_ns = 1
71 else:
72 self.use_main_ns = 0
73 self.namespace = namespace
Guido van Rossum2781fbe1997-09-26 22:04:56 +000074
75 def complete(self, text, state):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000076 """Return the next possible completion for 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000077
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000078 This is called successively with state == 0, 1, 2, ... until it
79 returns None. The completion should begin with 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000080
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000081 """
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000082 if self.use_main_ns:
83 self.namespace = __main__.__dict__
Tim Peters863ac442002-04-16 01:38:40 +000084
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000085 if state == 0:
86 if "." in text:
87 self.matches = self.attr_matches(text)
88 else:
89 self.matches = self.global_matches(text)
Guido van Rossumd458faa1998-06-12 19:42:14 +000090 try:
91 return self.matches[state]
92 except IndexError:
93 return None
Guido van Rossum2781fbe1997-09-26 22:04:56 +000094
Facundo Batista66c52772008-07-02 16:52:55 +000095 def _callable_postfix(self, val, word):
Brett Cannon52597be2008-08-01 01:45:49 +000096 if hasattr(val, '__call__'):
Facundo Batista66c52772008-07-02 16:52:55 +000097 word = word + "("
98 return word
99
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000100 def global_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000101 """Compute matches when text is a simple name.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000102
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000103 Return a list of all keywords, built-in functions and names currently
104 defined in self.namespace that match.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000105
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000106 """
107 import keyword
108 matches = []
109 n = len(text)
Facundo Batista66c52772008-07-02 16:52:55 +0000110 for word in keyword.kwlist:
111 if word[:n] == text:
112 matches.append(word)
113 for nspace in [__builtin__.__dict__, self.namespace]:
114 for word, val in nspace.items():
Fred Drake46bd9a62000-05-31 14:31:00 +0000115 if word[:n] == text and word != "__builtins__":
Facundo Batista66c52772008-07-02 16:52:55 +0000116 matches.append(self._callable_postfix(val, word))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000117 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000118
119 def attr_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000120 """Compute matches when text contains a dot.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000121
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000122 Assuming the text is of the form NAME.NAME....[NAME], and is
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000123 evaluatable in self.namespace, it will be evaluated and its attributes
124 (as revealed by dir()) are used as possible completions. (For class
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000125 instances, class members are also considered.)
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000126
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000127 WARNING: this can still invoke arbitrary C code, if an object
128 with a __getattr__ hook is evaluated.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000129
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000130 """
131 import re
132 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
133 if not m:
Georg Brandl42861382008-03-06 07:43:02 +0000134 return []
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000135 expr, attr = m.group(1, 3)
Georg Brandl627a6662008-05-11 21:03:42 +0000136 try:
Facundo Batistaf3f67592008-07-21 14:28:17 +0000137 thisobject = eval(expr, self.namespace)
Georg Brandl627a6662008-05-11 21:03:42 +0000138 except Exception:
139 return []
Facundo Batistaf3f67592008-07-21 14:28:17 +0000140
141 # get the content of the object, except __builtins__
142 words = dir(thisobject)
143 if "__builtins__" in words:
144 words.remove("__builtins__")
145
146 if hasattr(thisobject, '__class__'):
Guido van Rossum4e20de51999-10-26 13:09:08 +0000147 words.append('__class__')
Facundo Batistaf3f67592008-07-21 14:28:17 +0000148 words.extend(get_class_members(thisobject.__class__))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000149 matches = []
150 n = len(attr)
151 for word in words:
Facundo Batistaf3f67592008-07-21 14:28:17 +0000152 if word[:n] == attr and hasattr(thisobject, word):
153 val = getattr(thisobject, word)
Facundo Batista66c52772008-07-02 16:52:55 +0000154 word = self._callable_postfix(val, "%s.%s" % (expr, word))
155 matches.append(word)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000156 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000157
Guido van Rossum4e20de51999-10-26 13:09:08 +0000158def get_class_members(klass):
159 ret = dir(klass)
160 if hasattr(klass,'__bases__'):
161 for base in klass.__bases__:
162 ret = ret + get_class_members(base)
163 return ret
164
Georg Brandl3583cff2006-04-30 18:14:54 +0000165try:
166 import readline
167except ImportError:
168 pass
169else:
170 readline.set_completer(Completer().complete)