
    Mh                      U d Z ddlm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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 ddlmZ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* ddl+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZGmHZHmIZImJZKmLZLmMZNmOZOm#ZPmQZQ ddlRmSZS ddlTmUZU ddlVZVddl mWZW ejX        dk     rddlYmZZZm[Z[m\Z\m]Z]m^Z^ nddl mZZZm[Z[m\Z\m]Z]m^Z^ dZ_	 ddl`Z`de`ja        _b        ddlcZ`ddldZ`dZen# ef$ r dZeY nw xY wdd gZgd!d"gZheji        d#k    rd$Zjnd%Zjd&Zkd'Zl em            Zn G d( d)eo          Zp ejq        d*ep+           e6edd-                        Zrdd2Zsejfdd4Ztdd7Zudd;Zvd< Zw G d= d>          Zxe#d?exf         Zy G d@ dA          Zz G dB dC          Z{ G dD dEeZ          Z| e<ddFgG           G dH dIe|eZ                      Z} G dJ dKe|          Z~e#eye{f         Z e)dLeez          Ze G dM dN                      Ze#e}e~f         Z G dO dPe\          Z G dQ dRee\          Ze#eef         ZdSedT<    G dU dVe\          Ze#eef         ZdSedW<   ddZZdd\Zdd`ZddbZddeZdddfdgddoZddpZddqZdr Z eedst          Ze!ez         ZddxZddydd{Zeji        d#k    rd|Znd}Zd~Z G d d          Z G d d!eS          Zd Z G d dej                  Zd ZddZeeedZ	 dddZddZddZd Z e            dd            ZddZ e            dd            ZddZddZeeef         Z ej        d          ZddZ	 	 dddZ G d d"e          ZddZdS )u  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 :kbd:`Tab` to expand it to its latex form.

.. code::

    \α<tab>
    \alpha


Both forward and backward completions can be deactivated by setting the
:std:configtrait:`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 almost any code unlike the deprecated :any:`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.

Matchers
========

All completions routines are implemented using unified *Matchers* API.
The matchers API is provisional and subject to change without notice.

The built-in matchers include:

- :any:`IPCompleter.dict_key_matcher`:  dictionary key completions,
- :any:`IPCompleter.magic_matcher`: completions for magics,
- :any:`IPCompleter.unicode_name_matcher`,
  :any:`IPCompleter.fwd_unicode_matcher`
  and :any:`IPCompleter.latex_name_matcher`: see `Forward latex/unicode completion`_,
- :any:`back_unicode_name_matcher` and :any:`back_latex_name_matcher`: see `Backward latex completion`_,
- :any:`IPCompleter.file_matcher`: paths to files and directories,
- :any:`IPCompleter.python_func_kw_matcher` - function keywords,
- :any:`IPCompleter.python_matches` - globals and attributes (v1 API),
- ``IPCompleter.jedi_matcher`` - static analysis with Jedi,
- :any:`IPCompleter.custom_completer_matcher` - pluggable completer with a default
  implementation in :any:`InteractiveShell` which uses IPython hooks system
  (`complete_command`) with string dispatch (including regular expressions).
  Differently to other matchers, ``custom_completer_matcher`` will not suppress
  Jedi results to match behaviour in earlier IPython versions.

Custom matchers can be added by appending to ``IPCompleter.custom_matchers`` list.

Matcher API
-----------

Simplifying some details, the ``Matcher`` interface can described as

.. code-block::

    MatcherAPIv1 = Callable[[str], list[str]]
    MatcherAPIv2 = Callable[[CompletionContext], SimpleMatcherResult]

    Matcher = MatcherAPIv1 | MatcherAPIv2

The ``MatcherAPIv1`` reflects the matcher API as available prior to IPython 8.6.0
and remains supported as a simplest way for generating completions. This is also
currently the only API supported by the IPython hooks system `complete_command`.

To distinguish between matcher versions ``matcher_api_version`` attribute is used.
More precisely, the API allows to omit ``matcher_api_version`` for v1 Matchers,
and requires a literal ``2`` for v2 Matchers.

Once the API stabilises future versions may relax the requirement for specifying
``matcher_api_version`` by switching to :any:`functools.singledispatch`, therefore
please do not rely on the presence of ``matcher_api_version`` for any purposes.

Suppression of competing matchers
---------------------------------

By default results from all matchers are combined, in the order determined by
their priority. Matchers can request to suppress results from subsequent
matchers by setting ``suppress`` to ``True`` in the ``MatcherResult``.

When multiple matchers simultaneously request suppression, the results from of
the matcher with higher priority will be returned.

Sometimes it is desirable to suppress most but not all other matchers;
this can be achieved by adding a set of identifiers of matchers which
should not be suppressed to ``MatcherResult`` under ``do_not_suppress`` key.

The suppression behaviour can is user-configurable via
:std:configtrait:`IPCompleter.suppress_competing_matchers`.
    )annotationsN)literal_eval)defaultdict)contextmanager)	dataclass)cached_propertypartial)SimpleNamespace)
IterableIteratorUnionAnySequenceOptionalTYPE_CHECKINGSizedTypeVarLiteral)guarded_evalEvaluationContext)TryNext)	ESC_MAGIC)latex_symbolsreverse_latex_symbol)skip_doctest)generics)theme_table)sphinx_options)dir2get_real_method)GENERATING_DOCUMENTATION)ensure_dir_exists)	arg_split)	BoolEnumIntListUnicodeDictDottedObjectNamer   observe)Configurable)import_item)cast)      )	TypedDictNotRequiredProtocol	TypeAlias	TypeGuardTF)    i# )i  i 	CompleterIPCompleterwin32 z ()[]{}?=\|;:'#*"^&i  z	<unknown>c                      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__     V/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/IPython/core/completer.pyr<   r<   (  s          	DrB   r<   errorcategoryignorec              #     K   t          j                    5  t          j        | t                     dV  ddd           dS # 1 swxY 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!
    rE   N)warningscatch_warningsfilterwarningsr<   )actions    rC   provisionalcompleterrM   4  s      2 
	 	"	"  1LMMMM                 s    AA
AsstrreturnUnion[str, bool]c                n    |                      d          dz  rdS |                      d          dz  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)rN   s    rC   has_open_quotesrW   R  sA     	wws||a s	
	 surB   protectablesc                    t          |           t                    z  r9t          j        dk    rd| z   dz   S d                    fd| D                       S | S )z.Escape a string to protect certain characters.r9   rS    c              3  .   K   | ]}|v rd |z   n|V  dS \NrA   ).0crX   s     rC   	<genexpr>z#protect_filename.<locals>.<genexpr>m  s5      MMa\(9(9D1HHqMMMMMMrB   )setsysplatformjoin)rN   rX   s    `rC   protect_filenamere   g  se    
1vvL!!! <7""7S= 77MMMM1MMMMMMrB   pathtuple[str, bool, str]c                    d}d}| }|                      d          rCd}t          |           dz
  }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.
    FrZ   ~T   N)
startswithlenosrf   
expanduser)rf   tilde_expand	tilde_valnewpathrests        rC   expand_userrs   r  s{    0 LIGs  4yy{'$$T** 	 $IIIL)++rB   ro   boolrp   c                6    |r|                      |d          S | S )z8Does the opposite of expand_user, with its outputs.
    ri   replace)rf   ro   rp   s      rC   compress_userrx     s%      ||Is+++rB   c                X   d\  }}|                      d          rd}n|                      d          rd}|                     d          rd}|                      d          rd	| dd
         vr| dd
         } d}n-|                      d	          rd	| dd
         vr| 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   __rT   _rj   =z%%%N)rk   endswith)wordprio1prio2s      rC   completions_sorting_keyr     s     LE5t 			 }}S t d122h8DE			 d122h8DE$rB   c                      e Zd ZdZd Z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                h    || _         || _        d| _        || _        d| _        d| _        d| _        d S )NcrashedrZ   fake)namecompletetypename_with_symbols	signature_origintext)selfr   s     rC   __init__z_FakeJediCompletion.__init__  s8    		!%			rB   c                    dS )Nz)<Fake completion object jedi has crashed>rA   r   s    rC   __repr__z_FakeJediCompletion.__repr__  s    ::rB   N)r=   r>   r?   r@   r   r   rA   rB   rC   r   r     s<           ; ; ; ; ;rB   r   zjedi.api.Completionc                  @    e Zd ZdZg dZddddddZd ZddZd ZdS )
Completionao  
    Completion object used and returned 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endr   r   r   r   NrZ   r   r   r   r   intr   r   rO   r   Optional[str]rP   Nonec                   t          j        dt          d           || _        || _        || _        || _        || _        || _        d S )Nz~``Completion`` is a provisional API (as of IPython 6.0). It may change without warnings. Use in corresponding context manager.rT   rF   
stacklevel)	rI   warnr<   r   r   r   r   r   r   )r   r   r   r   r   r   r   s          rC   r   zCompletion.__init__  sZ     	4 1	
 	
 	
 	
 
		"rB   c                `    d| j         d| j        d| j        d| j        pdd| j        pddS )Nz<Completion start=z end=z text= type=?z, signature=z,>)r   r   r   r   r   r   s    rC   r   zCompletion.__repr__  sH     TXXXtyyy$)2Bs2B2BDNDYVYDYDY[ 	[rB   rt   c                b    | 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.
        )r   r   r   )r   others     rC   __eq__zCompletion.__eq__  s7     zU[( $H	!$I#	$rB   c                D    t          | j        | j        | j        f          S N)hashr   r   r   r   s    rC   __hash__zCompletion.__hash__#  s    TZ495666rB   )
r   r   r   r   r   rO   r   r   rP   r   )rP   rt   )	r=   r>   r?   r@   	__slots__r   r   r   r   rA   rB   rC   r   r     s         0 IHHI #     2[ [ [$ $ $ $7 7 7 7 7rB   r   c                  .    e Zd ZdZddgZddd
dZd	 ZdS )SimpleCompletiona  Completion item to be included in the dictionary returned by new-style Matcher (API v2).

    .. warning::

        Provisional

        This class is used to describe the currently supported attributes of
        simple completion items, and any additional implementation details
        should not be relied on. Additional attributes may be included in
        future versions, and meaning of text disambiguated from the current
        dual meaning of "text to insert" and "text to used as a label".
    r   r   Nr   rO   r   c               "    || _         || _        d S r   r   r   )r   r   r   s      rC   r   zSimpleCompletion.__init__7  s    				rB   c                (    d| j         d| j        dS )Nz<SimpleCompletion text=r   >r   r   s    rC   r   zSimpleCompletion.__repr__;  s    JJJDIJJJJrB   )r   rO   r   r   )r=   r>   r?   r@   r   r   r   rA   rB   rC   r   r   '  s_           I;?      K K K K KrB   r   c                  <    e Zd ZU dZded<   ded<   ded<   ded	<   d
S )_MatcherResultBasezFDefinition of dictionary to be returned by new-style Matcher (API v2).zNotRequired[str]matched_fragmentz"NotRequired[Union[bool, set[str]]]suppresszNotRequired[set[str]]do_not_suppresszNotRequired[bool]orderedNr=   r>   r?   r@   __annotations__rA   rB   rC   r   r   ?  sP         PP '&&& 1000 +*** rB   r   dict)show_inherited_membersexclude_inherited_fromc                      e Zd ZU dZded<   dS )SimpleMatcherResultz'Result of new-style completion matcher.z7Sequence[SimpleCompletion] | Iterator[SimpleCompletion]completionsNr   rA   rB   rC   r   r   Q  s'         11 IHHHHHrB   r   c                      e Zd ZU dZded<   dS )_JediMatcherResultz@Matching result returned by Jedi (will be processed differently)Iterator[_JediCompletionLike]r   Nr   rA   rB   rC   r   r   \  s&         JJ /.....rB   r   AnyCompletionc                  v    e Zd ZU dZded<   ded<   ded<   ded<   ded	<   edd            Zedd            ZdS )CompletionContextzMCompletion context provided as an argument to matchers in the Matcher API v2.rO   token	full_textr   cursor_positioncursor_linezOptional[int]limitrP   c                *    | j         d | j                 S r   )line_with_cursorr   r   s    rC   text_until_cursorz#CompletionContext.text_until_cursor  s    $%;t';%;<<rB   c                L    | j                             d          | j                 S )N
)r   splitr   r   s    rC   r   z"CompletionContext.line_with_cursor  s     ~##D))$*:;;rB   NrP   rO   )r=   r>   r?   r@   r   r   r   r   rA   rB   rC   r   r   g  s         WW JJJ NNN   = = = _= < < < _< < <rB   r   c                  "    e Zd ZU ddZded<   dS )	_MatcherAPIv1Baser   rO   rP   	list[str]c                    dS zCall signature.NrA   r   r   s     rC   __call__z_MatcherAPIv1Base.__call__      rB   r?   Nr   rO   rP   r   )r=   r>   r?   r   r   rA   rB   rC   r   r     s4            
 rB   r   c                  "    e Zd ZU ded<   d	dZdS )
