o
    ˷e);                    @   s.  d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZmZmZmZmZm Z  ddl!m"Z" ddl#m$Z$ dd	l%m&Z&m'Z' dd
l(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7m8Z8mZ9m:Z:m;Z;m<Z< ddl=m>Z> ddl?Z?dZ@zddlAZAdeAjB_CddlDZAddlEZAdZFW n eGy   dZFY nw ddgZHddgZIe
jJdkrdZKndZKdZLG dd deMZNejOdeNd e+edbd!d"ZPd#d$ ZQeKfd%d&ZRd'eSd(eeSeTeSf fd)d*ZUd'eSd+eTd,eSd(eSfd-d.ZVd/d0 ZWG d1d2 d2ZXG d3d4 d4ZYeeY ZZd5eSd6eZd(eZfd7d8Z[dd9d5eSd6eZd:eTd(eZfd;d<Z\e
jJdkred=Z]nd>Z]d?Z^G d@dA dAe_Z`G dBd de>ZadCdD Zb	dcdEeeeSeceeeSecf  f  dFeSdGeSdHe eeSecf  d(eeSedeeS f f
dIdJZed5eSdKeddLedd(edfdMdNZfd5eSdOedd(eededf fdPdQZgdRdS Zhd5eSd(eeSeeS f fdTdUZid5eSd(eeSeeS f fdVdWZjd(eSfdXdYZkd(eSfdZd[ZlG d\d] d]eZmG d^d deaZnd_eeededf  d(eeS fd`daZodS )du  Completion for IPython.

This module started as fork of the rlcompleter module in the Python standard
library.  The original enhancements made to rlcompleter have been sent
upstream and were accepted as of Python 2.3,

This module now support a wide variety of completion mechanism both available
for normal classic Python code, as well as completer for IPython specific
Syntax like magics.

Latex and Unicode completion
============================

IPython and compatible frontends not only can complete your code, but can help
you to input a wide range of characters. In particular we allow you to insert
a unicode character using the tab completion mechanism.

Forward latex/unicode completion
--------------------------------

Forward completion allows you to easily type a unicode character using its latex
name, or unicode long description. To do so type a backslash follow by the
relevant name and press tab:


Using latex completion:

.. code::

    \alpha<tab>
    α

or using unicode completion:


.. code::

    \GREEK SMALL LETTER ALPHA<tab>
    α


Only valid Python identifiers will complete. Combining characters (like arrow or
dots) are also available, unlike latex they need to be put after the their
counterpart that is to say, ``F\\vec<tab>`` is correct, not ``\\vec<tab>F``.

Some browsers are known to display combining characters incorrectly.

Backward latex completion
-------------------------

It is sometime challenging to know how to type a character, if you are using
IPython, or any compatible frontend you can prepend backslash to the character
and press ``<tab>`` to expand it to its latex form.

.. code::

    \α<tab>
    \alpha


Both forward and backward completions can be deactivated by setting the
``Completer.backslash_combining_completions`` option to ``False``.


Experimental
============

Starting with IPython 6.0, this module can make use of the Jedi library to
generate completions both using static analysis of the code, and dynamically
inspecting multiple namespaces. Jedi is an autocompletion and static analysis
for Python. The APIs attached to this new mechanism is unstable and will
raise unless use in an :any:`provisionalcompleter` context manager.

You will find that the following are experimental:

    - :any:`provisionalcompleter`
    - :any:`IPCompleter.completions`
    - :any:`Completion`
    - :any:`rectify_completions`

.. note::

    better name for :any:`rectify_completions` ?

We welcome any feedback on these new API, and we also encourage you to try this
module in debug mode (start IPython with ``--Completer.debug=True``) in order
to have extra logging information if :any:`jedi` is crashing, or if current
IPython completer pending deprecations are returning results not yet handled
by :any:`jedi`

Using Jedi for tab completion allow snippets like the following to work without
having to execute any code:

   >>> myvar = ['hello', 42]
   ... myvar[1].bi<tab>

Tab completion will be able to infer that ``myvar[1]`` is a real number without
executing any code unlike the previously available ``IPCompleter.greedy``
option.

Be sure to update :any:`jedi` to the latest stable version or to try the
current development version to get better completions.
    N)contextmanager)import_module)SimpleNamespace)IterableIteratorListTupleUnionAnySequenceDict
NamedTuplePatternOptional)TryNext)	ESC_MAGIC)latex_symbolsreverse_latex_symbol)InspectColors)skip_doctest)generics)dir2get_real_method)ensure_dir_exists)	arg_split)BoolEnumIntr   Unicodedefaultobserve)ConfigurableTF)    iK )i  i 	CompleterIPCompleterwin32 z ()[]{}?=\|;:'#*"^&i  c                   @   s   e Zd ZdZdS )ProvisionalCompleterWarningz
    Exception raise by an experimental feature in this module.

    Wrap code in :any:`provisionalcompleter` context manager if you
    are certain you want to use an unstable feature.
    N)__name__
__module____qualname____doc__ r,   r,   M/var/www/ideatree/venv/lib/python3.10/site-packages/IPython/core/completer.pyr'      s    r'   errorcategoryignorec                 c   sD    t   t j| td dV  W d   dS 1 sw   Y  dS )a  
    This context manager has to be used in any place where unstable completer
    behavior and API may be called.

    >>> with provisionalcompleter():
    ...     completer.do_experimental_things() # works

    >>> completer.do_experimental_things() # raises.

    .. note::

        Unstable

        By using this context manager you agree that the API in use may change
        without warning, and that you won't complain if they do so.

        You also understand that, if the API is not to your liking, you should report
        a bug to explain your use case upstream.

        We'll be happy to get your feedback, feature requests, and improvements on
        any of the unstable APIs!
    r/   N)warningscatch_warningsfilterwarningsr'   )actionr,   r,   r-   provisionalcompleter   s
   
"r6   c                 C   s(   |  dd r	dS |  dd rdS dS )a  Return whether a string has open quotes.

    This simply counts whether the number of quote characters of either type in
    the string is odd.

    Returns
    -------
    If there is an open quote, the quote character is returned.  Else, return
    False.
    "   'F)countsr,   r,   r-   has_open_quotes   s
   r=   c                    sB   t | t  @ rtjdkrd|  d S d fdd| D S | S )z.Escape a string to protect certain characters.r%   r7    c                 3   s$    | ]}| v rd | n|V  qdS \Nr,   .0cprotectablesr,   r-   	<genexpr>   s   " z#protect_filename.<locals>.<genexpr>)setsysplatformjoin)r<   rE   r,   rD   r-   protect_filename   s
   
rK   pathreturnc                 C   sT   d}d}| }|  dr%d}t| d }tj| }|r#|d|  }n|}|||fS )a  Expand ``~``-style usernames in strings.

    This is similar to :func:`os.path.expanduser`, but it computes and returns
    extra information that will be useful if the input was being used in
    computing completions, and you wish to return the completions with the
    original '~' instead of its expanded value.

    Parameters
    ----------
    path : str
        String to be expanded.  If no ~ is present, the output is the same as the
        input.

    Returns
    -------
    newpath : str
        Result of ~ expansion in the input path.
    tilde_expand : bool
        Whether any expansion was performed or not.
    tilde_val : str
        The value that ~ was replaced with.
    Fr>   ~T   N)
