
    Ki#y                         d Z ddlZej        j        dk    rd ZeZd Zd Zne	Zd Zd Zd	d
l
mZmZmZmZ  G d de          Z G d de          Z G d de          Zd Zd Zd Z G d de          ZdS )a"  
Provides classes and helper functions to describe a LaTeX context of known
macros and environments, specifying how they should be parsed by
:py:mod:`pylatexenc.latexwalker`.

.. versionadded:: 2.0

   The entire module :py:mod:`pylatexenc.macrospec` was introduced in
   `pylatexenc 2.0`.
    N   c                     | S N )ss    u/var/www/development/aibuddy-work/election-extract/venv/lib/python3.11/site-packages/pylatexenc/macrospec/__init__.pyunicoder	   +   s    1H    c                     | S r   r   xs    r   <lambda>r   -       ! r
   c                     | S r   r   r   s    r   r   r   .   r   r
   c                 F    t          |                               d          S Nzutf-8)r	   encoder   s    r   r   r   2   s    '!**"3"3G"<"< r
   c                 ,    |                      d          S r   )decoder   s    r   r   r   3   s    !((7"3"3 r
      )ParsedMacroArgsMacroStandardArgsParserParsedVerbatimArgsVerbatimArgsParserc                   B     e Zd ZdZ e            f fd	Zd Zd Z xZS )	MacroSpeca  
    Stores the specification of a macro.

    This stores the macro name and instructions on how to parse the macro
    arguments.

    .. py:attribute:: macroname

       The name of the macro, without the leading backslash.

    .. py:attribute:: args_parser

       The parser instance that can understand this macro's arguments.  For
       standard LaTeX macros this is usually a
       :py:class:`MacroStandardArgsParser` instance.

       If you specify a string, then for convenience this is interpreted as an
       argspec argument for :py:class:`MacroStandardArgsParser` and such an
       instance is automatically created.
    c                      t          t          |           j        di | || _        t	          |t
                    rt          |          | _        d S || _        d S Nr   )superr   __init__	macroname
isinstance_basestringr   args_parser)selfr!   r$   kwargs	__class__s       r   r    zMacroSpec.__init__R   sc    'i'11&111"k;// 	+6{CCD*Dr
   c                 &     | j         j        |i |S z
        Shorthand for calling the :py:attr:`args_parser`\ 's `parse_args()` method.
        See :py:class:`MacroStandardArgsParser`.
        r$   
parse_argsr%   argsr&   s      r   r+   zMacroSpec.parse_argsZ       
 +t*D;F;;;r
   c                 (    d| j         d| j        dS )NzMacroSpec(macroname=, args_parser=))r!   r$   r%   s    r   __repr__zMacroSpec.__repr__a   s     :>...$JZJZJZ[[r
   	__name__
__module____qualname____doc__r   r    r+   r3   __classcell__r'   s   @r   r   r   =   s{         ( /F.E.G.G + + + + + +< < <\ \ \ \ \ \ \r
   r   c                   D     e Zd ZdZ e            df fd	Zd Zd Z xZS )EnvironmentSpecaP  
    Stores the specification of a LaTeX environment.

    This stores the environment name and instructions on how to parse any
    arguments provided after ``\begin{environment}<args>``.

    .. py:attribute:: environmentname

       The name of the environment, i.e., the argument of ``\begin{...}`` and
       ``\end{...}``.

    .. py:attribute:: args_parser

       The parser instance that can understand this environment's arguments.
       For standard LaTeX environment this is usually a
       :py:class:`MacroStandardArgsParser` instance.

       If you specify a string, then for convenience this is interpreted as an
       argspec argument for :py:class:`MacroStandardArgsParser` and such an
       instance is automatically created.

    .. py:attribute:: is_math_mode

       A boolean that indicates whether or not the contents is to be interpreted
       in Math Mode.  This would be True for environments like
       ``\begin{equation}``, ``\begin{align}``, etc., but False for
       ``\begin{figure}``, etc.

    .. note::

       Starred variants of environments (as in ``\begin{equation*}``) must not
       be specified using an argspec as for macros (e.g., `argspec='*'`).
       Rather, we need to define a separate environment spec for the starred
       variant with the star in the name itself (``EnvironmentSpec('equation*',
       None)``) because the star really is part of the environment name.  If you
       happened to use ``EnvironmentSpec('equation', '*')``, then the parser
       would recognize the expression ``\begin{equation}*`` but not
       ``\begin{equation*}``.
    Fc                      t          t          |           j        di | || _        t	          |t
                    rt          |          | _        n|| _        || _        d S r   )	r   r<   r    environmentnamer"   r#   r   r$   is_math_mode)r%   r>   r$   r?   r&   r'   s        r   r    zEnvironmentSpec.__init__   si    -ot$$-77777.k;// 	+6{CCD*D(r
   c                 &     | j         j        |i |S r)   r*   r,   s      r   r+   zEnvironmentSpec.parse_args   r.   r
   c                 8    d| j         d| j        d| j        dS )Nz EnvironmentSpec(environmentname=r0   z, is_math_mode=r1   )r>   r$   r?   r2   s    r   r3   zEnvironmentSpec.__repr__   s0        $"2"2"2D4E4E4E
 	