_MatcherAPIv1TotalzOptional[Literal[1]]matcher_api_versionr   rO   rP   r   c                    dS r   rA   r   s     rC   r   z_MatcherAPIv1Total.__call__  r   rB   Nr   )r=   r>   r?   r   r   rA   rB   rC   r   r     s6         ----     rB   r   r4   MatcherAPIv1c                  4    e Zd ZU dZdZded<   dd	Zd
ed<   dS )MatcherAPIv2z#Protocol describing Matcher API v2.rT   z
Literal[2]r   contextr   rP   MatcherResultc                    dS r   rA   )r   r   s     rC   r   zMatcherAPIv2.__call__  r   rB   rO   r?   N)r   r   rP   r   )r=   r>   r?   r@   r   r   r   rA   rB   rC   r   r     sN         -- '(''''   
 rB   r   MatchermatcherTypeGuard[MatcherAPIv1]c                ,    t          |           }|dk    S )Nrj   _get_matcher_api_versionr   api_versions     rC   _is_matcher_v1r         *733K!rB   TypeGuard[MatcherAPIv2]c                ,    t          |           }|dk    S )NrT   r   r   s     rC   _is_matcher_v2r     r   rB   valuer   TypeGuard[Sized]c                "    t          | d          S )%Determines whether objects is sizable__len__hasattrr   s    rC   _is_sizabler     s    5)$$$rB   TypeGuard[Iterator]c                "    t          | d          S )r   __next__r   r   s    rC   _is_iteratorr     s    5*%%%rB   resultr   c                J   | d         }t          |          rt          |          dk    S t          |          r\	 |}t          |          }t	          t
          t                   t          j        |g|                    | d<   dS # t          $ r Y dS w xY wt          d          )z-Check if any result includes any completions.r   r   TFzCCompletions returned by matcher need to be an Iterator or a Sizable)r   rl   r   nextr.   r   r   	itertoolschainStopIteration
ValueError)r  r   old_iteratorfirsts       rC   has_any_completionsr
    s    'K; %;1$$K   
		&L&&E$()*66% %F=! 4 	 	 	55	
M  s   AB 
BBrj   )priority
identifierr   r  Optional[float]r  r   r   r   Callable[[Matcher], Matcher]c                     d fd}|S )aW  Adds attributes describing the matcher.

    Parameters
    ----------
    priority : Optional[float]
        The priority of the matcher, determines the order of execution of matchers.
        Higher priority means that the matcher will be executed first. Defaults to 0.
    identifier : Optional[str]
        identifier of the matcher allowing users to modify the behaviour via traitlets,
        and also used to for debugging (will be passed as ``origin`` with the completions).

        Defaults to matcher function's ``__qualname__`` (for example,
        ``IPCompleter.file_matcher`` for the built-in matched defined
        as a ``file_matcher`` method of the ``IPCompleter`` class).
    api_version: Optional[int]
        version of the Matcher API used by this matcher.
        Currently supported values are 1 and 2.
        Defaults to 1.
    funcr   c                    pd| _         p| j        | _        | _        t          r7dk    rt          t          |           } ndk    rt          t          |           } | S )Nr   rj   rT   )matcher_priorityr?   matcher_identifierr   r   r.   r   r   )r  r   r  r  s    rC   wrapperz#completion_matcher.<locals>.wrapper  sj     (A","A0A#.  	0aL$//!!L$//rB   )r  r   rA   )r  r  r   r  s   ``` rC   completion_matcherr    s4    4	 	 	 	 	 	 	 	 NrB   c                $    t          | dd          S )Nr  r   getattrr   s    rC   _get_matcher_priorityr  
  s    7.222rB   c                .    t          | d| j                  S )Nr  )r  r?   r  s    rC   _get_matcher_idr    s    70'2FGGGrB   c                $    t          | dd          S )Nr   rj   r  r  s    rC   r   r     s    711555rB   rT   r   r   r   _ICc              #  B  K   t          |          }|sdS t          d |D                       }t          d |D                       }t                      }|D ]F}| ||j                 |j        z   | |j        |         z   }||vr|V  |                    |           Gd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              3  $   K   | ]}|j         V  d S r   r   r^   r_   s     rC   r`   z+_deduplicate_completions.<locals>.<genexpr>;  s$      11AG111111rB   c              3  $   K   | ]}|j         V  d S r   r   r#  s     rC   r`   z+_deduplicate_completions.<locals>.<genexpr><  s$      --A!%------rB   )listminmaxra   r   r   r   add)r   r   	new_startnew_endseenr_   new_texts          rC   _deduplicate_completionsr.    s      6 {##K 11[11111I-------G55D  	!')*QV3d15=6II4GGGHHX	 rB   )_debugr/  c          	   #    K   t          j        dt          d           t          |          }|sdS d |D             }d |D             }t	          |          }t          |          }t                      }t                      }|D ]}	| ||	j                 |	j        z   | |	j	        |         z   }
|	j
        dk    r|                    |
           n |	j
        dk    r|                    |
           t          |||
|	j        |	j
        |	j        	          V  |                    |          }|r|rt!          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.rT   r   Nc              3  $   K   | ]}|j         V  d S r   r"  r#  s     rC   r`   z&rectify_completions.<locals>.<genexpr>m  s$      ++!ag++++++rB   c              3  $   K   | ]}|j         V  d S r   r%  r#  s     rC   r`   z&rectify_completions.<locals>.<genexpr>n  s$      ''aAE''''''rB   jedizIPCompleter.python_matcherr   z#IPython.python matches have extras:)rI   r   r<   r&  r'  r(  ra   r   r   r   r   r)  r   r   r   
differenceprint)r   r   r/  startsendsr*  r+  	seen_jediseen_python_matchesr_   r-  diffs               rC   rectify_completionsr;  F  s     > M 9 71F F F F
 {##K ++{+++F'';'''DFI$iiGI%% n n	!')*QV3d15=6II9MM(####Y666##H---GXAFAIabalmmmmmmm)))44D ; ;3T:::::; ; ; ;rB   z 	
`!@#$^&*()=+[{]}|;'",<>?z 	
`!@#$^&*()=+[{]}\|;:'",<>?z =
c                  d    e Zd ZdZeZdZdZddZe	d             Z
e
j        d             Z
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                4    |t           j        n|}|| _        d S r   )r=  _delimsdelims)r   r@  s     rC   r   zCompletionSplitter.__init__  s    /5~#++6rB   c                    | j         S )z*Return the string of delimiter characters.)r?  r   s    rC   r@  zCompletionSplitter.delims  s     |rB   c                    dd                     d |D                       z   dz   }t          j        |          | _        || _        || _        dS )z&Set the delimiters for line splitting.[rZ   c              3      K   | ]	}d |z   V  
dS r\   rA   r#  s     rC   r`   z,CompletionSplitter.delims.<locals>.<genexpr>  s&      55T1W555555rB   ]N)rd   recompile	_delim_rer?  _delim_expr)r   r@  exprs      rC   r@  zCompletionSplitter.delims  sT     RWW55f555555;D))rB   c                ^    ||n	|d|         }| j                             |          d         S )zBSplit a line of text with a cursor at the given position.
        Nr}   )rH  r   )r   line
cursor_poscut_lines       rC   
split_linezCompletionSplitter.split_line  s6     &-4443D~##H--b11rB   r   )r=   r>   r?   r@   DELIMSr?  rI  rH  r   propertyr@  setterrO  rA   rB   rC   r=  r=    s        
> 
>  G
 K I      X ]    ] 2 2 2 2 2 2rB   r=  c                      e Zd Z edd                              d          Z eddd	                              d          Z eed
	                              d          Z	 e
dd	                              d          Z edd	                              d          Z edd                              d          Z edd                              d          Z ei  e            d                              d          Z eddd                              d          Zd' fd	Zd Zd Zd Z ej        d          Zd(dZ	 d)d*d#Zd(d$Zd% Zed&             Z  xZ!S )+r7   Fal  Activate greedy completion.

        .. deprecated:: 8.8
            Use :std:configtrait:`Completer.evaluation` and :std:configtrait:`Completer.auto_close_dict_keys` instead.

        When enabled in IPython 8.8 or newer, changes configuration as follows:

        - ``Completer.evaluation = 'unsafe'``
        - ``Completer.auto_close_dict_keys = True``
        helpTconfig)	forbiddenminimallimitedunsafe	dangerousrZ  a#  Policy for code evaluation under completion.

        Successive options allow to enable more eager evaluation for better
        completion suggestions, including for nested dictionaries, nested lists,
        or even results of function calls.
        Setting ``unsafe`` or higher can lead to evaluation of arbitrary user
        code on :kbd:`Tab` with potentially unwanted or dangerous side effects.

        Allowed values are:

        - ``forbidden``: no evaluation of code is permitted,
        - ``minimal``: evaluation of literals and access to built-in namespace;
          no item/attribute evaluation, no access to locals/globals,
          no evaluation of any operations or comparisons.
        - ``limited``: access to all namespaces, evaluation of hard-coded methods
          (for example: :any:`dict.keys`, :any:`object.__getattr__`,
          :any:`object.__getitem__`) on allow-listed objects (for example:
          :any:`dict`, :any:`list`, :any:`tuple`, ``pandas.Series``),
        - ``unsafe``: evaluation of all methods and function calls but not of
          syntax with side-effects like `del x`,
        - ``dangerous``: completely arbitrary evaluation; does not support auto-import.

        To override specific elements of the policy, you can use ``policy_overrides`` trait.
        default_valuerU  zYExperimental: Use Jedi to generate autocompletions. Default to True if jedi is installed.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.a.  
        Enable auto-closing dictionary keys.

        When enabled string keys will be suffixed with a final quote
        (matching the opening quote), tuple keys will also receive a
        separating comma if needed, and keys which are final will
        receive a closing bracket (``]``).
        zOverrides for policy evaluation.

        For example, to enable auto-import on completion specify:

        .. code-block::

            ipython --Completer.policy_overrides='{"allow_auto_import": True}' --Completer.use_jedi=False

        )r^  	key_traitrU  zimportlib.import_modulea          Provisional:
              This is a provisional API in IPython 9.3, it may change without warnings.

        A fully qualified path to an auto-import method for use by completer.
        The function should take a single string and return `ModuleType` and
        can raise `ImportError` exception if module is not found.

        The default auto-import implementation does not populate the user namespace with the imported module.
        )r^  
allow_nonerU  Nc                    |d| _         nd| _         || _        |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.
        NTFrA   )use_main_ns	namespaceglobal_namespacecustom_matcherssuperr7   r   )r   rc  rd  kwargs	__class__s       rC   r   zCompleter.__init__'  sq    " #D$D&DN #$&D!!$4D!!'i'11&11111rB   c                    | j         rt          j        | _        |dk    r9d|v r|                     |          | _        n|                     |          | _        	 | j        |         S # t          $ r Y dS w xY 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)rb  __main____dict__rc  attr_matchesmatchesglobal_matches
