CallTips.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 __main__
  7. import re
  8. import sys
  9. import textwrap
  10. import types
  11. from idlelib import CallTipWindow
  12. from idlelib.HyperParser import HyperParser
  13. class CallTips:
  14. menudefs = [
  15. ('edit', [
  16. ("Show call tip", "<<force-open-calltip>>"),
  17. ])
  18. ]
  19. def __init__(self, editwin=None):
  20. if editwin is None: # subprocess and test
  21. self.editwin = None
  22. return
  23. self.editwin = editwin
  24. self.text = editwin.text
  25. self.calltip = None
  26. self._make_calltip_window = self._make_tk_calltip_window
  27. def close(self):
  28. self._make_calltip_window = None
  29. def _make_tk_calltip_window(self):
  30. # See __init__ for usage
  31. return CallTipWindow.CallTip(self.text)
  32. def _remove_calltip_window(self, event=None):
  33. if self.calltip:
  34. self.calltip.hidetip()
  35. self.calltip = None
  36. def force_open_calltip_event(self, event):
  37. """Happens when the user really wants to open a CallTip, even if a
  38. function call is needed.
  39. """
  40. self.open_calltip(True)
  41. def try_open_calltip_event(self, event):
  42. """Happens when it would be nice to open a CallTip, but not really
  43. necessary, for example after an opening bracket, so function calls
  44. won't be made.
  45. """
  46. self.open_calltip(False)
  47. def refresh_calltip_event(self, event):
  48. """If there is already a calltip window, check if it is still needed,
  49. and if so, reload it.
  50. """
  51. if self.calltip and self.calltip.is_active():
  52. self.open_calltip(False)
  53. def open_calltip(self, evalfuncs):
  54. self._remove_calltip_window()
  55. hp = HyperParser(self.editwin, "insert")
  56. sur_paren = hp.get_surrounding_brackets('(')
  57. if not sur_paren:
  58. return
  59. hp.set_index(sur_paren[0])
  60. expression = hp.get_expression()
  61. if not expression or (not evalfuncs and expression.find('(') != -1):
  62. return
  63. arg_text = self.fetch_tip(expression)
  64. if not arg_text:
  65. return
  66. self.calltip = self._make_calltip_window()
  67. self.calltip.showtip(arg_text, sur_paren[0], sur_paren[1])
  68. def fetch_tip(self, expression):
  69. """Return the argument list and docstring of a function or class
  70. If there is a Python subprocess, get the calltip there. Otherwise,
  71. either fetch_tip() is running in the subprocess itself or it was called
  72. in an IDLE EditorWindow before any script had been run.
  73. The subprocess environment is that of the most recently run script. If
  74. two unrelated modules are being edited some calltips in the current
  75. module may be inoperative if the module was not the last to run.
  76. To find methods, fetch_tip must be fed a fully qualified name.
  77. """
  78. try:
  79. rpcclt = self.editwin.flist.pyshell.interp.rpcclt
  80. except AttributeError:
  81. rpcclt = None
  82. if rpcclt:
  83. return rpcclt.remotecall("exec", "get_the_calltip",
  84. (expression,), {})
  85. else:
  86. entity = self.get_entity(expression)
  87. return get_arg_text(entity)
  88. def get_entity(self, expression):
  89. """Return the object corresponding to expression evaluated
  90. in a namespace spanning sys.modules and __main.dict__.
  91. """
  92. if expression:
  93. namespace = sys.modules.copy()
  94. namespace.update(__main__.__dict__)
  95. try:
  96. return eval(expression, namespace)
  97. except BaseException:
  98. # An uncaught exception closes idle, and eval can raise any
  99. # exception, especially if user classes are involved.
  100. return None
  101. def _find_constructor(class_ob):
  102. # Given a class object, return a function object used for the
  103. # constructor (ie, __init__() ) or None if we can't find one.
  104. try:
  105. return class_ob.__init__.im_func
  106. except AttributeError:
  107. for base in class_ob.__bases__:
  108. rc = _find_constructor(base)
  109. if rc is not None: return rc
  110. return None
  111. # The following are used in get_arg_text
  112. _MAX_COLS = 85
  113. _MAX_LINES = 5 # enough for bytes
  114. _INDENT = ' '*4 # for wrapped signatures
  115. def get_arg_text(ob):
  116. '''Return a string describing the signature of a callable object, or ''.
  117. For Python-coded functions and methods, the first line is introspected.
  118. Delete 'self' parameter for classes (.__init__) and bound methods.
  119. The next lines are the first lines of the doc string up to the first
  120. empty line or _MAX_LINES. For builtins, this typically includes
  121. the arguments in addition to the return value.
  122. '''
  123. argspec = ""
  124. try:
  125. ob_call = ob.__call__
  126. except BaseException:
  127. if type(ob) is types.ClassType: # old-style
  128. ob_call = ob
  129. else:
  130. return argspec
  131. arg_offset = 0
  132. if type(ob) in (types.ClassType, types.TypeType):
  133. # Look for the first __init__ in the class chain with .im_func.
  134. # Slot wrappers (builtins, classes defined in funcs) do not.
  135. fob = _find_constructor(ob)
  136. if fob is None:
  137. fob = lambda: None
  138. else:
  139. arg_offset = 1
  140. elif type(ob) == types.MethodType:
  141. # bit of a hack for methods - turn it into a function
  142. # and drop the "self" param for bound methods
  143. fob = ob.im_func
  144. if ob.im_self is not None:
  145. arg_offset = 1
  146. elif type(ob_call) == types.MethodType:
  147. # a callable class instance
  148. fob = ob_call.im_func
  149. arg_offset = 1
  150. else:
  151. fob = ob
  152. # Try to build one for Python defined functions
  153. if type(fob) in [types.FunctionType, types.LambdaType]:
  154. argcount = fob.func_code.co_argcount
  155. real_args = fob.func_code.co_varnames[arg_offset:argcount]
  156. defaults = fob.func_defaults or []
  157. defaults = list(map(lambda name: "=%s" % repr(name), defaults))
  158. defaults = [""] * (len(real_args) - len(defaults)) + defaults
  159. items = map(lambda arg, dflt: arg + dflt, real_args, defaults)
  160. for flag, pre, name in ((0x4, '*', 'args'), (0x8, '**', 'kwargs')):
  161. if fob.func_code.co_flags & flag:
  162. pre_name = pre + name
  163. if name not in real_args:
  164. items.append(pre_name)
  165. else:
  166. i = 1
  167. while ((name+'%s') % i) in real_args:
  168. i += 1
  169. items.append((pre_name+'%s') % i)
  170. argspec = ", ".join(items)
  171. argspec = "(%s)" % re.sub("(?<!\d)\.\d+", "<tuple>", argspec)
  172. lines = (textwrap.wrap(argspec, _MAX_COLS, subsequent_indent=_INDENT)
  173. if len(argspec) > _MAX_COLS else [argspec] if argspec else [])
  174. if isinstance(ob_call, types.MethodType):
  175. doc = ob_call.__doc__
  176. else:
  177. doc = getattr(ob, "__doc__", "")
  178. if doc:
  179. for line in doc.split('\n', _MAX_LINES)[:_MAX_LINES]:
  180. line = line.strip()
  181. if not line:
  182. break
  183. if len(line) > _MAX_COLS:
  184. line = line[: _MAX_COLS - 3] + '...'
  185. lines.append(line)
  186. argspec = '\n'.join(lines)
  187. return argspec
  188. if __name__ == '__main__':
  189. from unittest import main
  190. main('idlelib.idle_test.test_calltips', verbosity=2)