CallTips.py 6.46 KB
Newer Older
1 2 3
# CallTips.py - An IDLE extension that provides "Call Tips" - ie, a floating window that
# displays parameter information as you open parens.

4 5 6 7 8 9 10 11 12 13 14 15
import string
import sys
import types

class CallTips:

    menudefs = [
    ]

    keydefs = {
        '<<paren-open>>': ['<Key-parenleft>'],
        '<<paren-close>>': ['<Key-parenright>'],
16 17
        '<<check-calltip-cancel>>': ['<KeyRelease>'],
        '<<calltip-cancel>>': ['<ButtonPress>', '<Key-Escape>'],
18
    }
19

20 21 22 23 24 25 26 27 28 29 30 31 32 33
    windows_keydefs = {
    }

    unix_keydefs = {
    }

    def __init__(self, editwin):
        self.editwin = editwin
        self.text = editwin.text
        self.calltip = None
        if hasattr(self.text, "make_calltip_window"):
            self._make_calltip_window = self.text.make_calltip_window
        else:
            self._make_calltip_window = self._make_tk_calltip_window
34

35 36 37
    def close(self):
        self._make_calltip_window = None

38 39
    # Makes a Tk based calltip window.  Used by IDLE, but not Pythonwin.
    # See __init__ above for how this is used.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    def _make_tk_calltip_window(self):
        import CallTipWindow
        return CallTipWindow.CallTip(self.text)

    def _remove_calltip_window(self):
        if self.calltip:
            self.calltip.hidetip()
            self.calltip = None
        
    def paren_open_event(self, event):
        self._remove_calltip_window()
        arg_text = get_arg_text(self.get_object_at_cursor())
        if arg_text:
            self.calltip_start = self.text.index("insert")
            self.calltip = self._make_calltip_window()
            self.calltip.showtip(arg_text)
56
        return "" #so the event is handled normally.
57 58 59 60 61

    def paren_close_event(self, event):
        # Now just hides, but later we should check if other
        # paren'd expressions remain open.
        self._remove_calltip_window()
62
        return "" #so the event is handled normally.
63 64 65 66 67 68 69 70 71

    def check_calltip_cancel_event(self, event):
        if self.calltip:
            # If we have moved before the start of the calltip,
            # or off the calltip line, then cancel the tip.
            # (Later need to be smarter about multi-line, etc)
            if self.text.compare("insert", "<=", self.calltip_start) or \
               self.text.compare("insert", ">", self.calltip_start + " lineend"):
                self._remove_calltip_window()
72 73 74 75 76 77
        return "" #so the event is handled normally.

    def calltip_cancel_event(self, event):
        self._remove_calltip_window()
        return "" #so the event is handled normally.

78 79
    def get_object_at_cursor(self,
                             wordchars="._" + string.uppercase + string.lowercase + string.digits):
80 81
        # XXX - This needs to be moved to a better place
        # so the "." attribute lookup code can also use it.
82
        text = self.text
83 84 85 86 87 88 89
        chars = text.get("insert linestart", "insert")
        i = len(chars)
        while i and chars[i-1] in wordchars:
            i = i-1
        word = chars[i:]
        if word:
            # How is this for a hack!
90 91 92 93 94 95 96 97
            import sys, __main__
            namespace = sys.modules.copy()
            namespace.update(__main__.__dict__)
            try:
                    return eval(word, namespace)
            except:
                    pass
        return None # Can't find an object.
98

99 100 101 102 103 104 105 106 107 108 109
def _find_constructor(class_ob):
    # Given a class object, return a function object used for the
    # constructor (ie, __init__() ) or None if we can't find one.
    try:
        return class_ob.__init__.im_func
    except AttributeError:
        for base in class_ob.__bases__:
            rc = _find_constructor(base)
            if rc is not None: return rc
    return None

110 111 112 113 114
def get_arg_text(ob):
    # Get a string describing the arguments for the given object.
    argText = ""
    if ob is not None:
        argOffset = 0
115 116 117 118 119 120 121 122 123 124 125
        if type(ob)==types.ClassType:
            # Look for the highest __init__ in the class chain.
            fob = _find_constructor(ob)
            if fob is None:
                fob = lambda: None
            else:
                argOffset = 1
        elif type(ob)==types.MethodType:
            # bit of a hack for methods - turn it into a function
            # but we drop the "self" param.
            fob = ob.im_func
126
            argOffset = 1
127 128
        else:
            fob = ob
129
        # Try and build one for Python defined functions
130
        if type(fob) in [types.FunctionType, types.LambdaType]:
131
            try:
132 133
                realArgs = fob.func_code.co_varnames[argOffset:fob.func_code.co_argcount]
                defaults = fob.func_defaults or []
134 135
                defaults = list(map(lambda name: "=%s" % name, defaults))
                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 143 144
                argText = "(%s)" % argText
            except:
                pass
145
        # See if we can use the docstring
146
        if hasattr(ob, "__doc__") and ob.__doc__:
147 148
            pos = string.find(ob.__doc__, "\n")
            if pos<0 or pos>70: pos=70
149 150
            if argText: argText = argText + "\n"
            argText = argText + ob.__doc__[:pos]
151 152 153 154 155 156 157 158 159 160 161 162 163 164

    return argText

#################################################
#
# Test code
#
if __name__=='__main__':

    def t1(): "()"
    def t2(a, b=None): "(a, b=None)"
    def t3(a, *args): "(a, ...)"
    def t4(*args): "(...)"
    def t5(a, *args): "(a, ...)"
165
    def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)"
166 167

    class TC:
168 169
        "(a=None, ...)"
        def __init__(self, a=None, *b): "(a=None, ...)"
170 171 172 173 174
        def t1(self): "()"
        def t2(self, a, b=None): "(a, b=None)"
        def t3(self, a, *args): "(a, ...)"
        def t4(self, *args): "(...)"
        def t5(self, a, *args): "(a, ...)"
175
        def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)"
176 177 178 179

    def test( tests ):
        failed=[]
        for t in tests:
180 181
            expected = t.__doc__ + "\n" + t.__doc__
            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 185
        print "%d of %d tests failed" % (len(failed), len(tests))

186 187
    tc = TC()
    tests = t1, t2, t3, t4, t5, t6, \
188
            TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6
189 190

    test(tests)