startswithlenosrL   
expanduser)rL   tilde_expand	tilde_valnewpathrestr,   r,   r-   expand_user   s   

rX   rT   rU   c                 C   s   |r|  |dS | S )z8Does the opposite of expand_user, with its outputs.
    rN   replace)rL   rT   rU   r,   r,   r-   compress_user'  s   r[   c                 C   s   d\}}|  drd}n|  drd}| drd}|  dr0d	| dd
 vr/| dd
 } d}n|  d	rEd	| dd
 vrE| dd
 } d}|| |fS )zkey for sorting completions

    This does several things:

    - Demote any completions starting with underscores to the end
    - Insert any %magic and %%cellmagic completions in the alphabetical order
      by their name
    )r   r   __r8   _rO   =z%%%N)rP   endswith)wordprio1prio2r,   r,   r-   completions_sorting_key0  s"   	





re   c                   @   s    e Zd ZdZdd Zdd ZdS )_FakeJediCompletionz
    This is a workaround to communicate to the UI that Jedi has crashed and to
    report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.

    Added in IPython 6.0 so should likely be removed for 7.0

    c                 C   s(   || _ || _d| _|| _d| _d| _d S )Ncrashedr>   fake)namecompletetypename_with_symbols	signature_origin)selfri   r,   r,   r-   __init__Y  s   
z_FakeJediCompletion.__init__c                 C   s   dS )Nz)<Fake completion object jedi has crashed>r,   ro   r,   r,   r-   __repr__b  s   z_FakeJediCompletion.__repr__N)r(   r)   r*   r+   rp   rr   r,   r,   r,   r-   rf   P  s    	rf   c                   @   s^   e Zd ZdZg dZdddddededed	ed
df
ddZdd Zd
e	fddZ
dd ZdS )
Completionam  
    Completion object used and return by IPython completers.

    .. warning::

        Unstable

        This function is unstable, API may change without warning.
        It will also raise unless use in proper context manager.

    This act as a middle ground :any:`Completion` object between the
    :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
    object. While Jedi need a lot of information about evaluator and how the
    code should be ran/inspected, PromptToolkit (and other frontend) mostly
    need user facing information.

    - Which range should be replaced replaced by what.
    - Some metadata (like completion type), or meta information to displayed to
      the use user.

    For debugging purpose we can also store the origin of the completion (``jedi``,
    ``IPython.python_matches``, ``IPython.magics_matches``...).
    startendtextrk   rm   rn   Nr>   rk   rn   rm   ru   rv   rw   rk   rM   c                C   s8   t jdtdd || _|| _|| _|| _|| _|| _d S )Nz~``Completion`` is a provisional API (as of IPython 6.0). It may change without warnings. Use in corresponding context manager.r8   r0   
stacklevel)	r2   warnr'   ru   rv   rw   rk   rm   rn   )ro   ru   rv   rw   rk   rn   rm   r,   r,   r-   rp     s   
zCompletion.__init__c                 C   s$   d| j | j| j| jpd| jpdf S )Nz;<Completion start=%s end=%s text=%r type=%r, signature=%r,>?)ru   rv   rw   rk   rm   rq   r,   r,   r-   rr     s   zCompletion.__repr__c                 C   s$   | j |j ko| j|jko| j|jkS )a]  
        Equality and hash do not hash the type (as some completer may not be
        able to infer the type), but are use to (partially) de-duplicate
        completion.

        Completely de-duplicating completion is a bit tricker that just
        comparing as it depends on surrounding text, which Completions are not
        aware of.
        )ru   rv   rw   )ro   otherr,   r,   r-   __eq__  s
   


zCompletion.__eq__c                 C   s   t | j| j| jfS N)hashru   rv   rw   rq   r,   r,   r-   __hash__  s   zCompletion.__hash__)r(   r)   r*   r+   	__slots__intstrrp   rr   r   r~   r   r,   r,   r,   r-   rs   f  s    (rs   rw   completionsc                 c   s    t |}|s	dS tdd |D }tdd |D }t }|D ]}| ||j |j | |j|  }||vr?|V  || q dS )a  
    Deduplicate a set of completions.

    .. warning::

        Unstable

        This function is unstable, API may change without warning.

    Parameters
    ----------
    text : str
        text that should be completed.
    completions : Iterator[Completion]
        iterator over the completions to deduplicate

    Yields
    ------
    `Completions` objects
    Completions coming from multiple sources, may be different but end up having
    the same effect when applied to ``text``. If this is the case, this will
    consider completions as equal and only emit the first encountered.
    Not folded in `completions()` yet for debugging purpose, and to detect when
    the IPython completer does return things that Jedi does not, but should be
    at some point.
    Nc                 s       | ]}|j V  qd S r   ru   rA   r,   r,   r-   rF         z+_deduplicate_completions.<locals>.<genexpr>c                 s   r   r   rv   rA   r,   r,   r-   rF     r   )listminmaxrG   ru   rw   rv   add)rw   r   	new_startnew_endseenrC   new_textr,   r,   r-   _deduplicate_completions  s   "
r   )_debugr   c             	   c   s    t jdtdd t|}|sdS dd |D }dd |D }t|}t|}t }t }|D ]6}	| ||	j |	j | |	j	|  }
|	j
dkrM||
 n
|	j
d	krW||
 t|||
|	j|	j
|	jd
V  q/||}|rv|rxtd| dS dS dS )a  
    Rectify a set of completions to all have the same ``start`` and ``end``

    .. warning::

        Unstable

        This function is unstable, API may change without warning.
        It will also raise unless use in proper context manager.

    Parameters
    ----------
    text : str
        text that should be completed.
    completions : Iterator[Completion]
        iterator over the completions to rectify
    _debug : bool
        Log failed completion

    Notes
    -----
    :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
    the Jupyter Protocol requires them to behave like so. This will readjust
    the completion to have the same ``start`` and ``end`` by padding both
    extremities with surrounding text.

    During stabilisation should support a ``_debug`` option to log which
    completion are return by the IPython completer and not found in Jedi in
    order to make upstream bug report.
    z`rectify_completions` is a provisional API (as of IPython 6.0). It may change without warnings. Use in corresponding context manager.r8   ry   Nc                 s   r   r   r   rA   r,   r,   r-   rF     r   z&rectify_completions.<locals>.<genexpr>c                 s   r   r   r   rA   r,   r,   r-   rF     r   jediIPCompleter.python_matchesrx   z#IPython.python matches have extras:)r2   r{   r'   r   r   r   rG   ru   rw   rv   rn   r   rs   rk   rm   
differenceprint)rw   r   r   startsendsr   r   	seen_jediseen_python_matchesrC   r   diffr,   r,   r-   rectify_completions  s0   "



r   z 	
`!@#$^&*()=+[{]}|;'",<>?z 	
`!@#$^&*()=+[{]}\|;:'",<>?z =
c                   @   sJ   e Zd ZdZeZdZdZd
ddZe	dd Z
e
jdd Z
d
dd	ZdS )CompletionSplitteraW  An object to split an input line in a manner similar to readline.

    By having our own implementation, we can expose readline-like completion in
    a uniform manner to all frontends.  This object only needs to be given the
    line of text to be split and the cursor position on said line, and it
    returns the 'word' to be completed on at the cursor after splitting the
    entire line.

    What characters are used as splitting delimiters can be controlled by
    setting the ``delims`` attribute (this is a property that internally
    automatically builds the necessary regular expression)Nc                 C   s   |d u rt jn|}|| _d S r   )r   _delimsdelims)ro   r   r,   r,   r-   rp   /  s   
