blob: 8cd21ed18a621d877b865c6525a57e2c818f0aaa [file] [log] [blame]
Guido van Rossuma11cccc1997-10-06 20:19:59 +00001"""Word completion for GNU readline 2.0.
2
3This requires the latest extension to the readline module (the
Guido van Rossuma11cccc1997-10-06 20:19:59 +00004completes keywords, built-ins and globals in __main__; when completing
5NAME.NAME..., it evaluates (!) the expression up to the last dot and
6completes its attributes.
7
8It's very cool to do "import string" type "string.", hit the
9completion key (twice), and see the list of names defined by the
10string module!
11
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 Rossuma11cccc1997-10-06 20:19:59 +000043import __builtin__
44import __main__
Guido van Rossuma11cccc1997-10-06 20:19:59 +000045
46class Completer:
47
48 def complete(self, text, state):
Guido van Rossum548703a1998-03-26 22:14:20 +000049 """Return the next possible completion for 'text'.
Guido van Rossuma11cccc1997-10-06 20:19:59 +000050
Guido van Rossum548703a1998-03-26 22:14:20 +000051 This is called successively with state == 0, 1, 2, ... until it
52 returns None. The completion should begin with 'text'.
Guido van Rossuma11cccc1997-10-06 20:19:59 +000053
Guido van Rossum548703a1998-03-26 22:14:20 +000054 """
55 if state == 0:
56 if "." in text:
57 self.matches = self.attr_matches(text)
58 else:
59 self.matches = self.global_matches(text)
Guido van Rossume03c0501998-08-12 02:38:11 +000060 try:
61 return self.matches[state]
62 except IndexError:
63 return None
Guido van Rossuma11cccc1997-10-06 20:19:59 +000064
65 def global_matches(self, text):
Guido van Rossum548703a1998-03-26 22:14:20 +000066 """Compute matches when text is a simple name.
Guido van Rossuma11cccc1997-10-06 20:19:59 +000067
Guido van Rossum548703a1998-03-26 22:14:20 +000068 Return a list of all keywords, built-in functions and names
69 currently defines in __main__ that match.
Guido van Rossuma11cccc1997-10-06 20:19:59 +000070
Guido van Rossum548703a1998-03-26 22:14:20 +000071 """
72 import keyword
73 matches = []
74 n = len(text)
75 for list in [keyword.kwlist,
76 __builtin__.__dict__.keys(),
77 __main__.__dict__.keys()]:
78 for word in list:
Guido van Rossum3e06ab12000-06-29 19:35:29 +000079 if word[:n] == text and word != "__builtins__":
Guido van Rossum548703a1998-03-26 22:14:20 +000080 matches.append(word)
81 return matches
Guido van Rossuma11cccc1997-10-06 20:19:59 +000082
83 def attr_matches(self, text):
Guido van Rossum548703a1998-03-26 22:14:20 +000084 """Compute matches when text contains a dot.
Guido van Rossuma11cccc1997-10-06 20:19:59 +000085
Guido van Rossum548703a1998-03-26 22:14:20 +000086 Assuming the text is of the form NAME.NAME....[NAME], and is
Thomas Wouters7e474022000-07-16 12:04:32 +000087 evaluatable in the globals of __main__, it will be evaluated
Guido van Rossum548703a1998-03-26 22:14:20 +000088 and its attributes (as revealed by dir()) are used as possible
Guido van Rossumaad67612000-05-08 17:31:04 +000089 completions. (For class instances, class members are are also
90 considered.)
Guido van Rossuma11cccc1997-10-06 20:19:59 +000091
Guido van Rossum548703a1998-03-26 22:14:20 +000092 WARNING: this can still invoke arbitrary C code, if an object
93 with a __getattr__ hook is evaluated.
Guido van Rossuma11cccc1997-10-06 20:19:59 +000094
Guido van Rossum548703a1998-03-26 22:14:20 +000095 """
96 import re
97 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
98 if not m:
99 return
100 expr, attr = m.group(1, 3)
Guido van Rossumaad67612000-05-08 17:31:04 +0000101 object = eval(expr, __main__.__dict__)
102 words = dir(object)
103 if hasattr(object,'__class__'):
104 words.append('__class__')
105 words = words + get_class_members(object.__class__)
Guido van Rossum548703a1998-03-26 22:14:20 +0000106 matches = []
107 n = len(attr)
108 for word in words:
Guido van Rossum3e06ab12000-06-29 19:35:29 +0000109 if word[:n] == attr and word != "__builtins__":
Guido van Rossum548703a1998-03-26 22:14:20 +0000110 matches.append("%s.%s" % (expr, word))
111 return matches
Guido van Rossuma11cccc1997-10-06 20:19:59 +0000112
Guido van Rossumaad67612000-05-08 17:31:04 +0000113def get_class_members(klass):
114 ret = dir(klass)
115 if hasattr(klass,'__bases__'):
116 for base in klass.__bases__:
117 ret = ret + get_class_members(base)
118 return ret
119
Guido van Rossuma11cccc1997-10-06 20:19:59 +0000120readline.set_completer(Completer().complete)