r
   r4   r:   s   @r   r<   r<   f   sx        & &N 5L4K4M4M#) ) ) ) ) )< < <
 
 
 
 
 
 
r
   r<   c                   2     e Zd ZdZ	 d fd	Zd Zd Z xZS )SpecialsSpecas  
    Specification of a LaTeX "special char sequence": an active char, a
    ligature, or some other non-macro char sequence that has a special meaning.

    For instance, '&', '~', and '``' are considered as "specials".

    .. py:attribute:: specials_chars
    
       The string (one or several characters) that has a special meaning. E.g.,
       '&', '~', '``', etc.

    .. py:attribute:: args_parser
    
       A parser (e.g. :py:class:`MacroStandardArgsParser`) that is invoked when
       the specials is encountered.  Can/should be set to `None` if the specials
       should not parse any arguments (e.g. '~').
    Nc                 d     t          t          |           j        di | || _        || _        d S r   )r   rC   r    specials_charsr$   )r%   rE   r$   r&   r'   s       r   r    zSpecialsSpec.__init__   s>     	+lD!!*44V444,&r
   c                 8    | j         dS  | j         j        |i |S )a  
        Basically a shorthand for calling the :py:attr:`args_parser`\ 's
        `parse_args()` method.  See :py:class:`MacroStandardArgsParser`.
        
        If however the py:attr:`args_parser` attribute is `None`, then this
        method returns `None`.
        Nr*   r,   s      r   r+   zSpecialsSpec.parse_args   s-     #4*t*D;F;;;r
   c                 (    d| j         d| j        dS )NzSpecialsSpec(specials_chars=r0   r1   )rE   r$   r2   s    r   r3   zSpecialsSpec.__repr__   s%     !1!1!1
 	
r
   r   )r5   r6   r7   r8   r    r+   r3   r9   r:   s   @r   rC   rC      sj         $ "' ' ' ' ' '