zCompletionSplitter.__init__c                 C   s   | j S )z*Return the string of delimiter characters.)r   rq   r,   r,   r-   r   3  s   zCompletionSplitter.delimsc                 C   s8   dd dd |D  d }t|| _|| _|| _dS )z&Set the delimiters for line splitting.[r>   c                 s       | ]}d | V  qdS r?   r,   rA   r,   r,   r-   rF   ;      z,CompletionSplitter.delims.<locals>.<genexpr>]N)rJ   recompile	_delim_rer   _delim_expr)ro   r   exprr,   r,   r-   r   8  s   
c                 C   s(   |du r|n|d| }| j |d S )zBSplit a line of text with a cursor at the given position.
        Nr_   )r   split)ro   line
cursor_poslr,   r,   r-   
split_line@  s   zCompletionSplitter.split_liner   )r(   r)   r*   r+   DELIMSr   r   r   rp   propertyr   setterr   r,   r,   r,   r-   r     s    


r   c                       s   e Zd ZedddjddZeeddjddZedd	djddZ	edd
djddZ
edddjddZd fdd	Zdd Zdd Zdd Z  ZS )r#   Fa  Activate greedy completion
        PENDING DEPRECATION. this is now mostly taken care of with Jedi.

        This will enable completion on elements of lists, results of function calls, etc.,
        but can be unsafe because the code is actually evaluated on TAB.
        helpTconfigzYExperimental: Use Jedi to generate autocompletions. Default to True if jedi is installed.default_valuer   i  zExperimental: restrict time (in milliseconds) during which Jedi can compute types.
        Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
        performance by preventing jedi to build its cache.
        zaEnable debug for the Completer. Mostly print extra information for experimental jedi integration.zEnable unicode completions, e.g. \alpha<tab> . Includes completion of latex commands, unicode names, and expanding unicode characters back to latex commands.Nc                    sR   |du rd| _ nd| _ || _|du ri | _n|| _g | _tt| jdi | dS )a  Create a new completer for the command line.

        Completer(namespace=ns, global_namespace=ns2) -> completer instance.

        If unspecified, the default namespace where completions are performed
        is __main__ (technically, __main__.__dict__). Namespaces should be
        given as dictionaries.

        An optional second namespace can be given.  This allows the completer
        to handle cases where both the local and global scopes need to be
        distinguished.
        NTFr,   )use_main_ns	namespaceglobal_namespacecustom_matcherssuperr#   rp   )ro   r   r   kwargs	__class__r,   r-   rp   g  s   zCompleter.__init__c                 C   sZ   | j rtj| _|dkrd|v r| || _n| || _z| j| W S  ty,   Y dS w )zReturn the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        r   .N)r   __main____dict__r   attr_matchesmatchesglobal_matches
IndexError)ro   rw   stater,   r,   r-   rj     s   zCompleter.completec                    s   g }|j }t|}tjtj | j | j fD ]}|D ]}|d| |kr/|dkr/|| qqt	
d | j | j fD ]$} fdd|D }| D ]}|d| |krc|dkrc|||  qOq@|S )zCompute matches when text is a simple name.

        Return a list of all keywords, built-in functions and names currently
        defined in self.namespace or self.global_namespace that match.

        N__builtins__z[^_]+(_[^_]+)+?\Zc                    s2   i | ]}  |rd dd |d D |qS )r]   c                 S      g | ]}|d  qS r   r,   )rB   subr,   r,   r-   
<listcomp>      z7Completer.global_matches.<locals>.<dictcomp>.<listcomp>)matchrJ   r   )rB   rb   snake_case_rer,   r-   
<dictcomp>  s    
"z,Completer.global_matches.<locals>.<dictcomp>)appendrQ   keywordkwlistbuiltin_modr   keysr   r   r   r   )ro   rw   r   match_appendnlstrb   	shortenedr,   r   r-   r     s4   

zCompleter.global_matchesc              	      s  t d|}|r|dd\ n| jr(t d| j}|sg S |dd\ ng S zt| j}W n   zt| j}W n	   g  Y  Y S Y | jrVt	|drVt
|}nt|}zt||}W n tyk   Y n tyr     tyz   Y nw t  fdd|D S )	a  Compute matches when text contains a dot.

        Assuming the text is of the form NAME.NAME....[NAME], and is
        evaluatable in self.namespace or self.global_namespace, it will be
        evaluated and its attributes (as revealed by dir()) are used as
        possible completions.  (For class instances, class members are
        also considered.)

        WARNING: this can still invoke arbitrary C code, if an object
        with a __getattr__ hook is evaluated.

        z(\S+(\.\w+)*)\.(\w*)$rO      z(.+)\.(\w*)$r8   __all__c                    s(   g | ]}|d   krd|f qS )Nz%s.%sr,   rB   wattrr   r   r,   r-   r     s   ( z*Completer.attr_matches.<locals>.<listcomp>)r   r   groupgreedyline_bufferevalr   r   limit_to__all__hasattrget__all__entriesr   r   complete_objectr   AssertionError	ExceptionrQ   )ro   rw   mm2objwordsr,   r   r-   r     s>   
zCompleter.attr_matches)NN)r(   r)   r*   r   tagr   JEDI_INSTALLEDuse_jedir   jedi_compute_type_timeoutdebugbackslash_combining_completionsrp   rj   r   r   __classcell__r,   r,   r   r-   r#   H  s<    	!c                 C   s,   zt | d}W n   g  Y S dd |D S )z,returns the strings in the __all__ attributer   c                 S   s   g | ]	}t |tr|qS r,   )
isinstancer   r   r,   r,   r-   r         z%get__all__entries.<locals>.<listcomp>)getattr)r   r   r,   r,   r-   r     s
   r   r   prefixr   extra_prefixc                    s  |r|ndt   fdd}g fdd}| D ]}t|tr-||r,||   q|| q|s>dddd	 D fS td