IndexError)r   r   states      rC   r   zCompleter.completeH  s      	/%.DNA::d{{#0066#22488	<&& 	 	 	44	s   A& &
A43A4c                   g }|j         }t          |          }t          j        t          j                                        t          | j                                                  t          | j	                                                  fD ]&}|D ]!}|d|         |k    r|dk    r ||           "'t          j        d          t          | j                                                  t          | j	                                                  fD ]L}fd|D             }|                                D ]'}|d|         |k    r|dk    r |||                    (M|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                    i | ]J}                     |          d                     d |                    d           D                       |KS )r{   c                    g | ]
}|d          S )r   rA   )r^   subs     rC   
<listcomp>z7Completer.global_matches.<locals>.<dictcomp>.<listcomp>s  s    <<<S#a&<<<rB   )matchrd   r   )r^   r   snake_case_res     rC   
<dictcomp>z,Completer.global_matches.<locals>.<dictcomp>r  sd        &&t,,<<DJJsOO<<<==t  rB   )appendrl   keywordkwlistbuiltin_modrl  keysr&  rc  rd  rF  rG  )	r   r   rn  match_appendnlstr   	shortenedry  s	           @rC   ro  zCompleter.global_matches\  s    ~IIN %%''$$&&''&++--..	
 	' 	'C  ' '8t##(>(> L&&&' 
#788,,..//d6K6P6P6R6R1S1ST 	2 	2C     I
 "(( 2 28t##(>(> L41112 rB   c                8    |                      |          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.

        r   )_attr_matchesr   s     rC   rm  zCompleter.attr_matches|  s     !!$''**rB   z(.+)\.(\w*)$coderO   rP   c           	        h d}h d}	 t          t          j        t          |                                          j                            }n# t          j        $ rz |                     |          }	 t          t          j        t          |                                          j                            }|}n# t          j        $ r |cY cY S w xY wY nw xY wt          |          }d}g }d}	|D ]g}
|
j	        t          j
        k    r4|
j        |v r|	dz  }	n%|
j        |v r|	dz  }	n|
j        dk    r|	dk    rd}g }K|r|                    |
j                   h|rd                    |          S |S )	N>   {(rC  >   })rE  Fr   rj   rj  TrZ   )r&  tokenizegenerate_tokensiter
splitlinesr   
TokenError
_trim_expr_parse_tokensr   OPstringr{  rd   )r   r  o_parensc_parensr{   trimmed_codetokensencountered_operatorafter_operatornesting_levelts              rC   _strip_code_before_operatorz%Completer._strip_code_before_operator  s   "??"??	X-d4??3D3D.E.E.NOOPPAA" 		 		 		??400L,T,2I2I2K2K-L-L-UVV  $&    		 t$$$ 	0 	0Av$$8x''!Q&MMX))!Q&MMX__!););+/(%'N# 0%%ah/// 	77>***Ks7   AA $C5AB=<C=CCCCCr   include_prefixrt   tuple[Sequence[str], str]c                   | j                             |          }|sg dfS |                    dd          \  }	 |                     |          }n# t          j        $ r Y nw xY w|                     |          }|t          u rg dfS | j        r t          |d          rt          |          }nt          |          }	 t          j        ||          }n%# t          $ r Y nt          $ r  t           $ r Y nw xY wt#                    |rt%          |          }t'          |          }t          j        t          j        h}	d}
g }|D ]}|j        |	v r|j        t          j        k    r|
r|                    |j                   d}
@|j        t          j        k    r*|j        dk    r|
s|                    |j                   d}
 d                    t'          |                    ndfd|D             dz   fS )	NrZ   rj   rT   __all__TFrj  c                :    g | ]}|d          k    d|S )Nrj  rA   )r^   wattrr  prefix_after_spaces     rC   rw  z+Completer._attr_matches.<locals>.<listcomp>  s4    OOO12A2$***AA.rB   )_ATTR_MATCH_RErx  groupr  r  r  _evaluate_expr	not_foundlimit_to__all__r   get__all__entriesr   r   complete_objectr   AssertionError	Exceptionrl   r  reversed	ENDMARKERNEWLINEr   NAMEr{  r  r  rd   )r   r   r  m2rJ  objwordsr  
rev_tokens	skip_over	name_turnpartsr   r  r  r  s                @@@rC   r  zCompleter._attr_matches  so     &&t,, 	r6MXXa^^
d	33D99DD" 	 	 	D	 !!$'')r6M 	GC$;$; 	%c**EEIIE	,S%88EE 	 	 	D 	 	 	 	 	 	D	 II  	$"4((F!&))J!+X-=>IIE#  :**:..9.LL... %IIJ(+--%,#2E2Ei2ELL... $II !#%!9!9!# POOOOOOOO$J
 	
s)   A A&%A&C 
C:$C:9C:c                   |r|dd         }	 t          j        |          }n# t          $ r Y .w xY w|J t          |j                  dk    rO|j        d         j        }t          |t           j                  r|d         dk    s|S dS )z
        Trim the code until it is a valid expression and not a tuple;

        return the trimmed expression for guarded_eval.
        rj   Nr   r}   r  rZ   )astparseSyntaxErrorrl   bodyr   
isinstanceTuple)r   r  resrJ  s       rC   r  zCompleter._trim_expr  s      	8Dioo    ???38}}!!8A;$D$	** 48s?? Krs   # 
00c           
     ,   t           }d}|s|r	 t          |t          | j        | j        | j        | j        | j                            }d}nC# t          $ r6}| j	        rt          d|           |                     |          }Y d }~nd }~ww xY w|s||S )NF)globalslocals
evaluationauto_importpolicy_overridesTzEvaluation exception)r  r   r   rd  rc  r  _auto_importr  r  debugr5  r  )r   rJ  r  donees        rC   r  zCompleter._evaluate_expr  s     	-4 	--"% $ 5#~#'?$($5)-)>  	 	  - - -: 50!444
 t,,-  	-4 	-* 
s   =A 
B,BBc                t    | j         d S t          | d          st          | j                   | _        | j        S )N_auto_import_func)auto_import_methodr   r-   r  r   s    rC   r  zCompleter._auto_import.  s@    "*4t011 	J%01H%I%ID"%%rB   )NN)r  rO   rP   rO   )T)r   rO   r  rt   rP   r  )"r=   r>   r?   r$   taggreedyr%   r  JEDI_INSTALLEDuse_jedir&   jedi_compute_type_timeoutr  backslash_combining_completionsauto_close_dict_keys	DictTraitr(   r  r*   r  r   r   ro  rm  rF  rG  r  r  r  r  r  rQ  r  __classcell__rh  s   @rC   r7   r7     s       T	   
cc  B  6 
cc7 : t.<= = ==@SS=M=M  !$#! ! ! SS	  DuGH H H s$s'' 

 '+d4:'; '; '; <?3d3;K;K $
  4
 
 
 
cc  !y'))   
cc  *)/	   
cc 2 2 2 2 2 2B  (  @+ + +   RZ00N( ( ( (V 15B
 B
 B
 B
 B
H   0  4 & & X& & & & &rB   c                b    	 t          | d          }n# t          $ r g cY S w xY wd |D             S )z,returns the strings in the __all__ attributer  c                <    g | ]}t          |t                    |S rA   )r  rO   )r^   r  s     rC   rw  z%get__all__entries.<locals>.<listcomp>=  s'    333!
1c 2 23A333rB   )r  r  )r  r  s     rC   r  r  6  sR    Y''   			 43u3333s    ""c                  p    e Zd ZdZdZ ej                    Z ej                    Z ej                    Z	dS )_DictKeyStatea  Represent state of the key match in context of other possible matches.

    - given `d1 = {'a': 1}` completion on `d1['<tab>` will yield `{'a': END_OF_ITEM}` as there is no tuple.
    - given `d2 = {('a', 'b'): 1}`: `d2['a', '<tab>` will yield `{'b': END_OF_TUPLE}` as there is no tuple members to add beyond `'b'`.
    - given `d3 = {('a', 'b'): 1}`: `d3['<tab>` will yield `{'a': IN_TUPLE}` as `'a'` can be added.
    - given `d4 = {'a': 1, ('a', 'b'): 2}`: `d4['<tab>` will yield `{'a': END_OF_ITEM & END_OF_TUPLE}`
    r   N)
r=   r>   r?   r@   BASELINEenumautoEND_OF_ITEMEND_OF_TUPLEIN_TUPLErA   rB   rC   r  r  @  sF          H$)++K49;;Lty{{HHHrB   r  c                
   g }t          j        t          |                                           j                  }	 	 |                    t          |                     n$# t           j        $ r |cY S t          $ r |cY S w xY wI)z'Parse tokens even if there is an error.)	r  r  r  r  r   r{  r  r  r  )r_   r  token_generators      rC   r  r  O  s    F.tALLNN/C/C/LMMO	MM$//0000" 	 	 	MMM 	 	 	MMM	s   "A   B3B BprefixUnion[str, None]c                   | d                                          rdS t          |           }t          |          }t          j        t          j        h}d}|D ]f}|j        |v r| |j        t          j        k    r|j        }+ dS |j        t          j	        k    r!|j        dk    r n|j        dv r
|j        |z   }d dS |S )zMatch any valid Python numeric literal in a prefix of dictionary keys.

    References:
    - https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals
    - https://docs.python.org/3/library/tokenize.html
    r}   N,>   +-)
isspacer  r  r  r  r  r   NUMBERr  r  )r  r  r  r  numberr   s         rC    _match_number_in_dict_key_prefixr  \  s     bz  t6""F&!!J#X%56IF  :"">zX_,, tt:$$|s""|z)).44MrB   )0b0o0xr  6list[Union[str, bytes, tuple[Union[str, bytes], ...]]]r@  extra_prefix'Optional[tuple[Union[str, bytes], ...]])tuple[str, int, dict[str, _DictKeyState]]c                   |r|ndt          d D                       t          t          t          t          t
          ffd}t          d           }| D ]}t          |t                    rP ||          rD|         }||xx         t          |          dz   k    rt          j        nt          j        z  cc<   gdk    rnt          |          r||xx         t          j        z  cc<   |                                }|s!ddd |                                D             fS t!          j        d	|          }	d
}
|	r?|	                                }||z   }	 t'          |          }n1# t(          $ r ddi fcY S w xY wt+          |          }|ddi fS |}d}
d}dd                    d |D                       z   dz   }t!          j        ||t           j                  }|J |                                }|                                }i }|D ][}t          |t          t          f          re|
s"t          |          }t          |t                    r=|dd                                         }|t4          v rt4          |         } ||          }n|
r|}	 |                    |          sn# t8          t:          t<          f$ r Y w xY w|t          |          d         }t          |t                    rt?          |dz             nt?          |dz             }|d|                     d          z   d         }|dk    r|!                    dd          }||}||         ||<   ]|||fS )am  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 dictionary of replacement/completion keys on keys and values
        indicating whether the state.
    rA   c                :    g | ]}t          |t                     S rA   )r  slice)r^   ks     rC   rw  z#match_dict_keys.<locals>.<listcomp>  s7     	
 	
 	
  1e$$$	
 	
 	