< 
< 
<
 
 
 
 
 
 
r
   rC   c                    t          | t                    rAt          |          dk    rt          d          t          | dd                   }| d         } t          | t                    r$t          |          dk    rt          d          | S t          | t
                    r$t          |          dk    rt          d          | S t          |          dk    r	|d         }n|t          |          dk    r#t          d                    | |                    |d         s$t          |d         t                    r	|d         }nd	}|d         rd
}|d|d         z  z  }|                    dd          r3t          | t          |          |                    dd                    S t	          | t          |                    S )a	  
    Return a macro specification for the given macro.  Syntax::
    
      spec = std_macro(macname, argspec)
      #  or
      spec = std_macro(macname, optarg, numargs)
      #  or
      spec = std_macro( (macname, argspec), )
      #  or
      spec = std_macro( (macname, optarg, numargs), )
      #  or
      spec = std_macro( spec ) # spec is already a `MacroSpec` -- no-op

    - `macname` is the name of the macro, without the leading backslash.

    - `argspec` is a string either characters "\*", "{" or "[", in which star
      indicates an optional asterisk character (e.g. starred macro variants),
      each curly brace specifies a mandatory argument and each square bracket
      specifies an optional argument in square brackets.  For example, "{{\*[{"
      expects two mandatory arguments, then an optional star, an optional
      argument in square brackets, and then another mandatory argument.

      `argspec` may also be `None`, which is the same as ``argspec=''``.

    - `optarg` may be one of `True`, `False`, or `None`, corresponding to these
      possibilities:

      + if `True`, the macro expects as first argument an optional argument in
        square brackets. Then, `numargs` specifies the number of additional
        mandatory arguments to the command, given in usual curly braces (or
        simply as one TeX token like a single macro)

      + if `False`, the macro only expects a number of mandatory arguments given
        by `numargs`. The mandatory arguments are given in usual curly braces
        (or simply as one TeX token like a single macro)

      + if `None`, then `numargs` is a string like `argspec` above.  I.e.,
        ``std_macro(macname, None, argspec)`` is the same as
        ``std_macro(macname, argspec)``.

    - `numargs`: depends on `optarg`, see above.
    
    To make environment specifications (:py:class:`EnvironmentSpec`) instead of
    a macro specification, use the function :py:func:`std_environment()`
    instead.

    The helper function :py:func:`std_environment()` is a shorthand for calling
    this function with additional keyword arguments.  An optional keyword
    argument `make_environment_spec=True` to the present function may be
    specified to return an `EnvironmentSpec` instead of a `MacroSpec`.  In this
    case, you can further specify the `environment_is_math_mode=True|False` to
    specify whether of not the environment represents a math mode.
    r   z=No positional arguments expected if first argument is a tupler   NzANo positional arguments expected if first argument is a MacroSpeczGNo positional arguments expected if first argument is a EnvironmentSpecr   z@Wrong number of arguments for std_macro, macname={!r}, args={!r} [{make_environment_specFenvironment_is_math_mode)r$   r?   r$   )