|}|dusJJ | }z	t|| i }	W n tye   ddg f Y S w dddd |D  d }
t|
|tj	}|dusJ |
 }| }g }D ]O}z	||	sW qW n tttfy   Y qw |t |	d }t|trt|d nt|d }|d|d d }|dkr|dd}|d||f  q|||fS )a*  Used by dict_key_matches, matching the prefix to a list of keys

    Parameters
    ----------
    keys
        list of keys in dictionary currently being completed.
    prefix
        Part of the text already typed by the user. E.g. `mydict[b'fo`
    delims
        String of delimiters to consider when finding the current key.
    extra_prefix : optional
        Part of the text already typed in multi-key index cases. E.g. for
        `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.

    Returns
    -------
    A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
    ``quote`` being the quote that need to be used to close current string.
    ``token_start`` the position where the replacement should start occurring,
    ``matches`` a list of replacement/completion

    r,   c                    sT   t |  krdS | D ]}t|ttfs dS q
t| D ]\}}||kr' dS qdS )NFT)rQ   r   r   byteszip)keykpt)Nprefixprefix_tupler,   r-   filter_prefix_tuple  s   z,match_dict_keys.<locals>.filter_prefix_tuplec                    s    t | ttfr |  d S d S r   )r   r   r   r   r   )filtered_keysr,   r-   _add_to_filtered_keys#  s   z.match_dict_keys.<locals>._add_to_filtered_keysr>   r   c                 S   s   g | ]}t |qS r,   )reprrB   r   r,   r,   r-   r   /  r   z#match_dict_keys.<locals>.<listcomp>z["']Nz[^c                 s   r   r?   r,   rA   r,   r,   r-   rF   8  r   z"match_dict_keys.<locals>.<genexpr>z]*$r7      "rO   r9   z\"z%s%s)rQ   r   tupler   searchr   r   r   rJ   UNICODEru   rP   AttributeError	TypeErrorUnicodeErrorr   r  indexrZ   r   )r   r   r   r   r  r  r   quote_matchquote
prefix_strpatterntoken_matchtoken_starttoken_prefixmatchedr   remrem_reprr,   )r   r  r  r-   match_dict_keys  sT   


"
r  r   columnc                 C   sP   |  d}|t|ksJ dt|tt|tdd |d| D | S )a  
    Convert the (line,column) position of the cursor in text to an offset in a
    string.

    Parameters
    ----------
    text : str
        The text in which to calculate the cursor offset
    line : int
        Line of the cursor; 0-indexed
    column : int
        Column of the cursor 0-indexed

    Returns
    -------
    Position of the cursor in ``text``, 0-indexed.

    See Also
    --------
    position_to_cursor : reciprocal of this function

    
z{} <= {}c                 s   s    | ]	}t |d  V  qdS )rO   N)rQ   )rB   r   r,   r,   r-   rF   q  s    z%cursor_to_position.<locals>.<genexpr>N)r   rQ   formatr   sum)rw   r   r  linesr,   r,   r-   cursor_to_positionW  s   
(r!  offsetc                 C   sb   d|  krt | ksn J d|t | f | d| }|d}|d}t |d }||fS )a:  
    Convert the position of the cursor in text (0 indexed) to a line
    number(0-indexed) and a column number (0-indexed) pair

    Position should be a valid position in ``text``.

    Parameters
    ----------
    text : str
        The text in which to calculate the cursor offset
    offset : int
        Position of the cursor in ``text``, 0-indexed.

    Returns
    -------
    (line, column) : (int, int)
        Line of the cursor; 0-indexed, column of the cursor 0-indexed

    See Also
    --------
    cursor_to_position : reciprocal of this function

    r   z0 <= %s <= %sNr  r_   )rQ   r   r:   )rw   r"  beforeblinesr   colr,   r,   r-   position_to_cursors  s   .

r&  c                 C   s   |t jv ot| tt||S )z@Checks if obj is an instance of module.class_name if loaded
    )rH   modulesr   r   r   )r   module
class_namer,   r,   r-   _safe_isinstance  s   
r*  c                 C   sv   t | dk rdS | d }|dkrdS | d }|tjv s|dv r!dS zt|}d| d| ffW S  ty:   Y dS w )uv  Match Unicode characters back to Unicode name

    This does  ``☃`` -> ``\snowman``

    Note that snowman is not a valid python3 combining character but will be expanded.
    Though it will not recombine back to the snowman character by the completion machinery.

    This will not either back-complete standard sequences like \n, \b ...

    Returns
    =======

    Return a tuple with two elements:

    - The Unicode character that was matched (preceded with a backslash), or
        empty string,
    - a sequence (of 1), name for the match Unicode character, preceded by
        backslash, or empty if no match.
    
    r8   r>   r,   r	  r@   r_   r7   r9   )rQ   stringascii_lettersunicodedatari   KeyError)rw   maybe_slashcharunicr,   r,   r-   back_unicode_name_matches  s   
r4  c                 C   sp   t | dk rdS | d }|dkrdS | d }|tjv s|dv r!dS zt| }d| |gfW S  ty7   Y dS w )uW   Match latex characters back to unicode name

    This does ``\ℵ`` -> ``\aleph``

    r8   r+  r	  r@   r_   r,  )rQ   r-  r.  r   r0  )rw   r1  r2  latexr,   r,   r-   back_latex_name_matches  s   r6  c                 C   s(   | j }|dstd| |dd S )a  
    Get parameter name and value from Jedi Private API

    Jedi does not expose a simple way to get `param=value` from its API.

    Parameters
    ----------
    parameter
        Jedi's function `Param`

    Returns
    -------
    A string like 'a', 'b=1', '*args', '**kwargs'

    zparam zWJedi function parameter description have change format.Expected "param ...", found %r".   N)descriptionrP   
ValueError)	parameterr8  r,   r,   r-   _formatparamchildren  s   
r;  c                 C   sf   t | dr |  }|sdS |  d }d| jdddd  S ddd	d
 dd |  D D  S )aR  
    Make the signature from a jedi completion

    Parameters
    ----------
    completion : jedi.Completion
        object does not complete a function type

    Returns
    -------
    a string consisting of the function signature, with the parenthesis but
    without the function name. example:
    `(a, *args, b=1, **kwargs)`

    get_signaturesz(?)r   (rO   )maxsplitz(%s)z, c                 S   s   g | ]}|r|qS r,   r,   rB   fr,   r,   r-   r     s    
z#_make_signature.<locals>.<listcomp>c                 s   s&    | ]}|  D ]}t|V  qqd S r   )defined_namesr;  )rB   rm   pr,   r,   r-   rF     s    z"_make_signature.<locals>.<genexpr>)r   r<  	to_stringr   rJ   )
completion
signaturesc0r,   r,   r-   _make_signature  s   
&rG  c                   @   s6   e Zd ZU eed< ee ed< ee ed< eed< dS )_CompleteResultmatched_textr   matches_originjedi_matchesN)r(   r)   r*   r   __annotations__r   r
   r,   r,   r,   r-   rH    s
   
 rH  c                	       s  e Zd ZU dZdZeeeef  e	d< e
ddd Zeddd	Zed
dd	jd
dZeddddjd
dZeddd	jd
dZedddjd
dZedddjd
dZe
ddd Z	dR fdd	Zedee fddZdedee fddZdefd d!Zdefd"d#Zdedee fd$d%Z defd&d'Z!dedee fd(d)Z"dedee fd*d+Z#d,e$d-e$dede%e fd.d/Z&dedee fd0d1Z'd2d3 Z(d4d5 Z)d6d7 Z*e+d8edee fd9d:Z,dedee fd;d<Z-e+dede.eee f fd=d>Z/dede.ee0e f fd?d@Z1dAdB Z2dedCe$de3e4 fdDdEZ5dFedCe$de3e4 fdGdHZ6dSde.ee0e f fdIdJZ7ddddKde8fdLdMZ9dede.ee0e f fdNdOZ:edee fdPdQZ;  Z<S )Tr$   z?Extension of the completer class with IPython-specific featuresN_IPCompleter__dict_key_regexpsr   c                 C   s    |d r
t | j_dS t| j_dS )z>update the splitter and readline delims when greedy is changednewN)GREEDY_DELIMSsplitterr   r   ro   changer,   r,   r-   _greedy_changed  s   zIPCompleter._greedy_changedFz%Whether to show dict key matches onlyr   TzWhether to merge completion results into a single list

        If False, only the completion results from the first non-empty
        completer will be returned.
        r   )r   rO   r8   r8   a1  Instruct the completer to omit private method names

        Specifically, when completing on ``object.<tab>``.

        When 2 [default]: all names that start with '_' will be excluded.

        When 1: all 'magic' names (``__foo__``) will be excluded.

        When 0: nothing will be excluded.
        r   a3  
        DEPRECATED as of version 5.0.

        Instruct the completer to use __all__ for the completion

        Specifically, when completing on ``object.<tab>``.

        When True: only those names in obj.__all__ will be included.

        When False [default]: the __all__ attribute is ignored
        zEIf True, emit profiling data for completion subsystem using cProfile.z.completion_profileszBTemplate for path at which to output profile data for completions.r   c                 C   s   t dt d S )Nz`IPython.core.IPCompleter.limit_to__all__` configuration value has been deprecated since IPython 5.0, will be made to have no effects and then removed in future version of IPython.)r2   r{   UserWarningrQ  r,   r,   r-   _limit_to_all_changedS  s   z!IPCompleter._limit_to_all_changedc                    s   t | _t | _t jd
|||d| g | _|| _t	d| _
tj| _tjdd}|dv | _tjdkr:| j| _n| j| _t	d| _t	d| _| j| jg| _d	| _d	| _d	S )a  IPCompleter() -> completer

        Return a completer object.

        Parameters
        ----------
        shell
            a pointer to the ipython shell itself.  This is needed
            because this completer knows about magic functions, and those can
            only be accessed via the ipython instance.
        namespace : dict, optional
            an optional dict where completions are performed.
        global_namespace : dict, optional
            secondary optional dict for completions, to
            handle cases (such as IPython embedded inside functions) where
            both Python scopes are visible.
        config : Config
            traitlet's config object
        **kwargs
            passed to super class unmodified.
        )r   r   r   z([^\\] )TERMxterm)dumbemacsr%   z^[\w|\s.]+\(([^)]*)\).*z[\s|\[]*(\w+)(?:\s*=\s*.*)Nr,   )r   magic_escaper   rP  r   rp   r   shellr   r   space_name_reglobrR   environgetdumb_terminalrH   rI   _clean_glob_win32
clean_glob_clean_globdocstring_sig_redocstring_kwd_remagic_config_matchesmagic_color_matchesmagic_arg_matcherscustom_completers_unicode_names)ro   r[  r   r   r   r   termr   r,   r-   rp   Z  s2   



zIPCompleter.__init__rM   c                 C   sX   | j r| jgS | jrg | j| j| j| jS g | j| j| j| j| j| jS )z*All active matcher routines for completion)dict_keys_onlydict_key_matchesr   r   file_matchesmagic_matchespython_matchespython_func_kw_matchesrq   r,   r,   r-   matchers  s2   zIPCompleter.matchersrw   c                    sb   | dd  t   fdd|t|D W  d   S 1 s%w   Y  |d S )zQ
        Wrapper around the completion methods for the benefit of emacs.
        r   r   c                    s,   g | ]} rj rd  |jgn|jqS )r   )r   rJ   rw   rA   r   ro   r,   r-   r     s    $z/IPCompleter.all_completions.<locals>.<listcomp>NrO   )
rpartitionr6   r   rQ   rj   ro   rw   r,   rs  r-   all_completions  s    zIPCompleter.all_completionsc                 C   s   |  d| S )N%s*r]  ru  r,   r,   r-   rc    s   zIPCompleter._clean_globc                 C   s   dd |  d| D S )Nc                 S   s   g | ]}| d dqS )r@   /rY   r?  r,   r,   r-   r     s    z1IPCompleter._clean_glob_win32.<locals>.<listcomp>rw  rx  ru  r,   r,   r-   ra    s   zIPCompleter._clean_glob_win32c                    sz  | dr|dd }dnd| j}t|d|v sd|v r"|}n*zt|d }W n! tyA   r;|d }ng  Y S Y n tyK   d}Y nw s\|t|kr\d}||}nd	}tj	
|}|dkrtfd
d| dD S tjdkr| |}n	| |dd}|rt|  fdd|D }nrtjdkr|nfdd|D }n	fdd|D }dd |D S )a  Match filenames, expanding ~USER type strings.

        Most of the seemingly convoluted logic in this completer is an
        attempt to handle filenames with spaces in them.  And yet it's not
        quite perfect, because Python's readline doesn't expose all of the
        GNU readline details needed for this to be done correctly.

        For a filename with a space in it, the printed completions will be
        only the parts after what's already been typed (instead of the
        full completions, as is normally done).  I don't think with the
        current (as of Python 2.3) Python readline it's possible to do
        better.!rO   Nr>   r=  r   r_   TFc                       g | ]} t | qS r,   rK   r?  text_prefixr,   r-   r         z,IPCompleter.file_matches.<locals>.<listcomp>*r%   r@   c                    s$   g | ]} t | d   qS r   r|  r?  )
len_lsplittext0r~  r,   r-   r     s
    c                    s   g | ]}t | qS r,   r|  r?  )open_quotesr,   r-   r     s    c                    r{  r,   r|  r?  r}  r,   r-   r     s
    c                 S   s$   g | ]}t j|r|d  n|qS )ry  )rR   rL   isdirrB   xr,   r,   r-   r     s   $ )rP   text_until_cursorr=   r   r9  r   r   rK   rR   rL   rS   r]  rH   rI   rb  rZ   rQ   )ro   rw   r  lsplithas_protectablesm0r   r,   )r  r  r  r~  r-   rn    sR   


zIPCompleter.file_matchesc                    s   | j j }|d }|d }| j |}| |  |s. fddn fddfdd|D }|sO|fdd|D 7 }|S )	zMatch magicsr   cellc                    s   |   o| vS )z
                Filter magics, in particular remove magics that match
                a name present in global namespace.
                rP   magic)	bare_textr   r,   r-   r   9  s   
z*IPCompleter.magic_matches.<locals>.matchesc                    s
   |   S r   r  r  )r  r,   r-   r   A  s   
c                       g | ]
} |r| qS r,   r,   rB   r   )r   pre2r,   r-   r   D      z-IPCompleter.magic_matches.<locals>.<listcomp>c                    r  r,   r,   r  )r   prer,   r-   r   F  r  )r[  magics_managerlsmagicrZ  rP   lstripr   )ro   rw   lsmline_magicscell_magicsexplicit_magiccompr,   )r  r   r   r  r  r-   ro     s   



zIPCompleter.magic_matchesc                    s  |   tdkrd dksd dkrttdd | jjD dd d}d	d |D }td
kr8|S d
 d}|d   fdd|D }d
 ddk rW|S t|d
kr|d  kr||  j	}|
 }ttdtjd|}fdd|   D S g S )z4 Match class names and attributes for %config magic r   r   z%configc                 S   s   g | ]}|j jd dr|qS )Tr   )r   class_traitsrA   r,   r,   r-   r   P  s    
z4IPCompleter.magic_config_matches.<locals>.<listcomp>c                 S   s   | j jS r   r   r(   r  r,   r,   r-   <lambda>R  s    z2IPCompleter.magic_config_matches.<locals>.<lambda>r  c                 S   s   g | ]}|j jqS r,   r  rA   r,   r,   r-   r   S  r   rO   r   c                       g | ]	}|  r|qS r,   r  rA   )	classnamer,   r-   r   \      
z^--r>   c                    s(   g | ]}|  d  r|dd qS )rO   r^   r   )rP   r   )rB   r   )textsr,   r-   r   h  s    )stripr   rQ   sortedrG   r[  configurablesfindr  r   class_get_helpr   r   r   	MULTILINE
splitlines)ro   rw   classes
classnamesclassname_textsclassname_matchesclsr   r,   )r  r  r-   rf  J  s,   $

z IPCompleter.magic_config_matchesc                    sb   |  }|dr|d t|dkr/|d dks |d dkr/|d   fdd	t D S g S )
z& Match color schemes for %colors magicr&   r>   r8   r   colorsz%colorsrO   c                    r  r,   r  )rB   colorr   r,   r-   r   w  r  z3IPCompleter.magic_color_matches.<locals>.<listcomp>)r   ra   r   rQ   r   r   )ro   rw   r  r,   r  r-   rg  m  s   

$zIPCompleter.magic_color_matchescursor_columncursor_linec              
   C   s  | j g}| jdur|| j dd }t|||}|rK||d  }|dkrK| jdkr/dd }n| jdkr9dd }n| jd	krCd
d }ntd| jt|d| |}d}	z.d}
zt	dd |
 jjD }W n	 tyr   Y nw t|jd	ko|jd	 dv }
|
 }	W n ty } z| jrtd|d W Y d}~nd}~ww |	sg S zt||j||d dW S  ty } z| jrtd| gW  Y d}~S g W  Y d}~S d}~ww )a?  
        Return a list of :any:`jedi.api.Completions` object from a ``text`` and
        cursor position.

        Parameters
        ----------
        cursor_column : int
            column position of the cursor in ``text``, 0-indexed.
        cursor_line : int
            line position of the cursor in ``text``, 0-indexed
        text : str
            text to complete

        Notes
        -----
        If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
        object containing a string with the Jedi debug information attached.
        Nc                 S      | S r   r,   r  r,   r,   r-   r        z+IPCompleter._jedi_matches.<locals>.<lambda>rO   r   r8   c                 S   s   | j d S )Nr]   )ri   rP   rC   r,   r,   r-   r    s    c                 S   s   | j do| j d S )Nr\   )ri   rP   ra   r  r,   r,   r-   r    r   r   c                 S   r  r   r,   r  r,   r,   r-   r    r  z'Don't understand self.omit__names == {}TFc                 s   s    | ]
}t |d r|V  qdS )valueN)r   rA   r,   r,   r-   rF     s    z,IPCompleter._jedi_matches.<locals>.<genexpr>>   r7   r9   z5Error detecting if completing a non-finished string :|)r  r   zJOops Jedi has crashed, please report a bug with the following:
"""
%s
s""")r   r   r   r!  omit__namesr9  r  r   Interpreternext_get_module	tree_nodechildrenStopIterationrQ   r  r   r   r   filterrj   rf   )ro   r  r  rw   
namespacescompletion_filterr"  r  interpretertry_jedicompleting_stringfirst_childer,   r,   r-   _jedi_matches{  sR   







zIPCompleter._jedi_matchesc                 C   s   d|v r:z)|  |}|dr(| jr+| jdkrdd }ndd }t||}W |S W |S W |S  ty9   g }Y |S w | |}|S )z'Match attributes or global python namesr   rO   c                 S   s   t d| d u S )Nz.*\.__.*?__)r   r   txtr,   r,   r-   r    s   z,IPCompleter.python_matches.<locals>.<lambda>c                 S   s   t d| | dd  d u S )Nz\._.*?r   )r   r   rindexr  r,   r,   r-   r    s   )r   ra   r  r  	NameErrorr   )ro   rw   r   no__namer,   r,   r-   rp    s&   



r   c                 C   sh   |du rg S |   d }| j|}|du rg S | d d}g }|D ]
}|| j|7 }q'|S )a  Parse the first line of docstring for call signature.

        Docstring should be of the form 'min(iterable[, key=func])
'.
        It can also parse cython docstring of the form
        'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
        Nr   ,)r  r  rd  r  groupsr   re  findall)ro   docr   sigretr<   r,   r,   r-   !_default_arguments_from_docstring  s   z-IPCompleter._default_arguments_from_docstringc                    s   |}g }t |r
n/t |s9t |s9t |r1|| t|dd7 }t|ddp/t|dd}nt|dr9|j}|| t|dd7 }t j	j
t j	jf zt |}| fdd|j D  W n	 tyk   Y nw tt|S )	z_Return the list of default arguments of obj if it is callable,
        or empty list otherwise.r+   r>   rp   N__new____call__c                 3   s"    | ]\}}|j  v r|V  qd S r   )kind)rB   r   v_keepsr,   r-   rF     s   
 
z1IPCompleter._default_arguments.<locals>.<genexpr>)inspect	isbuiltin
isfunctionismethodisclassr  r   r   r  	ParameterKEYWORD_ONLYPOSITIONAL_OR_KEYWORDrm   extend
parametersitemsr9  r   rG   )ro   r   call_objr  r  r,   r  r-   _default_arguments  s6   






"zIPCompleter._default_argumentsc                 C   s  d|v rg S z| j }W n ty!   tdtjtjB  }| _ Y nw || j}t|}d}|D ]}|dkr;|d8 }q0|dkrI|d7 }|dkrI nq0g S g }tdj	}	 z|
t| ||d	 si|  W nt|dksqW nW n	 ty{   Y nw qUt }	d	}
t||dd
 D ]$\}}|dkr|
d7 }
n|dkr|
d8 }
|
dkrq|dkrq|	| qg }z+d|d
d
d	 }| t|| j}t||	 D ]}||r|
d|  qW |S    Y |S )z9Match named parameters (kwargs) of the last open functionr   z
                '.*?(?<!\\)' |    # single quoted strings or
                ".*?(?<!\\)" |    # double quoted strings or
                \w+          |    # identifier
                \S                # other characters
                r   )rO   r=  z\w+$Tr_   Nr^   z%s=)_IPCompleter__funcParamsRegexr  r   r   VERBOSEDOTALLr  r  reversedr   r   r  popr  rG   r   r   rJ   r  r   r   rP   )ro   rw   regexptokens
iterTokensopenPartokenidsisIdusedNamedArgs	par_level
next_token
argMatchescallableObj	namedArgsnamedArgr,   r,   r-   rq    sx   




z"IPCompleter.python_func_kw_matchesr   c                 C   s|   t | d}|d ur| S t| tst| ddr*zt|  W S  ty)   g  Y S w t| dds6t| ddr<| jjp;g S g S )N_ipython_key_completions_pandas	DataFramenumpyndarrayvoid)	r   r   dictr*  r   r   r   dtypenames)r   methodr,   r,   r-   	_get_keysa  s    



zIPCompleter._get_keysc                    s  | j dur	| j }nd}t|d t|d d }| _ || j | j}|du r,g S | \}}}zt|| j}W n t	yZ   zt|| j
}W n t	yW   g  Y  Y S w Y nw | |}	|	sd|	S |dkrlt|nd}
t|	|| jj|
d\}}}|s|S t| jt| }|r|d}|| }n|  }}||krd n|||  |d	}d| jt| jd }||kr|r||r|t|d }n|7 ||kr|d
s݈d
7  fdd|D S )z5Match string keys in a dictionary, after e.g. 'foo[' Na  (?x)
            (  # match dict-referring expression wrt greedy setting
                %s
            )
            \[   # open bracket
            \s*  # and optional whitespace
            # Capture any number of str-like objects (e.g. "a", "b", 'c')
            ((?:[uUbB]?  # string prefix (r not handled)
                (?:
                    '(?:[^']|(?<!\\)\\')*'
                |
                    "(?:[^"]|(?<!\\)\\")*"
                )
                \s*,\s*
            )*)
            ([uUbB]?  # string prefix (r not handled)
                (?:   # unclosed string
                    '(?:[^']|(?<!\\)\\')*
                |
                    "(?:[^"]|(?<!\\)\\")*
                )
            )?
            $
            z
                                  # identifiers separated by .
                                  (?!\d)\w+
                                  (?:\.(?!\d)\w+)*
                                  zF
                                 .+
                                 )FTr>   )r   r   rO   r   c                    s   g | ]} |  qS r,   r,   r  leadingsufr,   r-   r     r  z0IPCompleter.dict_key_matches.<locals>.<listcomp>)rM  r   r   r   r  r  r  r   r   r   r   r  r  rP  r   rQ   ru   rv   r   rP   )ro   rw   regexpsdict_key_re_fmtr   r   prefix0r   r   r   r   closing_quotetoken_offsetr   
text_start	key_startcompletion_startbracket_idxcontinuationr,   r	  r-   rm  u  s\   






zIPCompleter.dict_key_matchesc                 C   st   |  d}|dkr6| |d d }zt|}d|  r%d| |gfW S W dg fS  ty5   Y dg fS w dg fS )u  Match Latex-like syntax for unicode characters base
        on the name of the character.

        This does  ``\GREEK SMALL LETTER ETA`` -> ``η``

        Works only on valid python 3 identifier, or on combining characters that
        will combine to form a valid identifier.
        r@   r_   rO   Nar>   )rfindr/  lookupisidentifierr0  )rw   slashposr<   r3  r,   r,   r-   unicode_name_matches  s   


z IPCompleter.unicode_name_matchesc                    sV   | d}|dkr)||d   tv r t  gfS  fddtD }|r) |fS dS )u{   Match Latex syntax for unicode characters.

        This does both ``\alp`` -> ``\alpha`` and ``\alpha`` -> ``α``
        r@   r_   Nc                    r  r,   r  r  r;   r,   r-   r     r   z-IPCompleter.latex_matches.<locals>.<listcomp>r+  )r  r   )ro   rw   r  r   r,   r;   r-   latex_matches  s   
zIPCompleter.latex_matchesc           	   	      s  | j sd S | j}| sd S t }||_ |_|d dd }||_| j|_|	| j
s6| j | j
| }ng }t| j ||| j | jD ]>}z(||}|rq fdd|D }|ra|W   S   fdd|D W   S W qH ty{   Y qH ty   	 Y  d S w d S )NrO   r   c                    r  r,   r  rB   r)rw   r,   r-   r   '  r   z9IPCompleter.dispatch_custom_completer.<locals>.<listcomp>c                    s   g | ]}|   r|qS r,   )lowerrP   r  )text_lowr,   r-   r   ,  s    )ri  r   r  r   r   symbolr   commandr  rP   rZ  	s_matches	itertoolschainflat_matchesr  r   KeyboardInterrupt)	ro   rw   r   eventcmd	try_magicrC   reswithcaser,   )rw   r   r-   dispatch_custom_completer  sJ   
z%IPCompleter.dispatch_custom_completerr"  c                 c   s,   t jdtdd t }zdz1| jrddl}| }|  nd}| j||| j	d dD ]}|r4||v r4q+|V  |
| q+W n
 tyH   	 Y nw W |duro|  t| j tj| jtt }td| || dS dS |dur|  t| j tj| jtt }td| || w w )	a  
        Returns an iterator over the possible completions

        .. warning::

            Unstable

            This function is unstable, API may change without warning.
            It will also raise unless use in proper context manager.

        Parameters
        ----------
        text : str
            Full text of the current input, multi line string.
        offset : int
            Integer representing the position of the cursor in ``text``. Offset
            is 0-based indexed.

        Yields
        ------
        Completion

        Notes
        -----
        The cursor on a text can either be seen as being "in between"
        characters or "On" a character depending on the interface visible to
        the user. For consistency the cursor being on "in between" characters X
        and Y is equivalent to the cursor being "on" character Y, that is to say
        the character the cursor is on is considered as being after the cursor.

        Combining characters may span more that one position in the
        text.

        .. note::

            If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
            fake Completion token to distinguish completion returned by Jedi
            and usual IPython completion.

        .. note::

            Completions are not completely deduplicated yet. If identical
            completions are coming from different sources this function does not
            ensure that each completion object will only be present once.
        zy_complete is a provisional API (as of IPython 6.0). It may change without warnings. Use in corresponding context manager.r8   ry   r   Ni  )_timeoutzWriting profiler output to)r2   r{   r'   rG   profile_completionscProfileProfileenable_completionsr   r   r'  disabler   profiler_output_dirrR   rL   rJ   r   uuiduuid4r   
dump_stats)ro   rw   r"  r   r0  profilerrC   output_pathr,   r,   r-   r   8  sF   .




zIPCompleter.completions	full_textc             	   c   s   t  | }|d| }t||\}}| j|||d\}}	}
}t|}|ro|D ]F}z|j}W n tyB   | jr>td| d}Y nw t	|j
t	|j }|dkrVt|}nd}t|| ||j
||ddV  t  |krn nq(|D ]}t	|j
t	|j }t|| ||j
dddd	V  qq||}|r|	r| jrt||d
ddddV  ||sJ t|	|
D ]\}}t||||dddV  qdS )ax  
        Core completion module.Same signature as :any:`completions`, with the
        extra `timeout` parameter (in seconds).

        Computing jedi's completion ``.type`` can be quite expensive (it is a
        lazy property) and can require some warm-up, more warm up than just
        computing the ``name`` of a completion. The warm-up can be :

            - Long warm-up the first time a module is encountered after
            install/update: actually build parse/inference tree.

            - first time the module is encountered in a session: load tree from
            disk.

        We don't want to block completions for tens of seconds so we give the
        completer a "budget" of ``_timeout`` seconds per invocation to compute
        completions types, the completions that have not yet been computed will
        be marked as "unknown" an will have a chance to be computed next round
        are things get cached.

        Keep in mind that Jedi is not the only thing treating the completion so
        keep the timeout short-ish as if we take more than 0.3 second we still
        have lots of processing to do.

        N)r;  r  r   zError in Jedi getting type of functionr>   r   rt   z	<unknown>)ru   rv   rw   rk   rn   rm   z--jedi/ipython--r   none)ru   rv   rw   rn   rk   rm   )ru   rv   rw   rn   rm   rk   )time	monotonicr&  	_completeiterrk   r   r   r   rQ   rl   rj   rG  rs   r  ra   r   )ro   r;  r"  r.  deadliner#  r  r  rI  r   rJ  rK  iter_jmjmtype_deltarm   start_offsetr   tr,   r,   r-   r3    sb   




zIPCompleter._completionsc                 C   s&   t dt | j|||dddd S )a  Find completions for the given text and line context.

        Note that both the text and the line_buffer are optional, but at least
        one of them must be given.

        Parameters
        ----------
        text : string, optional
            Text to perform the completion on.  If not given, the line buffer
            is split using the instance's CompletionSplitter object.
        line_buffer : string, optional
            If not given, the completer attempts to obtain the current line
            buffer via readline.  This keyword allows clients which are
            requesting for text completions in non-readline contexts to inform
            the completer of the entire text.
        cursor_pos : int, optional
            Index of the cursor in the full line buffer.  Should be provided by
            remote frontends where kernel has no access to frontend state.

        Returns
        -------
        Tuple of two items:
        text : str
            Text that was actually used in the completion.
        matches : list
            A list of completion matches.

        Notes
        -----
            This API is likely to be deprecated and replaced by
            :any:`IPCompleter.completions` in the future.

        zn`Completer.complete` is pending deprecation since IPython 6.0 and will be replaced by `Completer.completions`.r   )r   r   rw   r  Nr8   )r2   r{   PendingDeprecationWarningr@  )ro   rw   r   r   r,   r,   r-   rj     s   "zIPCompleter.complete)r   rw   r;  c                   s  |du r|du rt |nt |}| jrtj| _|s"|r"|d| }|s/|r-| j||nd}| jrg|s6|n|d| }| j	| j
tt| jfD ] }||\}}	|rft||	dt |jgtt |	t d  S qF|du rm|}|| _| jd| | _| jD ] t |dt }
|
r jgt |
 }t||
|d  S q{g }
t |dko|d dk}g }| jr|s|s|}| |||}| jrg }
| jD ] z|
 fdd |D  W q   tjt   Y qn| jD ]  fd	d |D }
|
r nqt }t }|
D ]}|\}}||vr|| || q t |d
d d}dd | !|p)g D }|p0|}|dt }dd |D }dd |D }|| _"t||||S )aQ  
        Like complete but can also returns raw jedi completions as well as the
        origin of the completion text. This could (and should) be made much
        cleaner but that will be simpler once we drop the old (and stateful)
        :any:`complete` API.

        With current provisional API, cursor_pos act both (depending on the
        caller) as the offset in the ``text`` or ``line_buffer``, or as the
        ``column`` when passing multiline strings this could/should be renamed
        but would add extra noise.

        Parameters
        ----------
        cursor_line
            Index of the line the cursor is on. 0 indexed.
        cursor_pos
            Position of the cursor in the current line/line_buffer/text. 0
            indexed.
        line_buffer : optional, str
            The current line the cursor is in, this is mostly due to legacy
            reason that readline could only give a us the single current line.
            Prefer `full_text`.
        text : str
            The current "token" the cursor is in, mostly also for historical
            reasons. as the completer would trigger only after the current line
            was parsed.
        full_text : str
            Full text of the current cell.

        Returns
        -------
        A tuple of N elements which are (likely):
            matched_text: ? the text that the complete matched
            matches: list of completions ?
            matches_origin: ? list same length as matches, and where each completion came from
            jedi_matches: list of Jedi matches, have it's own structure.
        Nr  r>   r,   r   r`   c                       g | ]}| j fqS r,   r*   r  matcherr,   r-   r   j      z)IPCompleter._complete.<locals>.<listcomp>c                    rJ  r,   rK  r  rL  r,   r-   r   r  rN  c                 S   s   t | d S )Nr   )re   r  r,   r,   r-   r    s    z'IPCompleter._complete.<locals>.<lambda>r  c                 S   s   g | ]}|d fqS )customr,   r  r,   r,   r-   r     r   c                 S   r   r   r,   r  r,   r,   r-   r     r   c                 S   r   )rO   r,   r  r,   r,   r-   r     r   )#rQ   r   r   r   r   r   rP  r   r   r  r  r6  r4  fwd_unicode_matchrH  MATCHES_LIMITr*   r   r   r  rh  r   r   r  merge_completionsrr  r  rH   