rB   c                    t          |           k    rdS | D ]}t          |          s dS t          |           D ]#\  }}||k    rt          |t                    s dS $dS )NFT)rl   r  zipr  )keyr  ptprefix_tupleprefix_tuple_sizetext_serializable_typess      rC   filter_prefix_tuplez,match_dict_keys.<locals>.filter_prefix_tuple  s    s88(((5 	 	Aa!899 uu l++ 	 	EArBwwz"e44wuutrB   c                     t           j        S r   )r  r  rA   rB   rC   <lambda>z!match_dict_keys.<locals>.<lambda>  s	    M2 rB   rj   r   rZ   c                4    i | ]\  }}t          |          |S rA   )repr)r^   r  vs      rC   rz  z#match_dict_keys.<locals>.<dictcomp>  s$    LLLdatAwwLLLrB   z(?:"|')FNTz[^c              3      K   | ]	}d |z   V  
dS r\   rA   r#  s     rC   r`   z"match_dict_keys.<locals>.<genexpr>  s&      66!TAX666666rB   z]*$rT   rS      "rU   z\")"sumrO   bytesr   floatr  r   r  tuplerl   r  r  r  r  r  itemsrF  searchr  r   r  r  rd   UNICODEr   lower_INT_FORMATSrk   AttributeError	TypeErrorUnicodeErrorr  indexrw   )r  r  r@  r  r  filtered_key_is_finalr  key_fragmentfiltered_keysquote_matchis_user_prefix_numericquotevalid_prefix
prefix_strnumber_matchpatterntoken_matchtoken_starttoken_prefixmatchedr  str_keyint_base
int_formatremrem_reprrx  r  r  r   s                              @@@rC   match_dict_keysr*    s^   8 $07<<RL	
 	
 "	
 	
 	
   #E3u=        	2233   F F
 a 	F""1%%  !23%l3331vv!2Q!666 "..&/333
 "" !455 F%a(((M,EE((()..00M M1LL.C.I.I.K.KLLLLL)J//K" !!##~	%l33JJ 	 	 	q"9	
 8??  q"9!
!%RWW66v666666>G)GVRZ88K"""##%%K$$&&L(*G  &4 &4cC<(( 	) #hhG#s## .%bqb>//11|++!-h!7J(jooG & G	%%j11 	<8 	 	 	H	
 c*oo''(&0c&:&:P4c	???S4Z@P@PAs 3 33B67C<<  ''U33H ',1.s3+w&&s$   E/ /F FJ66KKrL  columnc           	     $   |                      d          }|t          |          k    sEJ d                    t          |          t          t          |                                          t	          d |d|         D                       |z   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

    r   z{} <= {}c              3  :   K   | ]}t          |          d z   V  dS )rj   Nrl   )r^   rL  s     rC   r`   z%cursor_to_position.<locals>.<genexpr>A  s,      66s4yy1}666666rB   N)r   rl   formatrO   r
  )r   rL  r+  liness       rC   cursor_to_positionr1  '  s    . JJtE3u::z00TCE

OOLL66uu66666??rB   offsettuple[int, int]c                   d|cxk    rt          |           k    sn J d|dt          |                       | 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 <= z <= Nr   r}   )rl   r   rV   )r   r2  beforeblinesrL  cols         rC   position_to_cursorr8  D  s    2 #####d))#######d)))&L###'6']F\\$F<<D
fRj//C9rB   c                    |t           j        v r:t           j        |         }|g|D ]}t          ||          }t          | |          S dS )z@Checks if obj is an instance of module.class_name if loaded
    N)rb   modulesr  r  )r  module
class_nameattrsmr  s         rC   _safe_isinstancer?  f  s]     K(%( 	! 	!D4  AA#q!!!	 rB   r   c                V    t          | j                  \  }}t          |d|d          S )zMatch Unicode characters back to Unicode name

    Same as :any:`back_unicode_name_matches`, but adopted to new Matcher API.
    unicodeTr   fragmentsuppress_if_matches)back_unicode_name_matchesr    _convert_matcher_v1_result_to_v2)r   rC  rn  s      rC   back_unicode_name_matcherrG  p  s9     2'2KLLHg+i(   rB   tuple[str, Sequence[str]]c                    t          |           dk     rdS | d         }|dk    rdS | d         }|t          j        v s|dv rdS 	 t          j        |          }d|z   d|z   ffS # t
          $ r Y nw xY wdS )u  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 ...

    .. deprecated:: 8.6
        You can use :meth:`back_unicode_name_matcher` instead.

    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.
    rT   rZ   rA   r	  r]   r}   rS   rU   )rl   r  ascii_lettersunicodedatar   KeyError)r   maybe_slashcharunics       rC   rE  rE  |  s    . 4yy{{vr(Kdv8D v###ty'8'8v%%Dy$t)%%   6s   A" "
A/.A/c                   | j         }g dd}t          |          dk     r|S |d         }|dk    r|S |d         }|t          j        v s|dv r|S 	 t          |         }t          |d	          gd
d|z   dS # t          $ r Y nw xY w|S )uV   Match latex characters back to unicode name

    This does ``\ℵ`` -> ``\aleph``
    Fr   r   rT   r	  r]   r}   rK  latexr   Tr   r   r   )r   rl   r  rL  r   r   rN  )r   r   no_matchrO  rP  rT  s         rC   back_latex_name_matcherrW    s     $D H
 4yy{{r(Kd8D v###ty'8'8	$T* -%gFFFG $t
 
 	

     Os   %A5 5
BBc                r    | j         }|                    d          st          d|z            |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)descriptionrk   r  )	parameterrZ  s     rC   _formatparamchildrenr\    sT      'K!!(++ K <>IJ K K 	Kqrr?rB   c                f   t          | d          rd|                                 }|sdS |                                 d         }d|                                                    dd          d         z   S dd                    d	 d
 |                                 D             D                       z  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   r  rj   )maxsplitz(%s), c                    g | ]}||S rA   rA   r^   fs     rC   rw  z#_make_signature.<locals>.<listcomp>  s3     T T TAQRTa T T TrB   c              3  b   K   | ]*}|                                 D ]}t          |          V  +d S r   )defined_namesr\  )r^   r   ps      rC   r`   z"_make_signature.<locals>.<genexpr>  si       *N *Ni3<3J3J3L3L*N *N./ +?q*A*A *N *N *N *N *N *N *NrB   )r   r^  	to_stringr   rd   )
completion
signaturesc0s      rC   _make_signaturerk    s    $ z+,, <..00
 	E&&((+2<<>>''a'88;;;499 T T *N *NS]SlSlSnSn *N *N *N T T T U U U UrB   a  (?x)
(  # match dict-referring - or any get item object - expression
    .+
)
\[   # open bracket
\s*  # and optional whitespace
# Capture any number of serializable objects (e.g. "a", "b", 'c')
# and slices
((?:(?:
    (?: # closed string
        [uUbB]?  # string prefix (r not handled)
        (?:
            '(?:[^']|(?<!\\)\\')*'
        |
            "(?:[^"]|(?<!\\)\\")*"
        )
    )
    |
        # capture integers and slices
        (?:[-+]?\d+)?(?::(?:[-+]?\d+)?){0,2}
    |
        # integer in bin/hex/oct notation
        0[bBxXoO]_?(?:\w|\d)+
    )
    \s*,\s*
)*)
((?:
    (?: # unclosed string
        [uUbB]?  # string prefix (r not handled)
        (?:
            '(?:[^']|(?<!\\)\\')*
            |
            "(?:[^"]|(?<!\\)\\")*
        )
    )
    |
        # unfinished integer
        (?:[-+]?\d+)
    |
        # integer in bin/hex/oct notation
        0[bBxXoO]_?(?:\w|\d)+
    )
)?
$
rn  Sequence[str]r   c                >    t          fd| D             d          S )zlsame as _convert_matcher_v1_result_to_v2 but fragment=None, and suppress_if_matches is False by constructionc                2    g | ]}t          |           S r   r   r^   rx  r   s     rC   rw  z:_convert_matcher_v1_result_to_v2_no_no.<locals>.<listcomp>9  s'    RRR%5t<<<RRRrB   FrS  )r   )rn  r   s    `rC   &_convert_matcher_v1_result_to_v2_no_norr  3  s6    
 RRRR'RRR   rB   rC  rD  c                n    fd| D             |r| rdndndd}|||d<   t          t          |          S )zUtility to help with transitionc                2    g | ]}t          |           S ro  rp  rq  s     rC   rw  z4_convert_matcher_v1_result_to_v2.<locals>.<listcomp>F  s'    UUUE(e$???UUUrB   TFrS  Nr   )r.   r   )rn  r   rC  rD  r  s    `   rC   rF  rF  >  sb     VUUUWUUU4GRW/TT%%U F %-!"#V,,,rB   c            	          e Zd ZdZ ed          d             Z edd          Z e ed           e	 ed	d                    gd	d
          
                    d          Z edd          
                    d          Z e e            d          
                    d          Z eddd          
                    d          Z edd          
                    d          Z edd          
                    d          Z edd          
                    d          Z ed          d             Z	 dd fd	Zeded            ZdfdZdgd Zdgd!Z e            dhd%            Z e            dhd&            Z e            dhd'            Zdfd(Z  e            dhd)            Z! ed*+          did-            Z"djd2Z# G d3 d4e$j                  Z%d5 Z&d6 Z' e            dhd7            Z( e)d89          dkd;            Z*d< Z+d= Z, e            dhd>            Z-d? Z.e/dldC            Z0 e            dhdD            Z1dfdEZ2 e            dhdF            Z3 e            dmdG            Z4dndIZ5 e            dJ             Z6dK Z7dodNZ8dpdPZ9	 dqdrdQZ:dsdXZ;d	d	d	dYdtd[Z<e/dud_            Z=e/dvd`            Z> e            dmda            Z?dndbZ@edwdc            ZA xZBS )xr8   z?Extension of the completer class with IPython-specific featuresr  c                    |d         r!d| _         d| _        t          | j        _        dS d| _         d| _        t
          | j        _        dS )z>update the splitter and readline delims when greedy is changednewr[  TrZ  FN)r  r  GREEDY_DELIMSsplitterr@  rP  r   changes     rC   _greedy_changedzIPCompleter._greedy_changedQ  sN     %= 	*&DO(,D%#0DM   'DO(-D%#)DM   rB   Fz
        Whether to show dict key matches only.

        (disables all matchers except for `IPCompleter.dict_key_matcher`).
        rT  T)r`  Nag  
        Whether to suppress completions from other *Matchers*.

        When set to ``None`` (default) the matchers will attempt to auto-detect
        whether suppression of other matchers is desirable. For example, at
        the beginning of a line followed by `%` we expect a magic completion
        to be the only applicable option, and after ``my_dict['`` we usually
        expect a completion with an existing dictionary key.

        If you want to disable this heuristic and see completions from all matchers,
        set ``IPCompleter.suppress_competing_matchers = False``.
        To disable the heuristic for specific matchers provide a dictionary mapping:
        ``IPCompleter.suppress_competing_matchers = {'IPCompleter.dict_key_matcher': False}``.

        Set ``IPCompleter.suppress_competing_matchers = True`` to limit
        completions to the set of matchers with the highest priority;
        this is equivalent to ``IPCompleter.merge_completions`` and
        can be beneficial for performance, but will sometimes omit relevant
        candidates from matchers further down the priority list.
        r]  rV  a6  Whether to merge completion results into a single list

        If False, only the completion results from the first non-empty
        completer will be returned.

        As of version 8.6.0, setting the value to ``False`` is an alias for:
        ``IPCompleter.suppress_competing_matchers = True.``.
        z{List of matchers to disable.

        The list should contain matcher identifiers (see :any:`completion_matcher`).
        )r   rj   rT   rT   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.
        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                :    t          j        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.)rI   r   UserWarningrz  s     rC   _limit_to_all_changedz!IPCompleter._limit_to_all_changed  s+     H 	 	 	 	 	rB   c                   t           | _        t                      | _         t	                      j        d|||d| g | _        || _        t          j	        d          | _
        t          j        | _        t          j                            dd          }|dv | _        t           j        dk    r| j        | _        n| j        | _        t          j	        d          | _        t          j	        d          | _        | j        | j        g| _        d	| _        d	| _        | j        | j        t<          t>          | j         g| _!        | j"        s1| j!        D ])}| j#        $                    tK          |                     *| j&        s	d
| _'        d	S 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.
        )rc  rd  rW  z([^\\] )TERMxterm)dumbemacsr9   z^[\w|\s.]+\(([^)]*)\).*z[\s|\[]*(\w+)(?:\s*=\s*.*)NTrA   )(r   magic_escaper=  ry  rf  r   rn  shellrF  rG  space_name_reglobrm   environgetdumb_terminalrb   rc   _clean_glob_win32
clean_glob_clean_globdocstring_sig_redocstring_kwd_remagic_config_matchermagic_color_matchermagic_arg_matcherscustom_completers_unicode_nameslatex_name_matcherunicode_name_matcherrW  rG  fwd_unicode_matcher_backslash_combining_matchersr  disable_matchersr{  r  merge_completionssuppress_competing_matchers)	r   r  rc  rd  rW  rg  termr   rh  s	           rC   r   zIPCompleter.__init__  s   2 &*,, 	 	
-	
 	
 		
 	
 	
 
Z44I	 z~~fW--!%55 <7"""4DOO".DO !#
+E F F "
+H I I
 %$#
 "& # #%#%$.
* 3 	G= G G%,,_W-E-EFFFF% 	4/3D,,,	4 	4rB   rP   list[Matcher]c                $   | j         r| j        gS | j        r:g | j        | j        | j        | j        | j        | j        | j        | j	        S g | j        | j        | j        | j        | j        | j        | j
        | j	        | j        S )z*All active matcher routines for completion)dict_keys_onlydict_key_matcherr  re  r  r  custom_completer_matchermagic_matcher_jedi_matcherfile_matcherpython_matcherpython_func_kw_matcherr   s    rC   matcherszIPCompleter.matchers  s     	+)**= 		%	3	 (	 -		
 "	 "	 %	 !	 	
%
3
 (
 -	

 %
 "
 #
 !
 +
 
rB   r   rO   r   c                    |                     d          d         t                      5   fd                     |t          |                    D             cddd           S # 1 swxY w Y                        |          d         S )zQ
        Wrapper around the completion methods for the benefit of emacs.
        rj  r   c                h    g | ].}r#j         rd                     |j        g          n|j        /S )rj  )r  rd   r   )r^   r_   r  r   s     rC   rw  z/IPCompleter.all_completions.<locals>.<listcomp>>  sW     @ @ @ 39VT]VCHHfaf-...PQPV @ @ @rB   Nrj   )