r"   tuplelen	TypeErrorr   r<   formatr#   getr   )macnamer-   r&   argspecs       r   	std_macrorV      s   n '5!! t99>>[\\\WQRR[!!!*'9%% t99>>_```'?++ t99>>efff
4yyA~~q'	TaNUU   	 !W DG[99 q'7 	G3tAw;zz)511 [w4KG4T4T,2JJ7QSX,Y,Y[ [ [ 	[W*A'*J*JKKKKr
   c                     |                     dd          }t          |          }|                    d|           t          | g|R i |S )a
  
    Return an environment specification for the given environment.  Syntax::

      spec = std_environment(envname, argspec, is_math_mode=True|False)
      #  or
      spec = std_environment(envname, optarg, numargs, is_math_mode=True|False)
      #  or
      spec = std_environment( (envname, argspec), is_math_mode=True|False)
      #  or
      spec = std_environment( (envname, optarg, numargs), is_math_mode=True|False)
      #  or
      spec = std_environment( spec ) # spec is already a `EnvironmentSpec` -- no-op

    - `envname` is the name of the environment, i.e., the argument to
      ``\begin{...}``.

    - `argspec` is a string either characters "\*", "{" or "[", in which star
      indicates an optional asterisk character (e.g. starred environment
      variants), each curly brace specifies a mandatory argument and each square
      bracket specifies an optional argument in square brackets.  For example,
      "{{\*[{" expects two mandatory arguments, then an optional star, an
      optional argument in square brackets, and then another mandatory argument.

      `argspec` may also be `None`, which is the same as ``argspec=''``.

    .. note::

       See :py:class:`EnvironmentSpec` for an important remark about starred
       variants for environments.  TL;DR: a starred verison of an environment is
       defined as a separate `EnvironmentSpec` with the star in the name and
       *not* using an ``argspec='*'``.

    - `optarg` may be one of `True`, `False`, or `None`, corresponding to these
      possibilities:

      + if `True`, the environment expects as first argument an optional argument in
        square brackets. Then, `numargs` specifies the number of additional
        mandatory arguments to the command, given in usual curly braces (or
        simply as one TeX token like a single environment)

      + if `False`, the environment only expects a number of mandatory arguments given
        by `numargs`. The mandatory arguments are given in usual curly braces
        (or simply as one TeX token like a single environment)

      + if `None`, then `numargs` is a string like `argspec` above.  I.e.,
        ``std_environment(envname, None, argspec)`` is the same as
        ``std_environment(envname, argspec)``.

    - `numargs`: depends on `optarg`, see above.

    - `is_math_mode`: if set to True, then the environment represents a math
      mode environment (e.g., 'equation', 'align', 'gather', etc.), i.e., whose
      contents should be parsed in an appropriate math mode.  Note that
      `is_math_mode` *must* be given as a keyword argument, in contrast to all
      other arguments which must be positional (non-keyword) arguments.
    r?   FT)rL   rM   )popdictupdaterV   )envnamer-   r&   r?   kwargs2s        r   std_environmentr]   2  sa    r ::ne44L6llGNN,8  : : :W/t///w///r
   c                 $    t          | d          S )a  
    Return a latex specials specification for the given character sequence.  Syntax::

      spec = std_specials(specials_chars)

    where `specials_chars` is the sequence of characters that has a special
    LaTeX meaning, e.g. ``&`` or ``''``.

    This helper function only allows to create specs for simple specials without
    any argument parsing.  For more complicated specials, you can instantiate a
    :py:class:`SpecialsSpec` directly.
    NrN   )rC   rE   s    r   std_specialsr`   r  s     D9999r
   c                        e Zd ZdZ fdZg g g dddfdZd Zd Zd Zd	 Z	d
 Z
d Zd ZddZddZddZddZg g g fdZ xZS )LatexContextDba  
    Store a database of specifications of known macros, environments, and other
    latex specials.  This might be, e.g., how many arguments a macro accepts, or
    how to determine the text representation of a macro or environment.

    When used with :py:class:`pylatexenc.latexwalker.LatexWalker`, the
    specifications describe mostly rules for parsing arguments of macros and
    environments, and which sequences of characters to consider as "latex
    specials".  Specifications for macros, environments, and other specials are
    stored as :py:class:`MacroSpec`, :py:class:`EnvironmentSpec`, and
    :py:class:`SpecialsSpec` instances, respectively.
    When used with :py:class:`pylatexenc.latex2text.LatexNodes2Text`, the
    specifications for macros, environments, and other specials are stored as
    :py:class:`pylatexenc.latex2text.MacroTextSpec` ,
    :py:class:`pylatexenc.latex2text.EnvironmentTextSpec`, and
    :py:class:`pylatexenc.latex2text.SpecialsTextSpec` instances, respectively.

    In fact, the objects stored in this database may be of any type, except that
    macro specifications must have an attribute `macroname`, environment
    specifications must have an attribute `environmentname`, and specials
    specification must have an attribute `specials_chars`.

    The `LatexContextDb` instance is meant to be (pseudo-)immutable.  Once
    constructed and all the definitions added with
    :py:meth:`add_context_category()`, one should refrain from modifying it
    directly after providing it to, e.g., a
    :py:class:`~pylatexenc.latexwalker.LatexWalker` object.  The reason is that
    the latex walker keeps track of what the latex context was when parsing
    nodes, and modifying the context will modify that stored information, too.
    Instead of being tempted to modify the object, create a new one with
    :py:meth:`filter_context()`.

    See :py:func:`pylatexenc.latexwalker.get_default_latex_context_db()` for the
    default latex context for `latexwalker` with a default collection of known
    latex macros and environments.
    See :py:func:`pylatexenc.latex2text.get_default_latex_context_db()` for the
    default latex context for `latex2text` with a set of text replacements for a
    collection of known macros and environments.
    c                      t          t          |           j        di | g | _        i | _        d | _        d | _        d | _        d S r   )r   rb   r    category_listdunknown_macro_specunknown_environment_specunknown_specials_spec)r%   r&   r'   s     r   r    zLatexContextDb.__init__  sS    ,nd##,66v666"&(,%%)"""r
   FNc                 
   || j         v r"t          d                    |                    t          d |||fD                       dk    rt	          d          |r| j                             d|           n|rB|| j         v r| j                             |          }nd}| j                             ||           ns|rW|| j         v r| j                             |          dz   }nt          | j                   }| j                             ||           n| j                             |           t          d |D                       t          d |D                       t          d |D                       d	| j	        |<   d
S )a  
        Register a category of macro and environment specifications in the context
        database.

        The category name `category` must not already exist in the database.

        The argument `macros` is an iterable (e.g., a list) of macro
        specification objects.  The argument `environments` is an iterable
        (e.g., a list) of environment spec objects.  Similarly, the `specials`
        argument is an iterable of latex specials spec instances.

        If you specify `prepend=True`, then macro and environment lookups will
        prioritize this category over other categories.  Categories are normally
        searched for in the order they are registered to the database; if you
        specify `prepend=True`, then the new category is prepended to the
        existing list so that it is searched first.

        If `insert_before` is not `None`, then it must be a string; the
        definitions are inserted in the category list immediately before the
        given category name, or at the beginning of the list if the given
        category doesn't exist.  If `insert_after` is not `None`, then it must
        be a string; the definitions are inserted in the category list
        immediately after the given category name, or at the end of the list if
        the given category doesn't exist.

        You may only specify one of `prepend=True`, `insert_before='...'` or
        `insert_after='...'`.
        z9Category {} is already registered in the context databasec                     g | ]}||S r   r   ).0r   s     r   
<listcomp>z7LatexContextDb.add_context_category.<locals>.<listcomp>  s    IIIqaIIIIr
   r   zgadd_context_category(): You may only specify one of prepend=True, insert_before=... or insert_after=...r   c              3   (   K   | ]}|j         |fV  d S r   )r!   )rk   ms     r   	<genexpr>z6LatexContextDb.add_context_category.<locals>.<genexpr>  s)      >>Q[!,>>>>>>r
   c              3   (   K   | ]}|j         |fV  d S r   )r>   )rk   es     r   ro   z6LatexContextDb.add_context_category.<locals>.<genexpr>  s*       P PQ1#4a"8 P P P P P Pr
   c              3   (   K   | ]}|j         |fV  d S r   r_   )rk   r   s     r   ro   z6LatexContextDb.add_context_category.<locals>.<genexpr>  s*      GGq/3GGGGGGr
   macrosenvironmentsspecialsN)
rd   
ValueErrorrR   rP   rQ   insertindexappendrY   re   )	r%   categoryrt   ru   rv   prependinsert_beforeinsert_afteris	            r   add_context_categoryz#LatexContextDb.add_context_category  s   > t)))X$fX..0 0 0 IIWm\BIIIJJQNN R S S S  	0%%a2222 	0 222&,,];;%%a2222 	0t111&,,\::Q>*++%%a2222%%h/// >>f>>>>>  P P, P P PPPGGXGGGGG
 
xr
   c                     || _         dS )zj
        Set the macro spec to use when encountering a macro that is not in the
        database.
        N)rf   )r%   	macrospecs     r   set_unknown_macro_specz%LatexContextDb.set_unknown_macro_spec  s    
 #,r
   c                     || _         dS )z|
        Set the environment spec to use when encountering a LaTeX environment that
        is not in the database.
        N)rg   )r%   environmentspecs     r   set_unknown_environment_specz+LatexContextDb.set_unknown_environment_spec  s    
 )8%%%r
   c                     || _         dS )z
        Set the latex specials spec to use when encountering a LaTeX environment
        that is not in the database.
        N)rh   )r%   specialsspecs     r   set_unknown_specials_specz(LatexContextDb.set_unknown_specials_spec	  s    
 &2"""r
   c                 *    t          | j                  S )zt
        Return a list of valid category names that are registered in the current
        database context.
        )listrd   r2   s    r   
categorieszLatexContextDb.categories  s    
 D&'''r
   c                     | j         D ]2}|| j        |         d         v r| j        |         d         |         c S 3| j        S )a  
        Look up a macro specification by macro name.  The macro name is searched for
        in all categories one by one and the first match is returned.

        Returns a macro spec instance that matches the given `macroname`.  If
        the macro name was not found, we return the default macro specification
        set by :py:meth:`set_unknown_macro_spec()` or `None` if no such spec was
        set.
        rt   )rd   re   rf   )r%   r!   cats      r   get_macro_speczLatexContextDb.get_macro_spec  sV     % 	8 	8CDF3K111vc{8,Y7777 2&&r
   c                     | j         D ]2}|| j        |         d         v r| j        |         d         |         c S 3| j        S )a  
        Look up an environment specification by environment name.  The environment
        name is searched for in all categories one by one and the first match is
        returned.

        Returns the environment spec.  If the environment name was not found, we
        return the default environment specification set by
        :py:meth:`set_unknown_environment_spec()` or `None` if no such spec was
        set.
        ru   )rd   re   rg   )r%   r>   r   s      r   get_environment_specz#LatexContextDb.get_environment_spec'  sX     % 	D 	DC$&+n"===vc{>2?CCCC >,,r
   c                     | j         D ]2}|| j        |         d         v r| j        |         d         |         c S 3| j        S )a  
        Look up a "latex specials" specification by character sequence.  The
        sequence name is searched for in all categories one by one and the first
        match is returned.

        If you are parsing a chunk of LaTeX code, you should use
        :py:meth:`test_for_specials()` instead.  Unlike
        :py:meth:`test_for_specials()`, :py:meth:`get_specials_spec()` returns
        the first match regardless of matched length.  [Rationale: we only need
        to worry about matching the longest specials sequence when parsing LaTeX
        code.  Calling `get_specials_spec()` means one has already parsed the
        sequence and one is looking up additional specs on it.]

        Returns the specials spec.  If the latex specials was not found, we
        return the default latex specials specification set by
        :py:meth:`set_unknown_specials_spec()` or `None` if no such spec was
        set.
        rv   )rd   re   rh   )r%   rE   r   s      r   get_specials_specz LatexContextDb.get_specials_spec8  sV    & % 	? 	?CZ!888vc{:.~>>>> 9))r
   c                    d}d}| j         D ]{}| j        |         d                                         D ]S}t          |          |k    r>|                    ||          r(| j        |         d         |         }t          |          }T||S )a  
        Test the given position in the string for any LaTeX specials.  The lookup
        proceeds by searching for in all categories one by one and the first
        match is returned, except that the longest match accross all categories
        is returned.  For instance, a match of '``' in a later category will
        take precedence over a match of '`' in a earlier-searched category.

        Returns a specials spec instance, or `None` if no specials are detected
        at the position `pos`.
        r   Nrv   )rd   re   keysrP   
