Added 'description' class attribute to every command class (to help the
[python/dscho.git] / Tools / idle / CallTips.py
blob04eccde0b401eaaf75a6a97efdc8e80d9c0ef364
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.uppercase + string.lowercase + string.digits):
80 # XXX - This needs to be moved to a better place
81 # so the "." attribute lookup code can also use it.
82 text = self.text
83 chars = text.get("insert linestart", "insert")
84 i = len(chars)
85 while i and chars[i-1] in wordchars:
86 i = i-1
87 word = chars[i:]
88 if word:
89 # How is this for a hack!
90 import sys, __main__
91 namespace = sys.modules.copy()
92 namespace.update(__main__.__dict__)
93 try:
94 return eval(word, namespace)
95 except:
96 pass
97 return None # Can't find an object.
99 def _find_constructor(class_ob):
100 # Given a class object, return a function object used for the
101 # constructor (ie, __init__() ) or None if we can't find one.
102 try:
103 return class_ob.__init__.im_func
104 except AttributeError:
105 for base in class_ob.__bases__:
106 rc = _find_constructor(base)
107 if rc is not None: return rc
108 return None
110 def get_arg_text(ob):
111 # Get a string describing the arguments for the given object.
112 argText = ""
113 if ob is not None:
114 argOffset = 0
115 if type(ob)==types.ClassType:
116 # Look for the highest __init__ in the class chain.
117 fob = _find_constructor(ob)
118 if fob is None:
119 fob = lambda: None
120 else:
121 argOffset = 1
122 elif type(ob)==types.MethodType:
123 # bit of a hack for methods - turn it into a function
124 # but we drop the "self" param.
125 fob = ob.im_func
126 argOffset = 1
127 else:
128 fob = ob
129 # Try and build one for Python defined functions
130 if type(fob) in [types.FunctionType, types.LambdaType]:
131 try:
132 realArgs = fob.func_code.co_varnames[argOffset:fob.func_code.co_argcount]
133 defaults = fob.func_defaults or []
134 defaults = list(map(lambda name: "=%s" % name, defaults))
135 defaults = [""] * (len(realArgs)-len(defaults)) + defaults
136 items = map(lambda arg, dflt: arg+dflt, realArgs, defaults)
137 if fob.func_code.co_flags & 0x4:
138 items.append("...")
139 if fob.func_code.co_flags & 0x8:
140 items.append("***")
141 argText = string.join(items , ", ")
142 argText = "(%s)" % argText
143 except:
144 pass
145 # See if we can use the docstring
146 if hasattr(ob, "__doc__") and ob.__doc__:
147 pos = string.find(ob.__doc__, "\n")
148 if pos<0 or pos>70: pos=70
149 if argText: argText = argText + "\n"
150 argText = argText + ob.__doc__[:pos]
152 return argText
154 #################################################
156 # Test code
158 if __name__=='__main__':
160 def t1(): "()"
161 def t2(a, b=None): "(a, b=None)"
162 def t3(a, *args): "(a, ...)"
163 def t4(*args): "(...)"
164 def t5(a, *args): "(a, ...)"
165 def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)"
167 class TC:
168 "(a=None, ...)"
169 def __init__(self, a=None, *b): "(a=None, ...)"
170 def t1(self): "()"
171 def t2(self, a, b=None): "(a, b=None)"
172 def t3(self, a, *args): "(a, ...)"
173 def t4(self, *args): "(...)"
174 def t5(self, a, *args): "(a, ...)"
175 def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)"
177 def test( tests ):
178 failed=[]
179 for t in tests:
180 expected = t.__doc__ + "\n" + t.__doc__
181 if get_arg_text(t) != expected:
182 failed.append(t)
183 print "%s - expected %s, but got %s" % (t, `expected`, `get_arg_text(t)`)
184 print "%d of %d tests failed" % (len(failed), len(tests))
186 tc = TC()
187 tests = t1, t2, t3, t4, t5, t6, \
188 TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6
190 test(tests)