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