startswith)r%   r   posparsing_statebest_match_lenbest_match_sr   rE   s           r   test_for_specialsz LatexContextDb.test_for_specialsQ  s     % 	9 	9C"&&+j"9">">"@"@ 9 9~&&77ALLY\<]<]7#'6#;z#:>#JL%(%8%8N9
 r
   c              #      K   || j         }|D ]_}|| j         vr(t          d                    || j                             | j        |         d                                         D ]}|V  `dS )a  
        Yield the macro specs corresponding to all macros in the given categories.

        If `categories` is `None`, then the known macro specs from all
        categories are provided in one long iterable sequence.  Otherwise,
        `categories` should be a list or iterable of category names (e.g.,
        'latex-base') of macro specs to return.

        The macro specs from the different categories specified are concatenated
        into one long sequence which is yielded spec by spec.
        NzAInvalid latex macro spec db category: {!r} (Expected one of {!r})rt   rd   rw   rR   re   valuesr%   r   cspecs       r   iter_macro_specszLatexContextDb.iter_macro_specsg  s       +J 	 	A*** !d"(&D,>"?"?A A Aq	(+2244  



		 	r
   c              #      K   || j         }|D ]_}|| j         vr(t          d                    || j                             | j        |         d                                         D ]}|V  `dS )a   
        Yield the environment specs corresponding to all environments in the given
        categories.

        If `categories` is `None`, then the known environment specs from all
        categories are provided in one long iterable sequence.  Otherwise,
        `categories` should be a list or iterable of category names (e.g.,
        'latex-base') of environment specs to return.

        The environment specs from the different categories specified are
        concatenated into one long sequence which is yielded spec by spec.
        NGInvalid latex environment spec db category: {!r} (Expected one of {!r})ru   r   r   s       r   iter_environment_specsz%LatexContextDb.iter_environment_specs~  s       +J 	 	A*** ]VAt122   q	.188::  



	 	r
   c              #      K   || j         }|D ]_}|| j         vr(t          d                    || j                             | j        |         d                                         D ]}|V  `dS )a  
        Yield the specials specs corresponding to all environments in the given
        categories.

        If `categories` is `None`, then the known specials specs from all
        categories are provided in one long iterable sequence.  Otherwise,
        `categories` should be a list or iterable of category names (e.g.,
        'latex-base') of specials specs to return.

        The specials specs from the different categories specified are
        concatenated into one long sequence which is yielded spec by spec.
        Nr   rv   r   r   s       r   iter_specials_specsz"LatexContextDb.iter_specials_specs  s       +J 	 	A*** !j"(&D,>"?"?A A Aq	*-4466  



		 	r
   c                    t                      }| j        |_        | j        |_        | j        |_        | pd|v }| pd|v }| pd|v }| j        D ]}|r||vr	|r||v r|                    ||r%| j        |         d                                         ng |r%| j        |         d                                         ng |r%| j        |         d                                         ng            |S )a  
        Return a new :py:class:`LatexContextDb` instance where we only keep
        certain categories of macro and environment specifications.
        
        If `keep_categories` is set to a nonempty list, then the returned
        context will not contain any definitions that do not correspond to the
        specified categories.

        If `exclude_categories` is set to a nonempty list, then the returned
        context will not contain any definitions that correspond to the
        specified categories.

        It is explicitly fine to have category names in `keep_categories` and
        `exclude_categories` that don't exist in the present object
        (cf. :py:meth:`categories()`).

        The argument `keep_which`, if non-empty, specifies which definitions to
        keep.  It should be a subset of the list ['macros', 'environments',
        'specials'].
        
        The returned context will make a copy of the dictionaries that store the
        macro and environment specifications, but the specification classes (and
        corresponding argument parsers) might correspond to the same instances.
        I.e., the returned context is not a full deep copy.
        rt   ru   rv   rs   )rb   rf   rg   rh   rd   r   re   r   )	r%   keep_categoriesexclude_categories
