/Lib/idlelib/CallTips.py

http://unladen-swallow.googlecode.com/ · Python · 221 lines · 177 code · 14 blank · 30 comment · 11 complexity · bff5e8b1da8e8d5c8ccfd8935fde916b MD5 · raw file

  1. """CallTips.py - An IDLE Extension to Jog Your Memory
  2. Call Tips are floating windows which display function, class, and method
  3. parameter and docstring information when you type an opening parenthesis, and
  4. which disappear when you type a closing parenthesis.
  5. """
  6. import re
  7. import sys
  8. import types
  9. import CallTipWindow
  10. from HyperParser import HyperParser
  11. import __main__
  12. class CallTips:
  13. menudefs = [
  14. ('edit', [
  15. ("Show call tip", "<<force-open-calltip>>"),
  16. ])
  17. ]
  18. def __init__(self, editwin=None):
  19. if editwin is None: # subprocess and test
  20. self.editwin = None
  21. return
  22. self.editwin = editwin
  23. self.text = editwin.text
  24. self.calltip = None
  25. self._make_calltip_window = self._make_tk_calltip_window
  26. def close(self):
  27. self._make_calltip_window = None
  28. def _make_tk_calltip_window(self):
  29. # See __init__ for usage
  30. return CallTipWindow.CallTip(self.text)
  31. def _remove_calltip_window(self, event=None):
  32. if self.calltip:
  33. self.calltip.hidetip()
  34. self.calltip = None
  35. def force_open_calltip_event(self, event):
  36. """Happens when the user really wants to open a CallTip, even if a
  37. function call is needed.
  38. """
  39. self.open_calltip(True)
  40. def try_open_calltip_event(self, event):
  41. """Happens when it would be nice to open a CallTip, but not really
  42. necessary, for example after an opening bracket, so function calls
  43. won't be made.
  44. """
  45. self.open_calltip(False)
  46. def refresh_calltip_event(self, event):
  47. """If there is already a calltip window, check if it is still needed,
  48. and if so, reload it.
  49. """
  50. if self.calltip and self.calltip.is_active():
  51. self.open_calltip(False)
  52. def open_calltip(self, evalfuncs):
  53. self._remove_calltip_window()
  54. hp = HyperParser(self.editwin, "insert")
  55. sur_paren = hp.get_surrounding_brackets('(')
  56. if not sur_paren:
  57. return
  58. hp.set_index(sur_paren[0])
  59. name = hp.get_expression()
  60. if not name or (not evalfuncs and name.find('(') != -1):
  61. return
  62. arg_text = self.fetch_tip(name)
  63. if not arg_text:
  64. return
  65. self.calltip = self._make_calltip_window()
  66. self.calltip.showtip(arg_text, sur_paren[0], sur_paren[1])
  67. def fetch_tip(self, name):
  68. """Return the argument list and docstring of a function or class
  69. If there is a Python subprocess, get the calltip there. Otherwise,
  70. either fetch_tip() is running in the subprocess itself or it was called
  71. in an IDLE EditorWindow before any script had been run.
  72. The subprocess environment is that of the most recently run script. If
  73. two unrelated modules are being edited some calltips in the current
  74. module may be inoperative if the module was not the last to run.
  75. To find methods, fetch_tip must be fed a fully qualified name.
  76. """
  77. try:
  78. rpcclt = self.editwin.flist.pyshell.interp.rpcclt
  79. except:
  80. rpcclt = None
  81. if rpcclt:
  82. return rpcclt.remotecall("exec", "get_the_calltip",
  83. (name,), {})
  84. else:
  85. entity = self.get_entity(name)
  86. return get_arg_text(entity)
  87. def get_entity(self, name):
  88. "Lookup name in a namespace spanning sys.modules and __main.dict__"
  89. if name:
  90. namespace = sys.modules.copy()
  91. namespace.update(__main__.__dict__)
  92. try:
  93. return eval(name, namespace)
  94. except (NameError, AttributeError):
  95. return None
  96. def _find_constructor(class_ob):
  97. # Given a class object, return a function object used for the
  98. # constructor (ie, __init__() ) or None if we can't find one.
  99. try:
  100. return class_ob.__init__.im_func
  101. except AttributeError:
  102. for base in class_ob.__bases__:
  103. rc = _find_constructor(base)
  104. if rc is not None: return rc
  105. return None
  106. def get_arg_text(ob):
  107. """Get a string describing the arguments for the given object"""
  108. arg_text = ""
  109. if ob is not None:
  110. arg_offset = 0
  111. if type(ob) in (types.ClassType, types.TypeType):
  112. # Look for the highest __init__ in the class chain.
  113. fob = _find_constructor(ob)
  114. if fob is None:
  115. fob = lambda: None
  116. else:
  117. arg_offset = 1
  118. elif type(ob)==types.MethodType:
  119. # bit of a hack for methods - turn it into a function
  120. # but we drop the "self" param.
  121. fob = ob.im_func
  122. arg_offset = 1
  123. else:
  124. fob = ob
  125. # Try to build one for Python defined functions
  126. if type(fob) in [types.FunctionType, types.LambdaType]:
  127. argcount = fob.func_code.co_argcount
  128. real_args = fob.func_code.co_varnames[arg_offset:argcount]
  129. defaults = fob.func_defaults or []
  130. defaults = list(map(lambda name: "=%s" % repr(name), defaults))
  131. defaults = [""] * (len(real_args) - len(defaults)) + defaults
  132. items = map(lambda arg, dflt: arg + dflt, real_args, defaults)
  133. if fob.func_code.co_flags & 0x4:
  134. items.append("...")
  135. if fob.func_code.co_flags & 0x8:
  136. items.append("***")
  137. arg_text = ", ".join(items)
  138. arg_text = "(%s)" % re.sub("\.\d+", "<tuple>", arg_text)
  139. # See if we can use the docstring
  140. doc = getattr(ob, "__doc__", "")
  141. if doc:
  142. doc = doc.lstrip()
  143. pos = doc.find("\n")
  144. if pos < 0 or pos > 70:
  145. pos = 70
  146. if arg_text:
  147. arg_text += "\n"
  148. arg_text += doc[:pos]
  149. return arg_text
  150. #################################################
  151. #
  152. # Test code
  153. #
  154. if __name__=='__main__':
  155. def t1(): "()"
  156. def t2(a, b=None): "(a, b=None)"
  157. def t3(a, *args): "(a, ...)"
  158. def t4(*args): "(...)"
  159. def t5(a, *args): "(a, ...)"
  160. def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)"
  161. def t7((a, b), c, (d, e)): "(<tuple>, c, <tuple>)"
  162. class TC(object):
  163. "(ai=None, ...)"
  164. def __init__(self, ai=None, *b): "(ai=None, ...)"
  165. def t1(self): "()"
  166. def t2(self, ai, b=None): "(ai, b=None)"
  167. def t3(self, ai, *args): "(ai, ...)"
  168. def t4(self, *args): "(...)"
  169. def t5(self, ai, *args): "(ai, ...)"
  170. def t6(self, ai, b=None, *args, **kw): "(ai, b=None, ..., ***)"
  171. def t7(self, (ai, b), c, (d, e)): "(<tuple>, c, <tuple>)"
  172. def test(tests):
  173. ct = CallTips()
  174. failed=[]
  175. for t in tests:
  176. expected = t.__doc__ + "\n" + t.__doc__
  177. name = t.__name__
  178. # exercise fetch_tip(), not just get_arg_text()
  179. try:
  180. qualified_name = "%s.%s" % (t.im_class.__name__, name)
  181. except AttributeError:
  182. qualified_name = name
  183. arg_text = ct.fetch_tip(qualified_name)
  184. if arg_text != expected:
  185. failed.append(t)
  186. fmt = "%s - expected %s, but got %s"
  187. print fmt % (t.__name__, expected, get_arg_text(t))
  188. print "%d of %d tests failed" % (len(failed), len(tests))
  189. tc = TC()
  190. tests = (t1, t2, t3, t4, t5, t6, t7,
  191. TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6, tc.t7)
  192. test(tests)