rpartitionrM   r   rl   r   )r   r   r  s   ` @rC   all_completionszIPCompleter.all_completions8  s     %%a(!## 	@ 	@@ @ @ @ @!--dCII>>@ @ @	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ }}T""1%%s   0A))A-0A-c                2    |                      d|z            S )N%s*r  r   s     rC   r  zIPCompleter._clean_globC  s    yy&&&rB   c                F    d |                      d|z            D             S )Nc                :    g | ]}|                     d d          S )r]   /rv   rb  s     rC   rw  z1IPCompleter._clean_glob_win32.<locals>.<listcomp>G  s6     2 2 2 		$s## 2 2 2rB   r  r  r   s     rC   r  zIPCompleter._clean_glob_win32F  s3    2 254<002 2 2 	2rB   r   r   r   c                  	
 |j         }|                    d          r|dd         }dnd| j        }t          |          	d|v sd|v r|}nY	 t	          |          d         }nB# t
          $ r( 	r|                    	          d         }ng dd	cY S Y nt          $ r d}Y nw xY w	s|t          |          k    rd
}||c
}n!d}t          j
                            |          }|dk    r$fd|                     d          D             dd	S t          j        dk    r|                     |          }n)|                     |                    dd                    }|r t#          |          
fd|D             }n1	r!t          j        dk    r|n	f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.
        !rj   NrZ   r  rC  r}   FrS  Tc                R    g | ]#}t          t          |          z   d           $S )rf   r   )r   re   r^   rc  text_prefixs     rC   rw  z,IPCompleter.file_matcher.<locals>.<listcomp>  sM            %(+;A+>+>>V       rB   *r9   r]   c                J    g | ]}z   t          |d                    z    S r   re   )r^   rc  
len_lsplittext0r  s     rC   rw  z,IPCompleter.file_matcher.<locals>.<listcomp>  sL     E E E<= #U*'*++778 E E ErB   c                0    g | ]}t          |          S rA   r  )r^   rc  open_quotess     rC   rw  z,IPCompleter.file_matcher.<locals>.<listcomp>  s$    BBB!%a55BBBrB   c                4    g | ]}t          |          z   S rA   r  r  s     rC   rw  z,IPCompleter.file_matcher.<locals>.<listcomp>  s9     < < <34 '+A../ < < <rB   c                x    g | ]7}t          t          j                            |          r|d z   n|d          8S )r  rf   r   )r   rm   rf   isdir)r^   xs     rC   rw  z,IPCompleter.file_matcher.<locals>.<listcomp>  sP        !q1A1A&Ha#ggqvVVV  rB   )r   rk   r   rW   r#   r  r   rp  re   rm   rf   rn   r  rb   rc   r  rw   rl   )r   r   r   r   lsplithas_protectablesm0rn  r  r  r  r  s           @@@@rC   r  zIPCompleter.file_matcherJ  s   $ } ??3 	8DKKK 2%&788###s.?'?'?FF"#455b9    .44[AA"EFF (*$)     F      	,v)9&)A)AAA#fJE$$$7%%d++D2::        "YYs^^	      "   <7""&&BBdB!7!788B 	< VJE E E E E EACE E EGG  < !$ 7 7""BBBBrBBB < < < <8:< < <
     
 
 	
s   A( (-B'B'&B'c                  	
 |j         }| j        j                                        }|d         }|d         }| j        z   |                              }|                              	|                     	          
|s	
fdn	fdfd|D             }|                              s|fd|D             z  }t          |          dk    o|d         dk    }d	 |D             |ot          |          dk    d
S )zMatch magics.rL  cellc                6    |                                o| vS )z
                Filter magics, in particular remove magics that match
                a name present in global namespace.
                rk   )magic	bare_textro  s    rC   rn  z*IPCompleter.magic_matcher.<locals>.matches  s(    
 )))44 5n47rB   c                .    |                                S r   r  )r  r  s    rC   rn  z*IPCompleter.magic_matcher.<locals>.matches  s    ''	222rB   c                0    g | ]} |          |z   S rA   rA   )r^   r>  rn  pre2s     rC   rw  z-IPCompleter.magic_matcher.<locals>.<listcomp>  s*    CCCA

CtaxCCCrB   c                0    g | ]} |          |z   S rA   rA   )r^   r>  rn  pres     rC   rw  z-IPCompleter.magic_matcher.<locals>.<listcomp>  s*    GGGGGAJJGC!GGGGrB   r   r~   c                0    g | ]}t          |d           S )r  r   rp  )r^   comps     rC   rw  z-IPCompleter.magic_matcher.<locals>.<listcomp>  s3       >B d999  rB   rS  )	r   r  magics_managerlsmagicr  rk   lstripro  rl   )r   r   r   lsmline_magicscell_magicsexplicit_magicr   is_magic_prefixr  ro  rn  r  r  s            @@@@@rC   r  zIPCompleter.magic_matcher  sx    }j'//11&k&k3w-- KK$$	,,Y77 
	37 7 7 7 7 7 73 3 3 3 3 DCCCCCCCt$$ 	HGGGGG[GGGGKd))a-:DGsN FQ   (@C,<,<q,@	
 
 	
rB   c                X    |                      |j                  }t          |d          S )z3Match class names and attributes for %config magic.paramr   )magic_config_matchesr   rr  r   r   rn  s      rC   r  z IPCompleter.magic_config_matcher  s-     ++G,DEE5gGLLLLrB   c                l  	 |                                                                 	t          	          dk    rw	d         dk    s	d         dk    r^t          t	          d | j        j        D                       d           }d |D             }t          	          dk    r|S 	d                             d	          }|d         fd
|D             }	d                             d	          dk     r|S t          |          dk    r|d         k    r||                                       j	        }|
                                }t          j        t          j        dt          j                  d|          }	fd|                                                                 D             S g S )zMatch class names and attributes for %config magic.

        .. deprecated:: 8.6
            You can use :meth:`magic_config_matcher` instead.
        r   rW  z%configc                H    g | ]}|j                             d           | S )TrV  )rh  class_traitsr#  s     rC   rw  z4IPCompleter.magic_config_matches.<locals>.<listcomp>  s?     "% "% "%&'k&>&>d&>&K&K"%1 "% "% "%rB   c                    | j         j        S r   rh  r=   r  s    rC   r  z2IPCompleter.magic_config_matches.<locals>.<lambda>  s    Q[5I rB   r  c                &    g | ]}|j         j        S rA   r  r#  s     rC   rw  z4IPCompleter.magic_config_matches.<locals>.<listcomp>  s    BBBA1;/BBBrB   rj   rj  c                >    g | ]}|                               |S rA   r  )r^   r_   	classnames     rC   rw  z4IPCompleter.magic_config_matches.<locals>.<listcomp>	  s9     !? !? !?%&\\)%<%<!?! !? !? !?rB   z^--rZ   c                |    g | ]8}|                     d                    |                    d          d         9S )rj   r|   r   )rk   r   )r^   r  textss     rC   rw  z4IPCompleter.magic_config_matches.<locals>.<listcomp>	  sM     8 8 8! OOE!H558C+ 8 8 8rB   )stripr   rl   sortedra   r  configurablesfindr  rh  class_get_helprF  rv  rG  	MULTILINEr  )
r   r   classes
classnamesclassname_textsclassname_matchesclsrU  r  r  s
           @@rC   r  z IPCompleter.magic_config_matches  s    

""$$u::>>uQx833uQx97L7LS "% "%dj.F "% "% "% & &+I+IK K KG CBBBBJ 5zzQ!! $AhnnS11O'*I!? !? !? !?Z !? !? !? Qx}}S!!A%%((&''1,,-a0I==j..y99:D))++vbj>>DII8 8 8 8%)ZZ\\%<%<%>%>8 8 8 8 	rB   c                r   |j         }|                                }|                    d          r|                    d           t	          |          dk    rN|d         dk    s|d         dk    r6|d         t          fdt          j                    D             d	
          S t          g d	
          S )z&Match color schemes for %colors magic.r:   rZ   rT   r   colorsz%colorsrj   c                \    g | ](}|                               t          |d           )S )r  r   )rk   r   )r^   colorr  s     rC   rw  z3IPCompleter.magic_color_matcher.<locals>.<listcomp>"	  sJ       ''//$U999  rB   FrS  )r   r   r   r{  rl   r   r   r  )r   r   r   r  r  s       @rC   r  zIPCompleter.magic_color_matcher	  s     '

== 	 LLu::??aH 4 4aI8M8M1XF&   !,!1!3!3  
     #
 
 
 	
rB   zIPCompleter.jedi_matcher)r  r   c                Z    |                      |j        |j        |j                  }|ddS )N)cursor_columnr   r   FrS  )_jedi_matchesr   r   r   r  s      rC   r  zIPCompleter._jedi_matcher.	  sE    $$!1+" % 
 
 #
 
 	
rB   r  r   r   r   c                   | j         g}| j        |                    | j                   d }t          |||          }|re||dz
           }|dk    rT| j        dk    rd }nE| j        dk    rd }n6| j        dk    rd	 }n't          d
                    | j                            t          j        |d|         |          }d}		 d}
	 t          d |
                                j        j        D                       }t          |j                  dk    o|j        d         dv }
n# t          $ r Y nw xY w|
 }	n/# t           $ r"}| j        rt%          d|d           Y d}~nd}~ww xY w|	st'          g           S 	 t)          ||                    ||dz                       S # t           $ rE}| j        r%t'          t-          d|z            g          cY d}~S t'          g           cY d}~S d}~ww xY w)a  
        Return a list of :any:`jedi.api.Completion`\s 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.

        .. deprecated:: 8.6
            You can use :meth:`_jedi_matcher` instead.
        Nc                    | S r   rA   r  s    rC   r  z+IPCompleter._jedi_matches.<locals>.<lambda>W	  s    Q rB   rj   rj  rT   c                8    | j                             d           S )Nr{   )r   rk   r_   s    rC   r  z+IPCompleter._jedi_matches.<locals>.<lambda>^	  s    QV5F5Fs5K5K1K rB   c                l    | j                             d          o| j                             d           S )Nrz   )r   rk   r   r   s    rC   r  z+IPCompleter._jedi_matches.<locals>.<lambda>`	  s1    af6G6G6M6M6gRSRXRaRabfRgRg1h rB   r   c                    | S r   rA   r  s    rC   r  z+IPCompleter._jedi_matches.<locals>.<lambda>b	  s     rB   z'Don't understand self.omit__names == {}TFc              3  :   K   | ]}t          |d           |V  dS )r   Nr   r#  s     rC   r`   z,IPCompleter._jedi_matches.<locals>.<genexpr>m	  s4      "r"r^efgip^q^q"r1"r"r"r"r"r"rrB   >   rS   rU   z5Error detecting if completing a non-finished string :|)r+  rL  zJOops Jedi has crashed, please report a bug with the following:
"""
%s
s""")rc  rd  r{  r1  omit__namesr  r/  r3  Interpreterr  _get_module	tree_nodechildrenrl   r   r  r  r  r5  r  filterr   r   )r   r  r   r   
namespacescompletion_filterr2  r  interpretertry_jedicompleting_stringfirst_childr  s                rC   r  zIPCompleter._jedi_matches;	  s   0 n%
 ,d3444&J#D+}EE 
	ivax.Cczz#q(((K(K%%%**(h(h%%%**(2
%%$%N%U%UVZVf%g%ghhh&tGVG}jAA	W %f""r"rk.E.E.G.G.Q.Z"r"r"rrr %((9$:$:Q$>$e;CTUVCW[eCe!! !    -,HH 	W 	W 	Wz WMqRUVVV	W
  	88O	 +[-A-A]hkl]l-A-m-mnnn 	  	  	 z 
 +k "         Bxx	 sf   D9 5D% =(D9 %
D2/D9 1D22D9 9
E%E  E%:'F" "
G1,&G,G1G,&G1,G1c                      e Zd ZdZdZdS )"IPCompleter._CompletionContextType	attributeglobalN)r=   r>   r?   	ATTRIBUTEGLOBALrA   rB   rC   _CompletionContextTyper  	  s        	rB   r  c                t   |                      |          \  }}|r|s| j        j        S |r?|r=|                    d          }|dk    r"||dz   d         }|                     |          S t          j        d|          r| j        j        S t          j        d|          }|r| j        j        S | j        j        S )z_
        Determine whether the cursor is in an attribute or global completion context.
        r  r   rj   Nz)(?<!\w)(?<!\d\.)([-+]?\d+\.(\d+)?)(?!\w)$z.*(.+\.(?:[a-zA-Z]\w*)?)$)_is_in_string_or_commentr  r  rfind_determine_completion_contextrF  r  r  )r   rL  	is_stringis_in_expression
expr_startrJ  chain_matchs          rC   r  z)IPCompleter._determine_completion_context	  s    
 '+&C&CD&I&I#	# 	6- 	6.55  	@) 	@CJQJN,,-99$??? 9A4HH 	6.55 i <dCC 	9.88*11rB   c                   d}d}d}d}d}d}d}d}	|	t          |          k     r|	dz   t          |          k     r7||	         dv r-||	dz            dk    s||	dz            dk    r|s|s|s	|sd}|	dz  }	|	dz   t          |          k     rD||	|	d	z            d
k    r|s|s| }|sd}|	d	z  }	||	|	d	z            dk    r|s|s| }|sd}|	d	z  }	||	         dk    r|	dz   t          |          k     r|	dz  }	|rt|	dz   t          |          k     r||	|	dz            dk    r|	dz  }	||	         dk    r|r|r|dk    rd}|dz  }|	dz  }	7||	         dk    r|dz  }|dk    rd}d}|	dz  }	Y|p|}
||	         dk    r|s|
s
| }|s|
sd}n||	         dk    r|s|
s	| }|s|
sd}||	         dk    r|s|s|
sdS |	dz  }	|	t          |          k     |p|p|p|}|p|o| |o|dk    fS )z
        Determine if the cursor is inside a string or comment.
        Returns (is_string, is_in_expression) tuple:
        - is_string: True if in any kind of string
        - is_in_expression: True if inside an f-string/t-string expression
        Fr   rj   )rc  r  rS   rU   TrT   r/   z"""z'''r]   z{{r  r  #)TFr.  )r   r   in_single_quotein_double_quotein_triple_singlein_triple_doublein_template_stringin_expressionexpression_depthiin_triple_quoter  s               rC   r  z$IPCompleter._is_in_string_or_comment	  sf       "#d))mm AD		!!Gz))!a%[C''4A;#+=+=# ,> ' ,> (	 ,>
 ( ,> &*"Q 1us4yy  QUOu,,+ -, - ,<';$+ 3-2*FAQUOu,,+ -, - ,<';$+ 3-2*FA Aw$1q53t99#4#4Q " q53t99$$a!a%iD)@)@FA 7c>> ) .] .?OST?T?T(,(A-(FA 7c>>$)$'1,,(-+,(FA.B2BO Aw#~~o~o~&5"5& / /).&aC&5"5& / /).& Aw#~~ #2 6E  #{FAq #d))mmv VV2BVFV 	 C,B]1B2.2
 	
rB   c                   |j         }|                     |          }|| j        j        k    r	 |                     |d          \  }}|                    d          r)| j        r"| j        dk    rd }nd }t          ||          }t          |d|          S # t          $ r t          g d	          cY S w xY w|                     |j                  }t          d
 |D             d	          S )z'Match attributes or global python namesF)r  rj  rj   c                0    t          j        d|           d u S Nz.*\.__.*?__rF  rx  txts    rC   r  z,IPCompleter.python_matcher.<locals>.<lambda>1
  s    rx/L/LPT/T rB   c                f    t          j        d| |                     d          d                    d u S Nz\._.*?rj  rF  rx  rindexr/  s    rC   r  z,IPCompleter.python_matcher.<locals>.<lambda>5
  s/    C

3@Q@Q<R(S(S#)$ rB   r  )r   rC  rS  c                0    g | ]}t          |d           S )variabler   rp  )r^   rx  s     rC   rw  z.IPCompleter.python_matcher.<locals>.<listcomp>C
  s3       FK$%jAAA  rB   )r   r  r  r  r  r   r  r
  rF  	NameErrorr   ro  r   )r   r   r   completion_typern  rC  no__names          rC   r  zIPCompleter.python_matcher&
  sP    (<<TBBd9CCCK$($6$6tE$6$R$R!==%% 
8$*: 
8'1,,#T#T$ $ ! %Xw77G7+     K K K*rEJJJJJJK ))'-88G& OV   	   s   A)B B65B6rj   r  Iterable[str]c                   d|v rg	 |                      |          }|                    d          r)| j        r"| j        dk    rd }nd }t          ||          }n'# t          $ r g }Y nw xY w|                     |          }|S )z~Match attributes or global python names.

        .. deprecated:: 8.27
            You can use :meth:`python_matcher` instead.rj  rj   c                0    t          j        d|           d u S r-  r.  r/  s    rC   r  z,IPCompleter.python_matches.<locals>.<lambda>U
  s    $&H^C$@$@D$H rB   c                f    t          j        d| |                     d          d                    d u S r2  r3  r/  s    rC   r  z,IPCompleter.python_matches.<locals>.<lambda>Y
  s1    $&HYs3::c??;K;K7L$M$MQU$U rB   )rm  r   r  r
  r7  ro  )r   r   rn  r9  s       rC   python_matcheszIPCompleter.python_matchesI
  s     $;;++D11==%% 	8$*: 	8'1,,%I %I%V %V$Xw77G    ))$//Gs   AA A)(A)c                D   |g S |                                                                 d         }| j                            |          }|g S |                                d                             d          }g }|D ]}|| j                            |          z  } |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  r  r  r  groupsr   r  findall)r   docrL  sigretrN   s         rC   !_default_arguments_from_docstringz-IPCompleter._default_arguments_from_docstringc
  s     ;I zz||&&((+ #**400;Ijjll1o##C(( 	4 	4A4(00333CC
rB   c                   |}g }t          j        |          rnt          j        |          st          j        |          sut          j        |          rJ||                     t          |dd                    z  }t          |dd          pt          |dd          }nt          |d          r|j        }||                     t          |dd                    z  }t           j	        j
        t           j	        j        f	 t          j        |          }|                    fd|j                                        D                        n# t           $ r Y nw xY wt#          t%          |                    S )z_Return the list of default arguments of obj if it is callable,
        or empty list otherwise.r@   rZ   r   N__new__r   c              3  4   K   | ]\  }}|j         v |V  d S r   )kind)r^   r  r  _keepss      rC   r`   z1IPCompleter._default_arguments.<locals>.<genexpr>
  s?       ) )TQv'' '''') )rB   )inspect	isbuiltin
isfunctionismethodisclassrE  r  r   r   	ParameterKEYWORD_ONLYPOSITIONAL_OR_KEYWORDr   extend
parametersr  r  r&  ra   )r   r  call_objrD  rC  rJ  s        @rC   _default_argumentszIPCompleter._default_arguments}
  s    S!! 	($S)) 	(W-=c-B-B 	(s## 
( t==#CB779 9 9 $CT:: 5sIt44  j)) (<t559b113 3 	3 #0#9;	#C((CJJ ) ) ) )S^%9%9%;%; ) ) ) ) ) ) ) 	 	 	D	 CHH~~s   AE 
EEc                X    |                      |j                  }t          |d          S )z:Match named parameters (kwargs) of the last open function.r  r   )python_func_kw_matchesr   rr  r  s      rC   r  z"IPCompleter.python_func_kw_matcher
  s,     --gm<<5gGLLLLrB   c                V   d|v rg S | j         }nC# t          $ r6 t          j        dt          j        t          j        z            x}| _         Y nw xY w|                    | j                  }t          |          }d}|D ]!}|dk    r|dz  }|dk    r|dz  }|dk    r n"g S g }t          j        d          j	        }	 	 |
                    t          |                      ||d	                   s|                                 n&t          |          dk    snn# t          $ r Y nw xY wot                      }	d	}
t          ||dd
                   D ]?\  }}|dk    r|
dz  }
n|dk    r|
dz  }
|
dk    r#|dk    r*|	                    |           @g }	 d                    |d
d
d	                   }|                     t'          || j                            }t          |          |	z
  D ]/}|                    |          r|
                    d|z             0n#  Y nxY w|S )zMatch named parameters (kwargs) of the last open function.

        .. deprecated:: 8.6
            You can use :meth:`python_func_kw_matcher` instead.
        rj  z
                '.*?(?<!\\)' |    # single quoted strings or
                ".*?(?<!\\)" |    # double quoted strings or
                \w+          |    # identifier
                \S                # other characters
                r   r  rj   r  z\w+$Tr}   Nr|   z%s=)_IPCompleter__funcParamsRegexr  rF  rG  VERBOSEDOTALLrA  r   r  rx  r{  r  popr  ra   r  r)  rd   rV  evalrc  rk   )r   r   regexpr  
iterTokensopenParr   idsisIdusedNamedArgs	par_level
next_token
argMatchescallableObj	namedArgsnamedArgs                   rC   rX  z"IPCompleter.python_func_kw_matches
  s    $;;I,VV 	- 	- 	-.0j :
 Z")+/- /- -FT+++	-  677f%%
 		 		E||1#1Q;;EIz'""(		

4
++,,,tCG}} GGIIIJ''3.. /    		 	!$VVABBZ!8!8 	% 	%E:||Q		#Q	A~~S  e$$$$

	((3ttt9--K//[48N1D 1D E EI  	NN]: 7 7&&t,, 7%%eXo6667	Ds5    =AA AD D 
D*)D*BH" "H&r  r   	list[Any]c                   t          | d          }|
 |            S t          | t                    st          | dd          r4	 t	          |                                           S # t          $ r g cY S w xY wt          | dddd          r9	 t	          | j                                                  S # t          $ r g cY S w xY wt          | dd          st          | dd	          r| j        j	        pg S g S )
N_ipython_key_completions_pandas	DataFramecoreindexing_LocIndexernumpyndarrayvoid)
r    r  r   r?  r&  r  r  r  dtypenames)r  methods     rC   	_get_keyszIPCompleter._get_keys
  s!    !&ABB688O c4   	)$4S(K$P$P 	)CHHJJ'''   			c8VZOO 	)CGLLNN+++   			c7I66 	)c7F33	)9?(b(	s$    A% %A43A4%B1 1C ?C c                Z    |                      |j                  }t          |dd          S )z7Match string keys in a dictionary, after e.g. ``foo[``.zdict keyTr   rD  )dict_key_matchesr   rF  r  s      rC   r  zIPCompleter.dict_key_matcher  s7     ''66/*$
 
 
 	
rB   c                   | j                                                             d          rg S t                              | j                   }|g S |                                \  }}}|                     |          }|t          u rg S |                     |          }|s|S t          |t          | j        | j        | j        d| j        | j                            }t!          ||| j        j        |          \  }	}
}|sg S t'          | j                   t'          |          z
  }|r|                    d          }||
z   }n|                                x}}||k    rdn
|||         d}d}| j        t'          | j                   d                                         }|                    |	          r|t'          |	          d         }nd}|                                }t1          |t2                    }|                    d           o| j        }|                    d	           o|o| j        }|o| j        }|s|s|	rfd
|D             S g }t6          j        t6          j        z  }|                                D ]Q\  }}|z   }|r|	r||	z  }||k    r	 ||v r|r|dz  }|t6          j        k    r|r|dz  }|                     |           R|S )zMatch string keys in a dictionary, after e.g. ``foo[``.

        .. deprecated:: 8.6
            You can use :meth:`dict_key_matcher` instead.
        rE  NT)r  r  r  in_subscriptr  r  )r  r/   rZ   Fr  c                    g | ]}|z   S rA   rA   )r^   r  leadings     rC   rw  z0IPCompleter.dict_key_matches.<locals>.<listcomp>v  s    111AGaK111rB   r`  )!r   r  r   DICT_MATCHER_REGEXr  r@  r  r  ry  r   r   rd  rc  r  r  r  r*  ry  r@  rl   r   r   line_bufferrk   r  r   r  r  r  r  r  r  r{  )r   r   rx  rJ  prior_tuple_keys
key_prefixr  r  tuple_prefixclosing_quotetoken_offsetrn  
text_start	key_startcompletion_startcan_close_quotecan_close_bracketcontinuationhas_known_tuple_handlingcan_close_tuple_itemresultsend_of_tuple_or_itemr  
state_flagr  r  s                            @rC   r|  zIPCompleter.dict_key_matches  ss    !''))22377 	I"))$*@AA=I-2\\^^*
!!$'')I~~c"" 	K#-~?! -!%!6  

 

 0?*dm20
 0
 0
,|W  	I /003t99<
 	7AI(<7+099;;6I( 	!!GG:&667G
  !'D,B(C(C(E(EFLLNN""=11 	#'M(:(:(<(<=LL"O#))++ $.c4#8#8  '',,,J1J 	 '',,, *(*) 	
 *Gd.G  	2'8 	2] 	211111111,9M<UU$]]__ 	# 	#MAzq[F (= (-'111 1116G1#]3338L3$NN6""""rB   c                   |j         }|                    d          }|dk    rc||dz   d         }	 t          j        |          }d|z                                   rt          |d          gdd|z   d	S n# t          $ r Y nw xY wg d
