calltip.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. self.remove_calltip_window()
  47. hp = HyperParser(self.editwin, "insert")
  48. sur_paren = hp.get_surrounding_brackets('(')
  49. if not sur_paren:
  50. return
  51. hp.set_index(sur_paren[0])
  52. expression = hp.get_expression()
  53. if not expression:
  54. return
  55. if not evalfuncs and (expression.find('(') != -1):
  56. return
  57. argspec = self.fetch_tip(expression)
  58. if not argspec:
  59. return
  60. self.active_calltip = self._calltip_window()
  61. self.active_calltip.showtip(argspec, sur_paren[0], sur_paren[1])
  62. def fetch_tip(self, expression):
  63. """Return the argument list and docstring of a function or class.
  64. If there is a Python subprocess, get the calltip there. Otherwise,
  65. either this fetch_tip() is running in the subprocess or it was
  66. called in an IDLE running without the subprocess.
  67. The subprocess environment is that of the most recently run script. If
  68. two unrelated modules are being edited some calltips in the current
  69. module may be inoperative if the module was not the last to run.
  70. To find methods, fetch_tip must be fed a fully qualified name.
  71. """
  72. try:
  73. rpcclt = self.editwin.flist.pyshell.interp.rpcclt
  74. except AttributeError:
  75. rpcclt = None
  76. if rpcclt:
  77. return rpcclt.remotecall("exec", "get_the_calltip",
  78. (expression,), {})
  79. else:
  80. return get_argspec(get_entity(expression))
  81. def get_entity(expression):
  82. """Return the object corresponding to expression evaluated
  83. in a namespace spanning sys.modules and __main.dict__.
  84. """
  85. if expression:
  86. namespace = {**sys.modules, **__main__.__dict__}
  87. try:
  88. return eval(expression, namespace) # Only protect user code.
  89. except BaseException:
  90. # An uncaught exception closes idle, and eval can raise any
  91. # exception, especially if user classes are involved.
  92. return None
  93. # The following are used in get_argspec and some in tests
  94. _MAX_COLS = 85
  95. _MAX_LINES = 5 # enough for bytes
  96. _INDENT = ' '*4 # for wrapped signatures
  97. _first_param = re.compile(r'(?<=\()\w*\,?\s*')
  98. _default_callable_argspec = "See source or doc"
  99. _invalid_method = "invalid method signature"
  100. _argument_positional = " # '/' marks preceding args as positional-only."
  101. def get_argspec(ob):
  102. '''Return a string describing the signature of a callable object, or ''.
  103. For Python-coded functions and methods, the first line is introspected.
  104. Delete 'self' parameter for classes (.__init__) and bound methods.
  105. The next lines are the first lines of the doc string up to the first
  106. empty line or _MAX_LINES. For builtins, this typically includes
  107. the arguments in addition to the return value.
  108. '''
  109. argspec = default = ""
  110. try:
  111. ob_call = ob.__call__
  112. except BaseException:
  113. return default
  114. fob = ob_call if isinstance(ob_call, types.MethodType) else ob
  115. try:
  116. argspec = str(inspect.signature(fob))
  117. except ValueError as err:
  118. msg = str(err)
  119. if msg.startswith(_invalid_method):
  120. return _invalid_method
  121. if '/' in argspec and len(argspec) < _MAX_COLS - len(_argument_positional):
  122. # Add explanation TODO remove after 3.7, before 3.9.
  123. argspec += _argument_positional
  124. if isinstance(fob, type) and argspec == '()':
  125. # If fob has no argument, use default callable argspec.
  126. argspec = _default_callable_argspec
  127. lines = (textwrap.wrap(argspec, _MAX_COLS, subsequent_indent=_INDENT)
  128. if len(argspec) > _MAX_COLS else [argspec] if argspec else [])
  129. if isinstance(ob_call, types.MethodType):
  130. doc = ob_call.__doc__
  131. else:
  132. doc = getattr(ob, "__doc__", "")
  133. if doc:
  134. for line in doc.split('\n', _MAX_LINES)[:_MAX_LINES]:
  135. line = line.strip()
  136. if not line:
  137. break
  138. if len(line) > _MAX_COLS:
  139. line = line[: _MAX_COLS - 3] + '...'
  140. lines.append(line)
  141. argspec = '\n'.join(lines)
  142. if not argspec:
  143. argspec = _default_callable_argspec
  144. return argspec
  145. if __name__ == '__main__':
  146. from unittest import main
  147. main('idlelib.idle_test.test_calltip', verbosity=2)