calltip.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. """Pop up a reminder of how to call a function.
  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 inspect
  8. import re
  9. import sys
  10. import textwrap
  11. import types
  12. from idlelib import calltip_w
  13. from idlelib.hyperparser import HyperParser
  14. class Calltip:
  15. def __init__(self, editwin=None):
  16. if editwin is None: # subprocess and test
  17. self.editwin = None
  18. else:
  19. self.editwin = editwin
  20. self.text = editwin.text
  21. self.active_calltip = None
  22. self._calltip_window = self._make_tk_calltip_window
  23. def close(self):
  24. self._calltip_window = None
  25. def _make_tk_calltip_window(self):
  26. # See __init__ for usage
  27. return calltip_w.CalltipWindow(self.text)
  28. def remove_calltip_window(self, event=None):
  29. if self.active_calltip:
  30. self.active_calltip.hidetip()
  31. self.active_calltip = None
  32. def force_open_calltip_event(self, event):
  33. "The user selected the menu entry or hotkey, open the tip."
  34. self.open_calltip(True)
  35. return "break"
  36. def try_open_calltip_event(self, event):
  37. """Happens when it would be nice to open a calltip, but not really
  38. necessary, for example after an opening bracket, so function calls
  39. won't be made.
  40. """
  41. self.open_calltip(False)
  42. def refresh_calltip_event(self, event):
  43. if self.active_calltip and self.active_calltip.tipwindow:
  44. self.open_calltip(False)
  45. def open_calltip(self, evalfuncs):
  46. """Maybe close an existing calltip and maybe open a new calltip.
  47. Called from (force_open|try_open|refresh)_calltip_event functions.
  48. """
  49. hp = HyperParser(self.editwin, "insert")
  50. sur_paren = hp.get_surrounding_brackets('(')
  51. # If not inside parentheses, no calltip.
  52. if not sur_paren:
  53. self.remove_calltip_window()
  54. return
  55. # If a calltip is shown for the current parentheses, do
  56. # nothing.
  57. if self.active_calltip:
  58. opener_line, opener_col = map(int, sur_paren[0].split('.'))
  59. if (
  60. (opener_line, opener_col) ==
  61. (self.active_calltip.parenline, self.active_calltip.parencol)
  62. ):
  63. return
  64. hp.set_index(sur_paren[0])
  65. try:
  66. expression = hp.get_expression()
  67. except ValueError:
  68. expression = None
  69. if not expression:
  70. # No expression before the opening parenthesis, e.g.
  71. # because it's in a string or the opener for a tuple:
  72. # Do nothing.
  73. return
  74. # At this point, the current index is after an opening
  75. # parenthesis, in a section of code, preceded by a valid
  76. # expression. If there is a calltip shown, it's not for the
  77. # same index and should be closed.
  78. self.remove_calltip_window()
  79. # Simple, fast heuristic: If the preceding expression includes
  80. # an opening parenthesis, it likely includes a function call.
  81. if not evalfuncs and (expression.find('(') != -1):
  82. return
  83. argspec = self.fetch_tip(expression)
  84. if not argspec:
  85. return
  86. self.active_calltip = self._calltip_window()
  87. self.active_calltip.showtip(argspec, sur_paren[0], sur_paren[1])
  88. def fetch_tip(self, expression):
  89. """Return the argument list and docstring of a function or class.
  90. If there is a Python subprocess, get the calltip there. Otherwise,
  91. either this fetch_tip() is running in the subprocess or it was
  92. called in an IDLE running without the subprocess.
  93. The subprocess environment is that of the most recently run script. If
  94. two unrelated modules are being edited some calltips in the current
  95. module may be inoperative if the module was not the last to run.
  96. To find methods, fetch_tip must be fed a fully qualified name.
  97. """
  98. try:
  99. rpcclt = self.editwin.flist.pyshell.interp.rpcclt
  100. except AttributeError:
  101. rpcclt = None
  102. if rpcclt:
  103. return rpcclt.remotecall("exec", "get_the_calltip",
  104. (expression,), {})
  105. else:
  106. return get_argspec(get_entity(expression))
  107. def get_entity(expression):
  108. """Return the object corresponding to expression evaluated
  109. in a namespace spanning sys.modules and __main.dict__.
  110. """
  111. if expression:
  112. namespace = {**sys.modules, **__main__.__dict__}
  113. try:
  114. return eval(expression, namespace) # Only protect user code.
  115. except BaseException:
  116. # An uncaught exception closes idle, and eval can raise any
  117. # exception, especially if user classes are involved.
  118. return None
  119. # The following are used in get_argspec and some in tests
  120. _MAX_COLS = 85
  121. _MAX_LINES = 5 # enough for bytes
  122. _INDENT = ' '*4 # for wrapped signatures
  123. _first_param = re.compile(r'(?<=\()\w*\,?\s*')
  124. _default_callable_argspec = "See source or doc"
  125. _invalid_method = "invalid method signature"
  126. def get_argspec(ob):
  127. '''Return a string describing the signature of a callable object, or ''.
  128. For Python-coded functions and methods, the first line is introspected.
  129. Delete 'self' parameter for classes (.__init__) and bound methods.
  130. The next lines are the first lines of the doc string up to the first
  131. empty line or _MAX_LINES. For builtins, this typically includes
  132. the arguments in addition to the return value.
  133. '''
  134. # Determine function object fob to inspect.
  135. try:
  136. ob_call = ob.__call__
  137. except BaseException: # Buggy user object could raise anything.
  138. return '' # No popup for non-callables.
  139. # For Get_argspecTest.test_buggy_getattr_class, CallA() & CallB().
  140. fob = ob_call if isinstance(ob_call, types.MethodType) else ob
  141. # Initialize argspec and wrap it to get lines.
  142. try:
  143. argspec = str(inspect.signature(fob))
  144. except Exception as err:
  145. msg = str(err)
  146. if msg.startswith(_invalid_method):
  147. return _invalid_method
  148. else:
  149. argspec = ''
  150. if isinstance(fob, type) and argspec == '()':
  151. # If fob has no argument, use default callable argspec.
  152. argspec = _default_callable_argspec
  153. lines = (textwrap.wrap(argspec, _MAX_COLS, subsequent_indent=_INDENT)
  154. if len(argspec) > _MAX_COLS else [argspec] if argspec else [])
  155. # Augment lines from docstring, if any, and join to get argspec.
  156. doc = inspect.getdoc(ob)
  157. if doc:
  158. for line in doc.split('\n', _MAX_LINES)[:_MAX_LINES]:
  159. line = line.strip()
  160. if not line:
  161. break
  162. if len(line) > _MAX_COLS:
  163. line = line[: _MAX_COLS - 3] + '...'
  164. lines.append(line)
  165. argspec = '\n'.join(lines)
  166. return argspec or _default_callable_argspec
  167. if __name__ == '__main__':
  168. from unittest import main
  169. main('idlelib.idle_test.test_calltip', verbosity=2)