d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}   rj   NarA  r   TrU  FrS  )r   r  rM  lookupisidentifierr   rN  )r   r   r   slashposrN   rQ  s         rC   r  z IPCompleter.unicode_name_matcher  s     (::d##b==XaZ[[!A
")!,,H**,, (8d(S(S(S'T$(,01H       
 
 	
s   AA6 6
BBc                b    |                      |j                  \  }}t          |d|d          S )u{   Match Latex syntax for unicode characters.

        This does both ``\alp`` -> ``\alpha`` and ``\alpha`` -> ``α``
        rT  TrB  )latex_matchesr   rF  r   r   rC  rn  s       rC   r  zIPCompleter.latex_name_matcher  s?     !..w/HII'/'H$
 
 
 	
rB   rH  c                    |                     d          }|dk    r<||d         t          v rt                   gfS fdt          D             }|r|fS dS )u   Match Latex syntax for unicode characters.

        This does both ``\alp`` -> ``\alpha`` and ``\alpha`` -> ``α``

        .. deprecated:: 8.6
            You can use :meth:`latex_name_matcher` instead.
        r]   r}   Nc                >    g | ]}|                               |S rA   r  )r^   r  rN   s     rC   rw  z-IPCompleter.latex_matches.<locals>.<listcomp>  s(    GGGq||AG1GGGrB   rJ  )r  r   )r   r   r  rn  rN   s       @rC   r  zIPCompleter.latex_matches  s     ::d##b==XYYAM!! =+,,, HGGGmGGG &g:%vrB   c                    |                      |j                  pg }t          |t          d          }d|d<   t	          | j                  h|d<   |S )zpDispatch custom completer.

        If a match is found, suppresses all other matchers except for Jedi.
        Tr{  r   r   )dispatch_custom_completerr   rF  _UNKNOWN_TYPEr  r  )r   r   rn  r  s       rC   r  z$IPCompleter.custom_completer_matcher  sc     00??E21-T
 
 
 !y%4T5G%H%H$I !rB   c                  	 | j         sdS | j        }|                                sdS t                      }||_        |_        |                    dd          d         }||_        | j        |_        |	                    | j
                  s#| j                             | j
        |z             }ng }t          j        | j                             |          || j                             | j                            D ]e}	  ||          }|r8fd|D             }|r|c S                                 		fd|D             c S I# t           $ r Y Ut"          $ r 	 Y  nw xY wdS )zg
        .. deprecated:: 8.6
            You can use :meth:`custom_completer_matcher` instead.
        Nrj   r   c                >    g | ]}|                               |S rA   r  )r^   rr   s     rC   rw  z9IPCompleter.dispatch_custom_completer.<locals>.<listcomp>  s*    EEEa!,,t2D2DEEEErB   c                b    g | ]+}|                                                               )|,S rA   )r  rk   )r^   r  text_lows     rC   rw  z9IPCompleter.dispatch_custom_completer.<locals>.<listcomp>  s4    MMM!aggii.B.B8.L.LMAMMMrB   )r  r  r  r
   rL  symbolr   commandr   rk   r  	s_matchesr  r  flat_matchesr  r   KeyboardInterrupt)
r   r   rL  eventcmd	try_magicr_   r  withcaser  s
    `       @rC   r  z%IPCompleter.dispatch_custom_completer  s   
 % 	Fzz|| 	4  !!
jja  #"&"8 ~~d/00 	.88!C') )II I!7!A!A#!F!F'44T5KLLN N 	 	Aahh NEEEE3EEEH ('#zz||HMMMMsMMMMMMN    $     ts   E"!E
E!
E! E!r2  Iterator[Completion]c           	   #    K   t          j        dt          d           t                      }	 | j        r-ddl}|                                }|                                 nd}|                     ||| j	        dz            D ]"}|r||v r	|V  |
                    |           #n# t          $ r 	 Y nw xY w||                                 t          | j                   t          j                            | j        t%          t'          j                                        }t+          d|           |                    |           dS dS # ||                                 t          | j                   t          j                            | j        t%          t'          j                                        }t+          d|           |                    |           w w xY 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.rT   r   r   Ni  )_timeoutzWriting profiler output to)rI   r   r<   ra   profile_completionscProfileProfileenable_completionsr  r)  r  disabler"   profiler_output_dirrm   rf   rd   rO   uuiduuid4r5  
dump_stats)r   r   r2  r,  r  profilerr_   output_paths           rC   r   zIPCompleter.completions  s     \ 	 >  ;q	J 	J 	J 	J
 uu	1'  #++--!!!!&&tVd>\]a>a&bb   !t))	
 ! 	 	 	.D	
 #  """!$":;;; gll4+CSEVEVWW2K@@@##K00000 $#x#  """!$":;;; gll4+CSEVEVWW2K@@@##K0000 $s+   A9B( 'E (B63E 5B66E BG$r   c          
   #  \  K   t          j                    |z   }|d|         }t          ||          \  }}t          | j                  dfd|                     |||	          }fd
|                                D             }	|v r!t          t          |                   d         nd}
t          |
          }|r|D ]}	 |j
        }n)# t          $ r | j        rt          d|           d}Y nw xY wt          |j                  t          |j                  z
  }|dk    rt#          |          }nd}t%          ||z
  ||j        ||d          V  t          j                    |k    r n|D ]O}t          |j                  t          |j                  z
  }t%          ||z
  ||j        t&          dd          V  P|
rg|	re| j        r^|                    t+          t          |	                                                    d                   }t%          ||dddd          V  g }g }|	                                D ]\  }}|d         }|                    |          }|                    dd          }|r|n|}|                    |          sJ |d         D ]=}t%          |||j        |d|j
        pt&                    }|                    |           >t7          |                     ||                     |          z                       dt<                   E d{V  d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.

        Nr  r   r  rO   rP   TypeGuard[SimpleMatcherResult]c                    |k    S r   rA   )r  r  jedi_matcher_ids     rC   is_non_jedi_resultz4IPCompleter._completions.<locals>.is_non_jedi_result  s     00rB   )r   r   rM  c                4    i | ]\  }} ||          ||S rA   rA   )r^   r  r  r  s      rC   rz  z,IPCompleter._completions.<locals>.<dictcomp>  sB     <
 <
 <
"
F!!&*55<
<
 <
 <
rB   r   rA   zError in Jedi getting type of functionrZ   r3  r   )r   r   r   r   r   r   r   z--jedi/ipython--r  none)r   r   r   r   r   r   r   F)r   r   r   r   r   r   )r  r   r  rO   rP   r  )time	monotonicr8  r  r  	_completer  r.   r   r  r   r  r  r5  rl   r   r   rk  r   r  r  r  valuesr  r   r   r{  r&  _deduplicate_sortMATCHES_LIMIT)r   r   r2  r  deadliner5  r   r  r  non_jedi_resultsjedi_matchesiter_jmjmtype_deltar   some_start_offsetr   sortableoriginr  matched_textstart_offset
is_ordered	containersimple_completionrh  r  r  s                              @@rC   r  zIPCompleter._completions`  s@     4 >##h.7F7#%7	6%J%J"])$*<==	1 	1 	1 	1 	1 	1
 ..[] ! 
 
<
 <
 <
 <
&-mmoo<
 <
 <
 ')) #W_%=>>}MM 	 |$$ 	  !GEE  ! ! !z D>CCC EEE! B011C4D4DDJ&& / 3 3II "I v~%+&(&:&++4)/1 1 1 1 1 1 >##h..E /  		 		B,--BK0@0@@Eun)"        	, 	 	 &T*113344556HI! ! ''      %'%'.4466 	- 	-NFF!"45L!<<55LIu55J#-;8I ??<00000%+M%: 	- 	-!'&*/" */@=  
   ,,,,	- ))'DJJx4H4H*HIIJJ]N
 	
 	
 	
 	
 	
 	
 	
 	
 	
s   C#C54C5c                    t          j        dt                     |                     |||d          }t	          | j                  }|                     ||h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  rM  r   r   Tskip_matchersabort_if_offset_changes)rI   r   PendingDeprecationWarningr  r  r  _arrange_and_extract)r   r   r  rM  r  r  s         rC   r   zIPCompleter.complete  s    H 	 O/	1 	1 	1 ..#
ST ! 
 
 *$*<==((*+$( ) 
 
 	
rB   r  dict[str, MatcherResult]r  set[str]r  rt   c                   g }g }d }|                                 D ]z\  }}||v r
|d         s|s|d         }|r|d         |k    r nN|                    dd          r|                    |d                    _|                    |d                    {|sd}|d |                     ||                     |          z             D             fS )Nr   r   r   FrZ   c                    g | ]	}|j         
S rA   )r   )r^   r>  s     rC   rw  z4IPCompleter._arrange_and_extract.<locals>.<listcomp>;  s'     &
 &
 &
AF&
 &
 &
rB   )r  r  rS  r  r  )	r   r  r  r  r  r   most_recent_fragmentr  r  s	            rC   r  z IPCompleter._arrange_and_extract  s"    02.0#")--// 	7 	7J]**-( ' B'-.@'A$'-.2FFFzz)U++ 7vm45555} 56666# 	&#% # &
 &
 --g

88L8L.LMM&
 &
 &
 
 	
