1 """Word completion for GNU readline 2.0.
3 This requires the latest extension to the readline module (the
4 set_completer() function). When completing a simple identifier, it
5 completes keywords, built-ins and globals in __main__; when completing
6 NAME.NAME..., it evaluates (!) the expression up to the last dot and
7 completes its attributes.
9 It's very cool to do "import string" type "string.", hit the
10 completion key (twice), and see the list of names defined by the
13 Tip: to use the tab key as the completion key, call
15 readline.parse_and_bind("tab: complete")
19 - Exceptions raised by the completer function are *ignored* (and
20 generally cause the completion to fail). This is a feature -- since
21 readline sets the tty device in raw (or cbreak) mode, printing a
22 traceback wouldn't work well without some complicated hoopla to save,
23 reset and restore the tty state.
25 - The evaluation of the NAME.NAME... form may cause arbitrary
26 application defined code to be executed if an object with a
27 __getattr__ hook is found. Since it is the responsibility of the
28 application (or the user) to enable this feature, I consider this an
29 acceptable risk. More complicated expressions (e.g. function calls or
30 indexing operations) are *not* evaluated.
32 - GNU readline is also used by the built-in functions input() and
33 raw_input(), and thus these also benefit/suffer from the completer
34 features. Clearly an interactive application can benefit by
35 specifying its own completer function and using raw_input() for all
38 - When the original stdin is not a tty device, GNU readline is never
39 used, and this module (and the readline module) are silently inactive.
49 def complete(self
, text
, state
):
50 """Return the next possible completion for 'text'.
52 This is called successively with state == 0, 1, 2, ... until it
53 returns None. The completion should begin with 'text'.
58 self
.matches
= self
.attr_matches(text
)
60 self
.matches
= self
.global_matches(text
)
62 return self
.matches
[state
]
66 def global_matches(self
, text
):
67 """Compute matches when text is a simple name.
69 Return a list of all keywords, built-in functions and names
70 currently defines in __main__ that match.
76 for list in [keyword
.kwlist
,
77 __builtin__
.__dict
__.keys(),
78 __main__
.__dict
__.keys()]:
84 def attr_matches(self
, text
):
85 """Compute matches when text contains a dot.
87 Assuming the text is of the form NAME.NAME....[NAME], and is
88 evaluabable in the globals of __main__, it will be evaluated
89 and its attributes (as revealed by dir()) are used as possible
92 WARNING: this can still invoke arbitrary C code, if an object
93 with a __getattr__ hook is evaluated.
97 m
= re
.match(r
"(\w+(\.\w+)*)\.(\w*)", text
)
100 expr
, attr
= m
.group(1, 3)
101 words
= dir(eval(expr
, __main__
.__dict
__))
106 matches
.append("%s.%s" % (expr
, word
))
109 readline
.set_completer(Completer().complete
)