blob: 6e4bd12ad31d29bcfa0186c88c858ce20c931e71 [file] [log] [blame]
Georg Brandlc56e6672012-03-27 07:46:46 +02001"""Word completion for GNU readline.
Guido van Rossum2781fbe1997-09-26 22:04:56 +00002
Georg Brandlc56e6672012-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 Brandlc56e6672012-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 Brandlc56e6672012-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 Brandlc56e6672012-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
27- GNU readline is also used by the built-in functions input() and
28raw_input(), and thus these also benefit/suffer from the completer
29features. Clearly an interactive application can benefit by
30specifying its own completer function and using raw_input() for all
31its input.
32
33- When the original stdin is not a tty device, GNU readline is never
Georg Brandlc56e6672012-03-27 07:46:46 +020034 used, and this module (and the readline module) are silently inactive.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000035
36"""
37
Guido van Rossum2781fbe1997-09-26 22:04:56 +000038import __builtin__
39import __main__
Guido van Rossum2781fbe1997-09-26 22:04:56 +000040
Skip Montanaro0de65802001-02-15 22:15:14 +000041__all__ = ["Completer"]
42
Guido van Rossum2781fbe1997-09-26 22:04:56 +000043class Completer:
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000044 def __init__(self, namespace = None):
45 """Create a new completer for the command line.
46
47 Completer([namespace]) -> completer instance.
48
49 If unspecified, the default namespace where completions are performed
50 is __main__ (technically, __main__.__dict__). Namespaces should be
51 given as dictionaries.
52
53 Completer instances should be used as the completion mechanism of
54 readline via the set_completer() call:
55
56 readline.set_completer(Completer(my_namespace).complete)
57 """
Tim Peters863ac442002-04-16 01:38:40 +000058
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000059 if namespace and not isinstance(namespace, dict):
60 raise TypeError,'namespace must be a dictionary'
61
62 # Don't bind to namespace quite yet, but flag whether the user wants a
63 # specific namespace or to use __main__.__dict__. This will allow us
64 # to bind to __main__.__dict__ at completion time, not now.
65 if namespace is None:
66 self.use_main_ns = 1
67 else:
68 self.use_main_ns = 0
69 self.namespace = namespace
Guido van Rossum2781fbe1997-09-26 22:04:56 +000070
71 def complete(self, text, state):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000072 """Return the next possible completion for 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000073
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000074 This is called successively with state == 0, 1, 2, ... until it
75 returns None. The completion should begin with 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000076
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000077 """
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000078 if self.use_main_ns:
79 self.namespace = __main__.__dict__
Tim Peters863ac442002-04-16 01:38:40 +000080
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000081 if state == 0:
82 if "." in text:
83 self.matches = self.attr_matches(text)
84 else:
85 self.matches = self.global_matches(text)
Guido van Rossumd458faa1998-06-12 19:42:14 +000086 try:
87 return self.matches[state]
88 except IndexError:
89 return None
Guido van Rossum2781fbe1997-09-26 22:04:56 +000090
Facundo Batista66c52772008-07-02 16:52:55 +000091 def _callable_postfix(self, val, word):
Brett Cannon52597be2008-08-01 01:45:49 +000092 if hasattr(val, '__call__'):
Facundo Batista66c52772008-07-02 16:52:55 +000093 word = word + "("
94 return word
95
Guido van Rossum2781fbe1997-09-26 22:04:56 +000096 def global_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000097 """Compute matches when text is a simple name.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000098
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000099 Return a list of all keywords, built-in functions and names currently
100 defined in self.namespace that match.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000101
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000102 """
103 import keyword
104 matches = []
105 n = len(text)
Facundo Batista66c52772008-07-02 16:52:55 +0000106 for word in keyword.kwlist:
107 if word[:n] == text:
108 matches.append(word)
109 for nspace in [__builtin__.__dict__, self.namespace]:
110 for word, val in nspace.items():
Fred Drake46bd9a62000-05-31 14:31:00 +0000111 if word[:n] == text and word != "__builtins__":
Facundo Batista66c52772008-07-02 16:52:55 +0000112 matches.append(self._callable_postfix(val, word))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000113 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000114
115 def attr_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000116 """Compute matches when text contains a dot.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000117
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000118 Assuming the text is of the form NAME.NAME....[NAME], and is
Ezio Melottif5469cf2013-08-17 15:43:51 +0300119 evaluable in self.namespace, it will be evaluated and its attributes
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000120 (as revealed by dir()) are used as possible completions. (For class
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000121 instances, class members are also considered.)
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000122
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000123 WARNING: this can still invoke arbitrary C code, if an object
124 with a __getattr__ hook is evaluated.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000125
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000126 """
127 import re
128 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
129 if not m:
Georg Brandl42861382008-03-06 07:43:02 +0000130 return []
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000131 expr, attr = m.group(1, 3)
Georg Brandl627a6662008-05-11 21:03:42 +0000132 try:
Facundo Batistaf3f67592008-07-21 14:28:17 +0000133 thisobject = eval(expr, self.namespace)
Georg Brandl627a6662008-05-11 21:03:42 +0000134 except Exception:
135 return []
Facundo Batistaf3f67592008-07-21 14:28:17 +0000136
137 # get the content of the object, except __builtins__
138 words = dir(thisobject)
139 if "__builtins__" in words:
140 words.remove("__builtins__")
141
142 if hasattr(thisobject, '__class__'):
Guido van Rossum4e20de51999-10-26 13:09:08 +0000143 words.append('__class__')
Facundo Batistaf3f67592008-07-21 14:28:17 +0000144 words.extend(get_class_members(thisobject.__class__))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000145 matches = []
146 n = len(attr)
147 for word in words:
Facundo Batistaf3f67592008-07-21 14:28:17 +0000148 if word[:n] == attr and hasattr(thisobject, word):
149 val = getattr(thisobject, word)
Facundo Batista66c52772008-07-02 16:52:55 +0000150 word = self._callable_postfix(val, "%s.%s" % (expr, word))
151 matches.append(word)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000152 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000153
Guido van Rossum4e20de51999-10-26 13:09:08 +0000154def get_class_members(klass):
155 ret = dir(klass)
156 if hasattr(klass,'__bases__'):
157 for base in klass.__bases__:
158 ret = ret + get_class_members(base)
159 return ret
160
Georg Brandl3583cff2006-04-30 18:14:54 +0000161try:
162 import readline
163except ImportError:
164 pass
165else:
166 readline.set_completer(Completer().complete)