rlineimpl.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: utf-8 -*-
  2. """ Imports and provides the 'correct' version of readline for the platform.
  3. Readline is used throughout IPython as::
  4. import IPython.utils.rlineimpl as readline
  5. In addition to normal readline stuff, this module provides have_readline
  6. boolean and _outputfile variable used in IPython.utils.
  7. """
  8. import sys
  9. import warnings
  10. _rlmod_names = ['gnureadline', 'readline']
  11. have_readline = False
  12. for _rlmod_name in _rlmod_names:
  13. try:
  14. # import readline as _rl
  15. _rl = __import__(_rlmod_name)
  16. # from readline import *
  17. globals().update({k:v for k,v in _rl.__dict__.items() if not k.startswith('_')})
  18. except ImportError:
  19. pass
  20. else:
  21. have_readline = True
  22. break
  23. if have_readline and (sys.platform == 'win32' or sys.platform == 'cli'):
  24. try:
  25. _outputfile=_rl.GetOutputFile()
  26. except AttributeError:
  27. warnings.warn("Failed GetOutputFile")
  28. have_readline = False
  29. # Test to see if libedit is being used instead of GNU readline.
  30. # Thanks to Boyd Waters for the original patch.
  31. uses_libedit = False
  32. if have_readline:
  33. # Official Python docs state that 'libedit' is in the docstring for libedit readline:
  34. uses_libedit = _rl.__doc__ and 'libedit' in _rl.__doc__
  35. # Note that many non-System Pythons also do not use proper readline,
  36. # but do not report libedit at all, nor are they linked dynamically against libedit.
  37. # known culprits of this include: EPD, Fink
  38. # There is not much we can do to detect this, until we find a specific failure
  39. # case, rather than relying on the readline module to self-identify as broken.
  40. if uses_libedit and sys.platform == 'darwin':
  41. _rl.parse_and_bind("bind ^I rl_complete")
  42. warnings.warn('\n'.join(['', "*"*78,
  43. "libedit detected - readline will not be well behaved, including but not limited to:",
  44. " * crashes on tab completion",
  45. " * incorrect history navigation",
  46. " * corrupting long-lines",
  47. " * failure to wrap or indent lines properly",
  48. "It is highly recommended that you install gnureadline, which is installable with:",
  49. " pip install gnureadline",
  50. "*"*78]),
  51. RuntimeWarning)
  52. # the clear_history() function was only introduced in Python 2.4 and is
  53. # actually optional in the readline API, so we must explicitly check for its
  54. # existence. Some known platforms actually don't have it. This thread:
  55. # http://mail.python.org/pipermail/python-dev/2003-August/037845.html
  56. # has the original discussion.
  57. if have_readline:
  58. try:
  59. _rl.clear_history
  60. except AttributeError:
  61. def clear_history(): pass
  62. _rl.clear_history = clear_history