rB   )r  r   r   _CompleteResultc               X   | |t          |          nt          |          }| j        rt          j        | _        |s|r|                    d          |         }|s|r| j                            ||          nd}||}|| _        | j        d|         | _	        |s|}t          ||||t                    }i }t          | j                  }t                      }	d t          | j        t"          d          D             }
|
                                D ]\  }}t          |          }|| j        v r||v rt)          j        d| d	           ||	v r@	 t-          |          r t/           ||          t0          
          }n<t3          |          r ||          }n!t5          |          }t7          d|           n/# t8          $ r" t;          j        t;          j                      Y w xY w|                     d|j!                  |d<   |	s|                     dd          }tE          | j#        tH                    r| j#                             |d          n| j#        }|du p|o|duotK          |          }|r|                     dt                                }tE          |tL                    rt          |          }nt          |
          }||z
  }	i }|                                D ]\  }}||	vr|||<   |}|||<   | '                    ||hd          \  }}|| _(        |S )a  
        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
        -------
        An ordered dictionary where keys are identifiers of completion
        matchers and values are ``MatcherResult``s.
        Nr   rZ   )r   r   r   r   r   c                .    i | ]}t          |          |S rA   )r  )r^   r   s     rC   rz  z)IPCompleter._complete.<locals>.<dictcomp>  s2     
 
 
 G$$g
 
 
rB   T)r  reversezDuplicate matcher ID: rj  r   zUnsupported API version r   r   Fr   r  ))rl   rb  rk  rl  rc  r   ry  rO  r  r   r   r  r  r  ra   r  r  r  r  r  rI   r   r   rr  r  r   r   r  BaseExceptionrb   
excepthookexc_infor  r   r  r  r   r
  r   r  rn  )r   r   rM  r  r   r   r   r  r  suppressed_matchersr  
matcher_idr   r  r   suppression_recommendedsuppression_configshould_suppresssuppression_exceptionsto_suppressnew_resultsprevious_matcher_idprevious_resultr{   rn  s                            rC   r  zIPCompleter._complete?  s	   N -1\[)))s4yyJ 	/%.DN  	= 	=#//$//<K 	EPX((jAAAVX 
 K '!%!1+:+!> 	$#I#&#
 
 
 -/)$*<==(+
 
!#8$  
 
 
 $,>>#3#3 ?	) ?	)J(11JT222W$$DzDDDEEE000!'** OCM  FF $G,, O$WW--FF":7"C"CK$%M%M%MNNN     //	 *04F)V)VF%&& *AGB B' "$"BDII:D488TJJJ9 # (4/ W/U5Gu5T#2 *&11  
 # *7=zz)3558 8* ""98DD 4&)*A&B&B&)(mm*58N*N'"$K@G O O<+_.6III?NK(;<)G"(GJ.. ++$) / 
 

7 s   A+G)G.-G.rn  Sequence[AnyCompletion]Iterable[AnyCompletion]c                    i }| D ](}|j         }||vs||         j        t          k    r|||<   )|                                S r   )r   r   r  r  )rn  filtered_matchesrx  r   s       rC   r  zIPCompleter._deduplicate  s]     68 	/ 	/E:D,,,#D).-??). &&&(((rB   c                &    t          | d           S )Nc                *    t          | j                  S r   )r   r   r  s    rC   r  z#IPCompleter._sort.<locals>.<lambda>  s    -DQV-L-L rB   r  )r  )rn  s    rC   r  zIPCompleter._sort  s    g#L#LMMMMrB   c                b    |                      |j                  \  }}t          |d|d          S )zASame as :any:`fwd_unicode_match`, but adopted to new Matcher API.rA  TrB  )fwd_unicode_matchr   rF  r  s       rC   r  zIPCompleter.fwd_unicode_matcher  s?     !2273LMM'/)hD
 
 
 	
rB   c                F   |                     d          }|dk    r||dz   d         }|                                fd| j        D             }|r||fS fd| j        D             }|r||fS                     d          fd| j        D             }|r||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 of Unicode character names on first call and cache it.

        .. deprecated:: 8.6
            You can use :meth:`fwd_unicode_matcher` instead.

        Returns
        -------
        At tuple with:
            - matched text (empty if no matches)
            - list of potential completions, empty tuple  otherwise)
        r]   r}   rj   Nc                >    g | ]}|                               |S rA   r  r^   r  sups     rC   rw  z1IPCompleter.fwd_unicode_match.<locals>.<listcomp>+  s*    MMM1<<;L;LM!MMMrB   c                    g | ]}|v |	S rA   rA   r  s     rC   rw  z1IPCompleter.fwd_unicode_match.<locals>.<listcomp>.  s    DDD3!88!888rB   r:   c                L    g | ]t          fd D                        S )c              3      K   | ]}|v V  	d S r   rA   )r^   ur  s     rC   r`   z;IPCompleter.fwd_unicode_match.<locals>.<listcomp>.<genexpr>3  s'      4N4NQ!V4N4N4N4N4N4NrB   )all)r^   r  splitsups    @rC   rw  z1IPCompleter.fwd_unicode_match.<locals>.<listcomp>2  sL       4N4N4N4NX4N4N4N1N1N  rB   rJ  )r  upperunicode_namesr   )r   r   r  rN   
candidatesr  r  s        @@rC   r  zIPCompleter.fwd_unicode_match  s    @ ::d##b== X\^^$A''))CMMMMT%7MMMJ %*}$DDDDT%7DDDJ %*}$yy~~H   -  J  %*}$6 6rB   c                   | j         sg }t          dd          D ]G}	 |                    t          j        t          |                               8# t          $ r Y Dw xY 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   )	r  ranger{  rM  r   chrr  _unicode_name_compute_UNICODE_RANGES)r   rw  r_   s      rC   r
  zIPCompleter.unicode_names>  s     &E1\**  LL!1#a&&!9!9::::!   D"7"H"HD""s   4A
AA)NNNN)rP   r  r   )r   rO   r   r   rP   r   )r   r   rP   r   )r  r   r   r   r   rO   rP   r   )r   rO   rP   r:  )r  r   rP   rk  r   r   r   rO   rP   rH  )r   rO   r2  r   rP   r  )r   rO   r2  r   rP   r  )NNN)rP   rH  )r  r  r  r  r  rt   )rP   r  )rn  r  rP   r  )rn  r  )rP   r   )Cr=   r>   r?   r@   r+   r|  r$   r  
UnionTraitr  r  r  r  	ListTraitr(   r  r%   r  r  r  r  r  r   rQ  r  r  r  r  context_matcherr  r  r  r  r  r  r  r  r  r  r  r  r  r>  rE  rV  r  rX  staticmethodry  r  r|  r  r  r  r  r  r   r  r   r  r  r  r  r  r  r
  r  r  s   @rC   r8   r8   N  s       IIWX	* 	* 	* T  N #-*						$$t*E*E*E F FG# # #. 
cc/  2 
 
 
 
cc  !y		   
cc  $	   
cc  d5
   
cc  $T   
cc 
 "',Q   
cc 
 W    IMX4 X4 X4 X4 X4 X4t    X:	& 	& 	& 	&' ' ' '2 2 2 2 _f
 f
 f
 f
P _1
 1
 1
 1
f _M M M M% % % %N _
 
 
 
0 _ :;;;

 

 

 <;

R  R  R  R h       2 2 2>r
 r
 r
h _       D A&&&   '&2  4     D _M M M M
P P Pd    \. _
 
 
 
u u u un _
 
 
 
> _
 
 
 
   . _  2 2 2hL1 L1 L1 L1\B
 B
 B
 B
J 7;8
 8
 8
 8
 8
t
 
 
 
B AE4 b b b b b bH ) ) ) \) N N N \N _
 
 
 
; ; ; ;z # # # X# # # # #rB   rangeslist[tuple[int, int]]r   c           	         g }| D ]]\  }}t          ||          D ]G}	 |                    t          j        t	          |                               8# t
          $ r Y Dw xY w^|S r   )r  r{  rM  r   r  r  )r  rw  r   stopr_   s        rC   r  r  P  s    E  
dud## 	 	A[-c!ff556666   	
 Ls   4A
AA)rG   )rN   rO   rP   rQ   )rN   rO   rX   rO   rP   rO   )rf   rO   rP   rg   )rf   rO   ro   rt   rp   rO   rP   rO   )r   r   rP   r   )r   r   rP   r   )r   r   rP   r   )r   r   rP   r   )r  r   rP   rt   )r  r  r  r   r   r   rP   r  )r   r   )r   rO   r   r  rP   r  )r   rO   r   r  r/  rt   rP   r  )r  rO   rP   r  r   )
r  r  r  rO   r@  rO   r  r  rP   r  )r   rO   rL  r   r+  r   rP   r   )r   rO   r2  r   rP   r3  r  r  r  r   )rn  rl  r   rO   rP   r   )NF)
rn  rl  r   rO   rC  r   rD  rt   rP   r   )r  r  rP   r   )r@   
__future__r   builtinsr~  r  r  rK  r  r|  r  rm   rF  r  rb   r  r  rM  r  rI   r   collectionsr   
contextlibr   dataclassesr   	functoolsr   r	   typesr
   typingr   r   r   r   r   r   r   r   r   r   IPython.core.guarded_evalr   r   IPython.core.errorr   IPython.core.inputtransformer2r   IPython.core.latex_symbolsr   r   IPython.testing.skipdoctestr   IPython.utilsr   IPython.utils.PyColorizer   IPython.utils.decoratorsr   IPython.utils.dir2r   r    IPython.utils.docsr!   IPython.utils.pathr"   IPython.utils.processr#   	traitletsr$   r%   r&   r'   r  r(   r)   r  r*   r  r+   traitlets.config.configurabler,   traitlets.utils.importstringr-   rk  r.   version_infotyping_extensionsr1   r2   r3   r4   r5   __skip_doctest__r3  settingscase_insensitive_completionjedi.api.helpersjedi.api.classesr  ImportErrorr  r  rc   PROTECTABLESr  r  objectr  FutureWarningr<   rK   rM   rW   re   rs   rx   r   r   _JediCompletionLiker   r   r   r   r   AnyMatcherCompletionr   r   r   r   r   r   r   r   r   r   r   r   r   r
  r  r  r  r   r  r  r.  r;  rP  rx  r=  r7   r  Flagr  r  r  binocthexr  r*  r1  r8  r?  rG  rE  rW  r\  rk  r   rO   r  rG  r  rr  rF  r8   r  rA   rB   rC   <module>rD     sn  j j jf # " " " " "             



 				 				  



               # # # # # # % % % % % % ! ! ! ! ! ! . . . . . . . . ! ! ! ! ! !                        F E E E E E E E & & & & & & 4 4 4 4 4 4 J J J J J J J J 4 4 4 4 4 4 " " " " " " 0 0 0 0 0 0 3 3 3 3 3 3 4 4 4 4 4 4 4 4 7 7 7 7 7 7 0 0 0 0 0 0 + + + + + +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 7 6 6 6 6 6 4 4 4 4 4 4       gXXXXXXXXXXXXXXXMMMMMMMMMMMMMM  KKK05DM-NN   NNN !"45 
&<7LL*L   FHH		 	 	 	 	- 	 	 	  *E F F F F     8   * 2>     %, %, %, %,P     @; ; ; ; ; ; ; ;. 13FFG G7 G7 G7 G7 G7 G7 G7 G7TK K K K K K K K0       $ tVHMMMI I I I I,i I I NMI/ / / / /+ / / / 02BBC )=zJJ #< #< #< #< #< #< #< #<N )+==>           *H      13E EF F F F F    8    <56 6 6 6 6   
   
% % % %
& & & &
   . !% $	% % % % % %P3 3 3 3H H H H6 6 6 ',!<<< z' ' ' 'T HM 8; 8; 8; 8; 8; 8;v <7-FF0F02 02 02 02 02 02 02 02hw& w& w& w& w& w& w& w&r4 4 4    DI   
 
 
       H 

  =A	^' ^' ^' ^' ^'B@ @ @ @:   D" " "    ' ' ' 'T " " " "H   ,U U U U< sM)*  RZ,. . b    # %	- - - - - # # # # #) # # #D8     s   -E EE