This commit was manufactured by cvs2svn to create tag 'r222'.
[python/dscho.git] / Tools / idle / CallTips.py
blobdc25083e7eb85e2cffac7e3c75f0f69f5685a68b
1 # CallTips.py - An IDLE extension that provides "Call Tips" - ie, a floating window that
2 # displays parameter information as you open parens.
4 import string
5 import sys
6 import types
8 class CallTips:
10 menudefs = [
13 keydefs = {
14 '<<paren-open>>': ['<Key-parenleft>'],
15 '<<paren-close>>': ['<Key-parenright>'],
16 '<<check-calltip-cancel>>': ['<KeyRelease>'],
17 '<<calltip-cancel>>': ['<ButtonPress>', '<Key-Escape>'],
20 windows_keydefs = {
23 unix_keydefs = {
26 def __init__(self, editwin):
27 self.editwin = editwin
28 self.text = editwin.text
29 self.calltip = None
30 if hasattr(self.text, "make_calltip_window"):
31 self._make_calltip_window = self.text.make_calltip_window
32 else:
33 self._make_calltip_window = self._make_tk_calltip_window
35 def close(self):
36 self._make_calltip_window = None
38 # Makes a Tk based calltip window. Used by IDLE, but not Pythonwin.
39 # See __init__ above for how this is used.
40 def _make_tk_calltip_window(self):
41 import CallTipWindow
42 return CallTipWindow.CallTip(self.text)
44 def _remove_calltip_window(self):
45 if self.calltip:
46 self.calltip.hidetip()
47 self.calltip = None
49 def paren_open_event(self, event):
50 self._remove_calltip_window()
51 arg_text = get_arg_text(self.get_object_at_cursor())
52 if arg_text:
53 self.calltip_start = self.text.index("insert")
54 self.calltip = self._make_calltip_window()
55 self.calltip.showtip(arg_text)
56 return "" #so the event is handled normally.
58 def paren_close_event(self, event):
59 # Now just hides, but later we should check if other
60 # paren'd expressions remain open.
61 self._remove_calltip_window()
62 return "" #so the event is handled normally.
64 def check_calltip_cancel_event(self, event):
65 if self.calltip:
66 # If we have moved before the start of the calltip,
67 # or off the calltip line, then cancel the tip.
68 # (Later need to be smarter about multi-line, etc)
69 if self.text.compare("insert", "<=", self.calltip_start) or \
70 self.text.compare("insert", ">", self.calltip_start + " lineend"):
71 self._remove_calltip_window()
72 return "" #so the event is handled normally.
74 def calltip_cancel_event(self, event):
75 self._remove_calltip_window()
76 return "" #so the event is handled normally.
78 def get_object_at_cursor(self,
79 wordchars="._" + string.ascii_letters + string.digits):
80 # Usage of ascii_letters is necessary to avoid UnicodeErrors
81 # if chars contains non-ASCII.
83 # XXX - This needs to be moved to a better place
84 # so the "." attribute lookup code can also use it.
85 text = self.text
86 chars = text.get("insert linestart", "insert")
87 i = len(chars)
88 while i and chars[i-1] in wordchars:
89 i = i-1
90 word = chars[i:]
91 if word:
92 # How is this for a hack!
93 import sys, __main__
94 namespace = sys.modules.copy()
95 namespace.update(__main__.__dict__)
96 try:
97 return eval(word, namespace)
98 except:
99 pass
100 return None # Can't find an object.
102 def _find_constructor(class_ob):
103 # Given a class object, return a function object used for the
104 # constructor (ie, __init__() ) or None if we can't find one.
105 try:
106 return class_ob.__init__.im_func
107 except AttributeError:
108 for base in class_ob.__bases__:
109 rc = _find_constructor(base)
110 if rc is not None: return rc
111 return None
113 def get_arg_text(ob):
114 # Get a string describing the arguments for the given object.
115 argText = ""
116 if ob is not None:
117 argOffset = 0
118 if type(ob)==types.ClassType:
119 # Look for the highest __init__ in the class chain.
120 fob = _find_constructor(ob)
121 if fob is None:
122 fob = lambda: None
123 else:
124 argOffset = 1
125 elif type(ob)==types.MethodType:
126 # bit of a hack for methods - turn it into a function
127 # but we drop the "self" param.
128 fob = ob.im_func
129 argOffset = 1
130 else:
131 fob = ob
132 # Try and build one for Python defined functions
133 if type(fob) in [types.FunctionType, types.LambdaType]:
134 try:
135 realArgs = fob.func_code.co_varnames[argOffset:fob.func_code.co_argcount]
136 defaults = fob.func_defaults or []
137 defaults = list(map(lambda name: "=%s" % name, defaults))
138 defaults = [""] * (len(realArgs)-len(defaults)) + defaults
139 items = map(lambda arg, dflt: arg+dflt, realArgs, defaults)
140 if fob.func_code.co_flags & 0x4:
141 items.append("...")
142 if fob.func_code.co_flags & 0x8:
143 items.append("***")
144 argText = string.join(items , ", ")
145 argText = "(%s)" % argText
146 except:
147 pass
148 # See if we can use the docstring
149 doc = getattr(ob, "__doc__", "")
150 if doc:
151 while doc[:1] in " \t\n":
152 doc = doc[1:]
153 pos = doc.find("\n")
154 if pos < 0 or pos > 70:
155 pos = 70
156 if argText:
157 argText += "\n"
158 argText += doc[:pos]
160 return argText
162 #################################################
164 # Test code
166 if __name__=='__main__':
168 def t1(): "()"
169 def t2(a, b=None): "(a, b=None)"
170 def t3(a, *args): "(a, ...)"
171 def t4(*args): "(...)"
172 def t5(a, *args): "(a, ...)"
173 def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)"
175 class TC:
176 "(a=None, ...)"
177 def __init__(self, a=None, *b): "(a=None, ...)"
178 def t1(self): "()"
179 def t2(self, a, b=None): "(a, b=None)"
180 def t3(self, a, *args): "(a, ...)"
181 def t4(self, *args): "(...)"
182 def t5(self, a, *args): "(a, ...)"
183 def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)"
185 def test( tests ):
186 failed=[]
187 for t in tests:
188 expected = t.__doc__ + "\n" + t.__doc__
189 if get_arg_text(t) != expected:
190 failed.append(t)
191 print "%s - expected %s, but got %s" % (t, `expected`, `get_arg_text(t)`)
192 print "%d of %d tests failed" % (len(failed), len(tests))
194 tc = TC()
195 tests = t1, t2, t3, t4, t5, t6, \
196 TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6
198 test(tests)