excepthookexc_inforG   r   r  r-  r   )ro   r  r   r   rw   r;  	base_textmeth	name_textname_matchesr   originsis_magic_prefixr   r   filtered_matchesr   rH  rC   _filtered_matches
custom_res_matchesr,   rL  r-   r@    s   +



	




zIPCompleter._completec                    s   | d}|dkrL||d d }| fdd| jD }|r%||fS fdd| jD }|r5||fS d  fd	d| jD }|rJ||fS d
S d
S )a}  
        Forward match a string starting with a backslash with a list of
        potential Unicode completions.

        Will compute list list of Unicode character names on first call and cache it.

        Returns
        -------
        At tuple with:
            - matched text (empty if no matches)
            - list of potential completions, empty tuple  otherwise)
        r@   r_   rO   Nc                    r  r,   r  r  supr,   r-   r     r   z1IPCompleter.fwd_unicode_match.<locals>.<listcomp>c                    s   g | ]} |v r|qS r,   r,   r  r_  r,   r-   r     r  r&   c                    s&   g | ] t  fd dD r qS )c                 3   s    | ]}| v V  qd S r   r,   )rB   ur  r,   r-   rF     r   z;IPCompleter.fwd_unicode_match.<locals>.<listcomp>.<genexpr>)all)rB   )splitsupr  r-   r     s
    r+  )r  upperunicode_namesr   )ro   rw   r  r<   
