blob: 4f05ba30d77236282c2ce7a1f388ee935de32c0b [file] [log] [blame]
Guido van Rossum2781fbe1997-09-26 22:04:56 +00001"""Word completion for GNU readline 2.0.
2
3This requires the latest extension to the readline module (the
Guido van Rossum2781fbe1997-09-26 22:04:56 +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 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:
49
50 def complete(self, text, state):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000051 """Return the next possible completion for 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000052
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000053 This is called successively with state == 0, 1, 2, ... until it
54 returns None. The completion should begin with 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000055
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000056 """
57 if state == 0:
58 if "." in text:
59 self.matches = self.attr_matches(text)
60 else:
61 self.matches = self.global_matches(text)
Guido van Rossumd458faa1998-06-12 19:42:14 +000062 try:
63 return self.matches[state]
64 except IndexError:
65 return None
Guido van Rossum2781fbe1997-09-26 22:04:56 +000066
67 def global_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000068 """Compute matches when text is a simple name.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000069
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000070 Return a list of all keywords, built-in functions and names
71 currently defines in __main__ that match.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000072
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000073 """
74 import keyword
75 matches = []
76 n = len(text)
77 for list in [keyword.kwlist,
78 __builtin__.__dict__.keys(),
79 __main__.__dict__.keys()]:
80 for word in list:
Fred Drake46bd9a62000-05-31 14:31:00 +000081 if word[:n] == text and word != "__builtins__":
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000082 matches.append(word)
83 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +000084
85 def attr_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000086 """Compute matches when text contains a dot.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000087
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000088 Assuming the text is of the form NAME.NAME....[NAME], and is
Thomas Wouters7e474022000-07-16 12:04:32 +000089 evaluatable in the globals of __main__, it will be evaluated
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000090 and its attributes (as revealed by dir()) are used as possible
Guido van Rossum4e20de51999-10-26 13:09:08 +000091 completions. (For class instances, class members are are also
92 considered.)
Guido van Rossum2781fbe1997-09-26 22:04:56 +000093
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000094 WARNING: this can still invoke arbitrary C code, if an object
95 with a __getattr__ hook is evaluated.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000096
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000097 """
98 import re
99 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
100 if not m:
101 return
102 expr, attr = m.group(1, 3)
Guido van Rossum4e20de51999-10-26 13:09:08 +0000103 object = eval(expr, __main__.__dict__)
104 words = dir(object)
105 if hasattr(object,'__class__'):
106 words.append('__class__')
107 words = words + get_class_members(object.__class__)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000108 matches = []
109 n = len(attr)
110 for word in words:
Fred Drake46bd9a62000-05-31 14:31:00 +0000111 if word[:n] == attr and word != "__builtins__":
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000112 matches.append("%s.%s" % (expr, word))
113 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000114
Guido van Rossum4e20de51999-10-26 13:09:08 +0000115def get_class_members(klass):
116 ret = dir(klass)
117 if hasattr(klass,'__bases__'):
118 for base in klass.__bases__:
119 ret = ret + get_class_members(base)
120 return ret
121
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000122readline.set_completer(Completer().complete)