blob: 6eb77f97e13250a09bf17aa585833e36d9dc3ceb [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
Guido van Rossum2781fbe1997-09-26 22:04:56 +000031- When the original stdin is not a tty device, GNU readline is never
32used, and this module (and the readline module) are silently inactive.
33
34"""
35
36import readline
Guido van Rossum2781fbe1997-09-26 22:04:56 +000037import __builtin__
38import __main__
Guido van Rossum2781fbe1997-09-26 22:04:56 +000039
Skip Montanaro0de65802001-02-15 22:15:14 +000040__all__ = ["Completer"]
41
Guido van Rossum2781fbe1997-09-26 22:04:56 +000042class Completer:
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000043 def __init__(self, namespace = None):
44 """Create a new completer for the command line.
45
46 Completer([namespace]) -> completer instance.
47
48 If unspecified, the default namespace where completions are performed
49 is __main__ (technically, __main__.__dict__). Namespaces should be
50 given as dictionaries.
51
52 Completer instances should be used as the completion mechanism of
53 readline via the set_completer() call:
54
55 readline.set_completer(Completer(my_namespace).complete)
56 """
Tim Peters863ac442002-04-16 01:38:40 +000057
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000058 if namespace and not isinstance(namespace, dict):
59 raise TypeError,'namespace must be a dictionary'
60
61 # Don't bind to namespace quite yet, but flag whether the user wants a
62 # specific namespace or to use __main__.__dict__. This will allow us
63 # to bind to __main__.__dict__ at completion time, not now.
64 if namespace is None:
65 self.use_main_ns = 1
66 else:
67 self.use_main_ns = 0
68 self.namespace = namespace
Guido van Rossum2781fbe1997-09-26 22:04:56 +000069
70 def complete(self, text, state):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000071 """Return the next possible completion for 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000072
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000073 This is called successively with state == 0, 1, 2, ... until it
74 returns None. The completion should begin with 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000075
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000076 """
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000077 if self.use_main_ns:
78 self.namespace = __main__.__dict__
Tim Peters863ac442002-04-16 01:38:40 +000079
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000080 if state == 0:
81 if "." in text:
82 self.matches = self.attr_matches(text)
83 else:
84 self.matches = self.global_matches(text)
Guido van Rossumd458faa1998-06-12 19:42:14 +000085 try:
86 return self.matches[state]
87 except IndexError:
88 return None
Guido van Rossum2781fbe1997-09-26 22:04:56 +000089
90 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)
100 for list in [keyword.kwlist,
Raymond Hettingere0d49722002-06-02 18:55:56 +0000101 __builtin__.__dict__,
102 self.namespace]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000103 for word in list:
Fred Drake46bd9a62000-05-31 14:31:00 +0000104 if word[:n] == text and word != "__builtins__":
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000105 matches.append(word)
106 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000107
108 def attr_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000109 """Compute matches when text contains a dot.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000110
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 Assuming the text is of the form NAME.NAME....[NAME], and is
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000112 evaluatable in self.namespace, it will be evaluated and its attributes
113 (as revealed by dir()) are used as possible completions. (For class
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000114 instances, class members are also considered.)
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000115
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000116 WARNING: this can still invoke arbitrary C code, if an object
117 with a __getattr__ hook is evaluated.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000118
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000119 """
120 import re
121 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
122 if not m:
123 return
124 expr, attr = m.group(1, 3)
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000125 object = eval(expr, self.namespace)
Guido van Rossum4e20de51999-10-26 13:09:08 +0000126 words = dir(object)
127 if hasattr(object,'__class__'):
128 words.append('__class__')
129 words = words + get_class_members(object.__class__)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000130 matches = []
131 n = len(attr)
132 for word in words:
Fred Drake46bd9a62000-05-31 14:31:00 +0000133 if word[:n] == attr and word != "__builtins__":
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000134 matches.append("%s.%s" % (expr, word))
135 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000136
Guido van Rossum4e20de51999-10-26 13:09:08 +0000137def get_class_members(klass):
138 ret = dir(klass)
139 if hasattr(klass,'__bases__'):
140 for base in klass.__bases__:
141 ret = ret + get_class_members(base)
142 return ret
143
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000144readline.set_completer(Completer().complete)