keep_whichnew_contextkeep_macroskeep_environmentskeep_specialsr   s	            r   filter_contextzLatexContextDb.filter_context  s>   8 %&&)-)@&/3/L,,0,F)$n>J(> *NJn
.J&B*
*B% 	 	C 3o#=#=! c-?&?&? ,,9DLtvc{8,33555"EV^TVC[8??AAA\^=JRZ077999PR	 -     r
   r   )r5   r6   r7   r8   r    r   r   r   r   r   r   r   r   r   r   r   r   r   r9   r:   s   @r   rb   rb     s@       & &N* * * * * 57RRT%*$T=
 =
 =
 =
~, , ,8 8 82 2 2( ( (' ' ' - - -"* * *2   ,   .   4   2 .0B"$4 4 4 4 4 4 4 4r
   rb   )r8   sysversion_infomajorr	   strr#   _str_from_unicode_unicode_from_str
basestring_argparsersr   r   r   r   objectr   r<   rC   rV   r]   r`   rb   r   r
   r   <module>r      s  4	 	 


 AK## K<<33
+ + + + + + + + + + + +
%\ %\ %\ %\ %\ %\ %\ %\R<
 <
 <
 <
 <
f <
 <
 <
@(
 (
 (
 (
 (
6 (
 (
 (
\[L [L [L|=0 =0 =0@: : :.\ \ \ \ \V \ \ \ \ \r
   