home *** CD-ROM | disk | FTP | other *** search
/ Freelog 33 / Freelog033.iso / Progr / Python-2.2.1.exe / CALLTIPS.PY < prev    next >
Encoding:
Python Source  |  2001-09-16  |  6.7 KB  |  196 lines

  1. # CallTips.py - An IDLE extension that provides "Call Tips" - ie, a floating window that
  2. # displays parameter information as you open parens.
  3.  
  4. import string
  5. import sys
  6. import types
  7.  
  8. class CallTips:
  9.  
  10.     menudefs = [
  11.     ]
  12.  
  13.     keydefs = {
  14.         '<<paren-open>>': ['<Key-parenleft>'],
  15.         '<<paren-close>>': ['<Key-parenright>'],
  16.         '<<check-calltip-cancel>>': ['<KeyRelease>'],
  17.         '<<calltip-cancel>>': ['<ButtonPress>', '<Key-Escape>'],
  18.     }
  19.  
  20.     windows_keydefs = {
  21.     }
  22.  
  23.     unix_keydefs = {
  24.     }
  25.  
  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
  34.  
  35.     def close(self):
  36.         self._make_calltip_window = None
  37.  
  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)
  43.  
  44.     def _remove_calltip_window(self):
  45.         if self.calltip:
  46.             self.calltip.hidetip()
  47.             self.calltip = None
  48.  
  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.
  57.  
  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.
  63.  
  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.
  73.  
  74.     def calltip_cancel_event(self, event):
  75.         self._remove_calltip_window()
  76.         return "" #so the event is handled normally.
  77.  
  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.
  98.  
  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
  109.  
  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.         doc = getattr(ob, "__doc__", "")
  147.         if doc:
  148.             while doc[:1] in " \t\n":
  149.                 doc = doc[1:]
  150.             pos = doc.find("\n")
  151.             if pos < 0 or pos > 70:
  152.                 pos = 70
  153.             if argText:
  154.                 argText += "\n"
  155.             argText += doc[:pos]
  156.  
  157.     return argText
  158.  
  159. #################################################
  160. #
  161. # Test code
  162. #
  163. if __name__=='__main__':
  164.  
  165.     def t1(): "()"
  166.     def t2(a, b=None): "(a, b=None)"
  167.     def t3(a, *args): "(a, ...)"
  168.     def t4(*args): "(...)"
  169.     def t5(a, *args): "(a, ...)"
  170.     def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)"
  171.  
  172.     class TC:
  173.         "(a=None, ...)"
  174.         def __init__(self, a=None, *b): "(a=None, ...)"
  175.         def t1(self): "()"
  176.         def t2(self, a, b=None): "(a, b=None)"
  177.         def t3(self, a, *args): "(a, ...)"
  178.         def t4(self, *args): "(...)"
  179.         def t5(self, a, *args): "(a, ...)"
  180.         def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)"
  181.  
  182.     def test( tests ):
  183.         failed=[]
  184.         for t in tests:
  185.             expected = t.__doc__ + "\n" + t.__doc__
  186.             if get_arg_text(t) != expected:
  187.                 failed.append(t)
  188.                 print "%s - expected %s, but got %s" % (t, `expected`, `get_arg_text(t)`)
  189.         print "%d of %d tests failed" % (len(failed), len(tests))
  190.  
  191.     tc = TC()
  192.     tests = t1, t2, t3, t4, t5, t6, \
  193.             TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6
  194.  
  195.     test(tests)
  196.