blob: 1d291670f148bfa8d6fbaa3b0fc91d0d604d2e56 [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
42import readline
Guido van Rossum2781fbe1997-09-26 22:04:56 +000043import __builtin__
44import __main__
Guido van Rossum2781fbe1997-09-26 22:04:56 +000045
Skip Montanaro0de65802001-02-15 22:15:14 +000046__all__ = ["Completer"]
47
Guido van Rossum2781fbe1997-09-26 22:04:56 +000048class Completer:
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000049 def __init__(self, namespace = None):
50 """Create a new completer for the command line.
51
52 Completer([namespace]) -> completer instance.
53
54 If unspecified, the default namespace where completions are performed
55 is __main__ (technically, __main__.__dict__). Namespaces should be
56 given as dictionaries.
57
58 Completer instances should be used as the completion mechanism of
59 readline via the set_completer() call:
60
61 readline.set_completer(Completer(my_namespace).complete)
62 """
Tim Peters863ac442002-04-16 01:38:40 +000063
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000064 if namespace and not isinstance(namespace, dict):
65 raise TypeError,'namespace must be a dictionary'
66
67 # Don't bind to namespace quite yet, but flag whether the user wants a
68 # specific namespace or to use __main__.__dict__. This will allow us
69 # to bind to __main__.__dict__ at completion time, not now.
70 if namespace is None:
71 self.use_main_ns = 1
72 else:
73 self.use_main_ns = 0
74 self.namespace = namespace
Guido van Rossum2781fbe1997-09-26 22:04:56 +000075
76 def complete(self, text, state):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000077 """Return the next possible completion for 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000078
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000079 This is called successively with state == 0, 1, 2, ... until it
80 returns None. The completion should begin with 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000081
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000082 """
Neil Schemenauerdbab3e32002-03-23 23:44:51 +000083 if self.use_main_ns:
84 self.namespace = __main__.__dict__
Tim Peters863ac442002-04-16 01:38:40 +000085
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000086 if state == 0:
87 if "." in text:
88 self.matches = self.attr_matches(text)
89 else:
90 self.matches = self.global_matches(text)
Guido van Rossumd458faa1998-06-12 19:42:14 +000091 try:
92 return self.matches[state]
93 except IndexError:
94 return None
Guido van Rossum2781fbe1997-09-26 22:04:56 +000095
96 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)
106 for list in [keyword.kwlist,
Raymond Hettingere0d49722002-06-02 18:55:56 +0000107 __builtin__.__dict__,
108 self.namespace]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000109 for word in list:
Fred Drake46bd9a62000-05-31 14:31:00 +0000110 if word[:n] == text and word != "__builtins__":
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 matches.append(word)
112 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000113
114 def attr_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000115 """Compute matches when text contains a dot.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000116
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000117 Assuming the text is of the form NAME.NAME....[NAME], and is
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000118 evaluatable in self.namespace, it will be evaluated and its attributes
119 (as revealed by dir()) are used as possible completions. (For class
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000120 instances, class members are also considered.)
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000121
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000122 WARNING: this can still invoke arbitrary C code, if an object
123 with a __getattr__ hook is evaluated.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000124
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000125 """
126 import re
127 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
128 if not m:
129 return
130 expr, attr = m.group(1, 3)
Neil Schemenauerdbab3e32002-03-23 23:44:51 +0000131 object = eval(expr, self.namespace)
Guido van Rossum4e20de51999-10-26 13:09:08 +0000132 words = dir(object)
133 if hasattr(object,'__class__'):
134 words.append('__class__')
135 words = words + get_class_members(object.__class__)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000136 matches = []
137 n = len(attr)
138 for word in words:
Fred Drake46bd9a62000-05-31 14:31:00 +0000139 if word[:n] == attr and word != "__builtins__":
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000140 matches.append("%s.%s" % (expr, word))
141 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000142
Guido van Rossum4e20de51999-10-26 13:09:08 +0000143def get_class_members(klass):
144 ret = dir(klass)
145 if hasattr(klass,'__bases__'):
146 for base in klass.__bases__:
147 ret = ret + get_class_members(base)
148 return ret
149
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000150readline.set_completer(Completer().complete)