candidatesr,   )rc  r`  r-   rP    s$   


zIPCompleter.fwd_unicode_matchc              	   C   sX   | j du r)g }tddD ]}z|tt| W q ty#   Y qw tt| _ | j S )z}List of names of unicode code points that can be completed.

        The list is lazily initialized on first access.
        Nr   i   )	rj  ranger   r/  ri   chrr9  _unicode_name_compute_UNICODE_RANGES)ro   r  rC   r,   r,   r-   re    s   

zIPCompleter.unicode_names)NNNN)NNN)=r(   r)   r*   r+   rM  r   r   boolr   rL  r    rS  r   rl  r   rR  r   r  r   r/  r   r5  rU  rp   r   r   r
   rr  r   rv  rc  ra  rn  ro  rf  rg  r   r   r  rp  r  r  rq  staticmethodr  rm  r   r  r   r  r-  r   rs   r   r3  rj   rH  r@  rP  re  r   r,   r,   r   r-   r$     s   
 

KR*#H"Lh 0NT)
 :rangesc              
   C   sP   g }| D ]!\}}t ||D ]}z|tt| W q ty$   Y qw q|S r   )rg  r   r/  ri   rh  r9  )rm  r  ru   stoprC   r,   r,   r-   ri    s   ri  )r1   r   )pr+   builtinsr   r]  r  r$  r   rR   r   r-  rH   r>  r/  r6  r2   
contextlibr   	importlibr   typesr   typingr   r   r   r   r	   r
   r   r   r   r   r   IPython.core.errorr   IPython.core.inputtransformer2r   IPython.core.latex_symbolsr   r   IPython.core.oinspectr   IPython.testing.skipdoctestr   IPython.utilsr   IPython.utils.dir2r   r   IPython.utils.pathr   IPython.utils.processr   	traitletsr   r   r   	ListTraitr   r   r    traitlets.config.configurabler!   r   __skip_doctest__r   settingscase_insensitive_completionjedi.api.helpersjedi.api.classesr   ImportErrorrj  r   rI   PROTECTABLESrQ  FutureWarningr'   r4   r6   r=   rK   r   rk  rX   r[   re   rf   rs   _ICr   r   r   rO  objectr   r#   r   r   r   r  r!  r&  r*  r4  r6  r;  rG  rH  r$   ri  r,   r,   r,   r-   <module>   s    p4$
	(	 > *;4 (*
^"'         &I