blob: 96abad028374faca3a8fc462d376017d944e32ae [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 Rossum4e20de51999-10-26 13:09:08 +00004 object=eval(expr, __main__.__dict__)
5 words = dir(object)
6 if hasattr(object,'__class__'):
7 words.append('__class__')
8 words=words+get_class_members(object.__class__)
Guido van Rossum2781fbe1997-09-26 22:04:56 +00009completes keywords, built-ins and globals in __main__; when completing
10NAME.NAME..., it evaluates (!) the expression up to the last dot and
11completes its attributes.
12
13It's very cool to do "import string" type "string.", hit the
14completion key (twice), and see the list of names defined by the
Guido van Rossum4e20de51999-10-26 13:09:08 +000015
16def get_class_members(klass):
17 ret=dir(klass)
18 if hasattr(klass,'__bases__'):
19 for base in klass.__bases__:
20 ret=ret + get_class_members(base)
21 return ret
Guido van Rossum2781fbe1997-09-26 22:04:56 +000022string module!
23
24Tip: to use the tab key as the completion key, call
25
26 readline.parse_and_bind("tab: complete")
27
28Notes:
29
30- Exceptions raised by the completer function are *ignored* (and
31generally cause the completion to fail). This is a feature -- since
32readline sets the tty device in raw (or cbreak) mode, printing a
33traceback wouldn't work well without some complicated hoopla to save,
34reset and restore the tty state.
35
36- The evaluation of the NAME.NAME... form may cause arbitrary
37application defined code to be executed if an object with a
38__getattr__ hook is found. Since it is the responsibility of the
39application (or the user) to enable this feature, I consider this an
40acceptable risk. More complicated expressions (e.g. function calls or
41indexing operations) are *not* evaluated.
42
43- GNU readline is also used by the built-in functions input() and
44raw_input(), and thus these also benefit/suffer from the completer
45features. Clearly an interactive application can benefit by
46specifying its own completer function and using raw_input() for all
47its input.
48
49- When the original stdin is not a tty device, GNU readline is never
50used, and this module (and the readline module) are silently inactive.
51
52"""
53
54import readline
Guido van Rossum2781fbe1997-09-26 22:04:56 +000055import __builtin__
56import __main__
Guido van Rossum2781fbe1997-09-26 22:04:56 +000057
58class Completer:
59
60 def complete(self, text, state):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000061 """Return the next possible completion for 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000062
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000063 This is called successively with state == 0, 1, 2, ... until it
64 returns None. The completion should begin with 'text'.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000065
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000066 """
67 if state == 0:
68 if "." in text:
69 self.matches = self.attr_matches(text)
70 else:
71 self.matches = self.global_matches(text)
Guido van Rossumd458faa1998-06-12 19:42:14 +000072 try:
73 return self.matches[state]
74 except IndexError:
75 return None
Guido van Rossum2781fbe1997-09-26 22:04:56 +000076
77 def global_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000078 """Compute matches when text is a simple name.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000079
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000080 Return a list of all keywords, built-in functions and names
81 currently defines in __main__ that match.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000082
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000083 """
84 import keyword
85 matches = []
86 n = len(text)
87 for list in [keyword.kwlist,
88 __builtin__.__dict__.keys(),
89 __main__.__dict__.keys()]:
90 for word in list:
91 if word[:n] == text:
92 matches.append(word)
93 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +000094
95 def attr_matches(self, text):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000096 """Compute matches when text contains a dot.
Guido van Rossum2781fbe1997-09-26 22:04:56 +000097
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000098 Assuming the text is of the form NAME.NAME....[NAME], and is
99 evaluabable in the globals of __main__, it will be evaluated
100 and its attributes (as revealed by dir()) are used as possible
Guido van Rossum4e20de51999-10-26 13:09:08 +0000101 completions. (For class instances, class members are are also
102 considered.)
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000103
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000104 WARNING: this can still invoke arbitrary C code, if an object
105 with a __getattr__ hook is evaluated.
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000106
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000107 """
108 import re
109 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
110 if not m:
111 return
112 expr, attr = m.group(1, 3)
Guido van Rossum4e20de51999-10-26 13:09:08 +0000113 object = eval(expr, __main__.__dict__)
114 words = dir(object)
115 if hasattr(object,'__class__'):
116 words.append('__class__')
117 words = words + get_class_members(object.__class__)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000118 matches = []
119 n = len(attr)
120 for word in words:
121 if word[:n] == attr:
122 matches.append("%s.%s" % (expr, word))
123 return matches
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000124
Guido van Rossum4e20de51999-10-26 13:09:08 +0000125def get_class_members(klass):
126 ret = dir(klass)
127 if hasattr(klass,'__bases__'):
128 for base in klass.__bases__:
129 ret = ret + get_class_members(base)
130 return ret
131
Guido van Rossum2781fbe1997-09-26 22:04:56 +0000132readline.set_completer(Completer().complete)