
    /VhD                        d Z ddlmZ ddlZddlmc mZ ddlmZm	Z	 ddl
mZ ddl
mZ erddlmZ dd	Zdd
Z G d dej"                        Z G d de      Z G d de      Z G d de      Zy)z
Tree processors manipulate the tree created by block processors. They can even create an entirely
new `ElementTree` object. This is an excellent place for creating summaries, adding collected
references, or last minute adjustments.

    )annotationsN)TYPE_CHECKINGAny   )util)inlinepatterns)Markdownc                    t        j                         }|j                  t        |       dd       |j                  t	        |       dd       |j                  t        |       dd       |S )z3 Build the default  `treeprocessors` for Markdown. inline   prettify
   unescaper   )r   RegistryregisterInlineProcessorPrettifyTreeprocessorUnescapeTreeprocessor)mdkwargstreeprocessorss      G/home/dcms/DCMS/lib/python3.12/site-packages/markdown/treeprocessors.pybuild_treeprocessorsr   '   sZ    ]]_NOB/2>1"5z2F1"5z1E    c                X    t        | t        j                        st        | t              S y)z_ Return `True` if object is a string but not an  [`AtomicString`][markdown.util.AtomicString]. F)
isinstancer   AtomicStringstr)ss    r   isStringr    0   s"    a**+!S!!r   c                      e Zd ZdZddZy)Treeprocessora  
    `Treeprocessor`s are run on the `ElementTree` object before serialization.

    Each `Treeprocessor` implements a `run` method that takes a pointer to an
    `Element` and modifies it as necessary.

    `Treeprocessors` must extend `markdown.Treeprocessor`.

    c                     y)a  
        Subclasses of `Treeprocessor` should implement a `run` method, which
        takes a root `Element`. This method can return another `Element`
        object, and the existing root `Element` will be replaced, or it can
        modify the current tree and return `None`.
        N )selfroots     r   runzTreeprocessor.runA   s     	r   N)r&   etree.Elementreturnetree.Element | None)__name__
__module____qualname____doc__r'   r$   r   r   r"   r"   7   s    r   r"   c                      e Zd ZdZddZddZddZddZdddZdddZ		 d	 	 	 	 	 	 	 ddZ
	 d	 	 	 	 	 	 	 	 	 dd	Zdd
ZdddZy)r   zL
    A `Treeprocessor` that traverses a tree, applying inline patterns.
    c                &   t         j                  | _        t         j                  | _        dt        | j                        z   t        | j                        z   | _        t         j                  | _        || _	        |j                  | _
        g | _        y )N   )r   INLINE_PLACEHOLDER_PREFIX$_InlineProcessor__placeholder_prefixETX$_InlineProcessor__placeholder_suffixlen$_InlineProcessor__placeholder_lengthINLINE_PLACEHOLDER_RE _InlineProcessor__placeholder_rer   inlinePatterns	ancestors)r%   r   s     r   __init__zInlineProcessor.__init__P   sr    $($B$B!$(HH!$%D,E,E(F$F(+D,E,E(F%G! $ : : //$&r   c                `    dt        | j                        z  }t        j                  |z  }||fS )z Generate a placeholder z%04d)r6   stashed_nodesr   INLINE_PLACEHOLDER)r%   typeidhashs       r   __makePlaceholderz!InlineProcessor.__makePlaceholderZ   s0    c$,,--&&+Rxr   c                    | j                   j                  ||      }|r!|j                  d      |j                         fS d|dz   fS )a  
        Extract id from data string, start from index.

        Arguments:
            data: String.
            index: Index, from which we start search.

        Returns:
            Placeholder id and string index, after the found placeholder.

        r   N)r9   searchgroupend)r%   dataindexms       r   __findPlaceholderz!InlineProcessor.__findPlaceholder`   sF     !!((u5771:quuw&&?"r   c                L    | j                  |      \  }}|| j                  |<   |S )z Add node to stash. )!_InlineProcessor__makePlaceholderr>   )r%   noder@   placeholderrA   s        r   __stashNodezInlineProcessor.__stashNoder   s,    006R!%2r   c                    t        |t        j                        sNd}t        | j                        }||k  r2| j                  | j                  |   |||      \  }}}|s|dz  }||k  r2|S )a  
        Process string with inline patterns and replace it with placeholders.

        Arguments:
            data: A line of Markdown text.
            patternIndex: The index of the `inlinePattern` to start with.

        Returns:
            String with placeholders.

        r   r   )r   r   r   r6   r:   _InlineProcessor__applyPattern)r%   rH   patternIndex
startIndexcountmatcheds         r   __handleInlinezInlineProcessor.__handleInlinex   s|     $ 1 12J++,E&,0,?,?''5t\:-)gz  A%L & r   c                    |r|j                   }d|_         n|j                  }d|_        | j                  |||      }|s"||urt        |      j	                  |      dz   }nd}|j                          |D ]  }|j                  ||d           y)a'  
        Process placeholders in `Element.text` or `Element.tail`
        of Elements popped from `self.stashed_nodes`.

        Arguments:
            node: Parent node.
            subnode: Processing node.
            isText: Boolean variable, True - it's text, False - it's a tail.

        Nr   r   )texttail%_InlineProcessor__processPlaceholderslistrI   reverseinsert)r%   rN   subnodeisTextrY   childResultposnewChilds           r   __processElementTextz$InlineProcessor.__processElementText   s     <<DGL<<DGL00wG$g-t*""7+a/CC# 	*HKKXa[)	*r   c                l   dfd}g d}|r|j                  | j                  |      }|dk7  r=| j                  ||      \  }}|| j                  v r| j                  j	                  |      }	|dkD  r||| }
 ||
       t        |	t              s|	gt        |	      z   D ]u  }|j                  r-|j                  j                         r| j                  |	|d       |j                  sI|j                  j                         sd| j                  ||       w n ||	       |}|}j                  |	| j                  dd f       nd|t        | j                        z   } ||||        |}n>||d }
t        |t        j                         rt        j                   |
      }
 ||
       d}|rS )a  
        Process string with placeholders and generate `ElementTree` tree.

        Arguments:
            data: String with placeholders instead of `ElementTree` elements.
            parent: Element, which contains processing inline data.
            isText: Boolean variable, True - it's text, False - it's a tail.

        Returns:
            List with `ElementTree` elements with applied inline patterns.

        c                2   | rr<d   d   j                   rd   d   xj                   | z  c_         y | d   d   _         y s*j                   rxj                   | z  c_         y | _         y j                  rxj                  | z  c_        y | _        y y )Nr   )rZ   rY   )rY   r`   parentresults    r   linkTextz7InlineProcessor.__processPlaceholders.<locals>.linkText   s    bz!}))r
1**d2*-1r
1*{{t+&*{{t+&* r   r   rg   FN )rY   
str | Noner)   None)findr3   !_InlineProcessor__findPlaceholderr>   getr   r   r\   rZ   strip$_InlineProcessor__processElementTextrY   appendr;   r6   r   r   )r%   rH   rh   r`   rj   strartIndexrI   rA   
phEndIndexrN   rY   childrG   ri   s     ``         @r   __processPlaceholdersz%InlineProcessor.__processPlaceholders   s   $	+" IId77EE{!%!7!7e!DJ+++--11"5Dqy#K6 %dC0&*Vd4j%8 LE$zz#(::#3#3#5$($=$=(,eU%&  %zz#(::#3#3#5$($=$=eU$KL !&0 ",KMM4):";<  #d&?&?"@@CT+c23"%KKL)dD$5$56,,T2DQ T r   c                   t        |t        j                        }|j                  D ]%  }|j	                         | j
                  v s |ddfc S  |rZd}|j                         j                  ||      D ]4  }|j                  ||      \  }}	}
|	|
||j                  d      z  }d}4 n) n'|j                         j                  ||d       }|d| }|s|ddfS |s3|j                  |      }|j                  d      }	|j                  d      }
|d
fS t        |t              st        |j                  t        j                        s|gt!        |      z   D ]  }t#        |      r|j                  rq| j
                  j%                  |j&                  j	                                | j)                  |j                  |dz         |_        | j
                  j+                          |j,                  s| j)                  |j,                  |      |_         | j/                  ||j1                               }|rdj3                  |d	 ||
d       ddfS dj3                  |j5                  d      ||j7                         d         ddfS )	a  
        Check if the line fits the pattern, create the necessary
        elements, add it to `stashed_nodes`.

        Arguments:
            data: The text to be processed.
            pattern: The pattern to be checked.
            patternIndex: Index of current pattern.
            startIndex: String index, from which we start searching.

        Returns:
            String with placeholders instead of `ElementTree` elements.

        Fr   NTr   z{}{}{}z{}{}{}{}rg   )r   r   r   ANCESTOR_EXCLUDESlowerr;   getCompiledRegExpfinditerhandleMatchrG   matchstartr   rY   r   r   r\   r    rs   tag_InlineProcessor__handleInlinepoprZ   _InlineProcessor__stashNoder@   formatrF   groups)r%   patternrH   rS   rT   	new_styleexcluder~   rN   r   rG   leftDatarv   rO   s                 r   __applyPatternzInlineProcessor.__applyPattern   sw   * w(F(FG	00 	&G}}$..0UA~%	& E !224==dJO #*#6#6ud#C eS=CK%))A,.J E --/55d:;6GHEKZ(H>!&&u-DKKNE))A,C<s?"$$dii):):;"Vd4j0 E#D> :: NN11%))//2CD)-)<)< %

L1,<*EJ !NN..0 ::)-)<)< %

L*EJ &&tW\\^<??4<#.ST
<=A1E E $$X%*[[^%0%,,.2DFGKQO Or   c                    g }|I|)|j                  |j                  j                                | j                  j	                  |      }|I|j                          |j                  |       y)zBuild the ancestor list.N)rs   r   rz   
parent_maprp   r]   extend)r%   rh   parentsr;   s       r   __build_ancestorsz!InlineProcessor.__build_ancestorsM  sd    	 !  !1!1!34__((0F   	y!r   Nc                f   i | _         |g n|dd }|j                         D ci c]  }|D ]  }||  c}}| _        ||fg}|re|j                         \  }}|| _        | j                  || j                         g }	|D ]  }
|
j                  rt        |
j                  t        j                        s| j                  j                  |
j                  j                                |
j                  }d|
_        | j                  | j                  |      |
      }|D ]  }|
| j                  |d   <    ||z  }|	j                  |
|f       | j                  j                          |
j                  r| j                  |
j                        }t!        j"                  d      }d|
_        | j                  ||d      }|j                  r|j                  |
_        t%        |      j'                  |
      dz   }|j)                          |D ])  }|| j                  |d   <   |j+                  ||d          + t-        |
      s|| j                  |
<   |j                  |
| j                  dd f        |	D ]/  \  }}t/        |      D ]  \  }}|d   }|j+                  ||        1 |re|S c c}}w )a  Apply inline patterns to a parsed Markdown tree.

        Iterate over `Element`, find elements with inline tag, apply inline
        patterns and append newly created Elements to tree.  To avoid further
        processing of string with inline patterns, instead of normal string,
        use subclass [`AtomicString`][markdown.util.AtomicString]:

            node.text = markdown.util.AtomicString("This will not be processed.")

        Arguments:
            tree: `Element` object, representing Markdown tree.
            ancestors: List of parent tag names that precede the tree node (if needed).

        Returns:
            An element tree object with applied inline patterns.

        Nr   dFr   )r>   iterr   r   r;   !_InlineProcessor__build_ancestorsrY   r   r   r   rs   r   rz   r[   r   rZ   etreeElementr\   rI   r]   r^   r6   	enumerate)r%   treer;   tree_parentspcstackcurrElementr   insertQueuerv   rY   lstitemrZ   dumby
tailResultrb   rc   elementiobjs                         r   r'   zInlineProcessor.runW  s   $ >@ '.rIaL)-@Aa@1a4@1@%&#(99; K$DN"";?K$ =::jJJ 1 1' NN))%))//*;< ::D!%EJ44++D15C !$ 938Q09SLE&&s|4NN&&(::..uzz:D!MM#.E!%EJ!%!;!;D%!OJzz%*ZZ
{+11%81<C&&($. =7B4#**3<= u:-8DOOE*LL%):!;<;=> !, 0'n 0FAs"1vHNN1h/00M T [ As   J-)r   r	   )r@   r   r)   ztuple[str, str])rH   r   rI   intr)   ztuple[str | None, int])rN   zetree.Element | strr@   r   r)   r   )r   )rH   r   rS   r   r)   r   )T)rN   r(   r_   r(   r`   boolr)   rm   )rH   rl   rh   r(   r`   r   r)   z%list[tuple[etree.Element, list[str]]])
r   zinlinepatterns.PatternrH   r   rS   r   rT   r   r)   ztuple[str, bool, int])rh   r*   r   z	list[str]r)   rm   N)r   r(   r;   zlist[str] | Noner)   r(   )r+   r,   r-   r.   r<   rM   ro   r   r   rr   r[   rR   r   r'   r$   r   r   r   r   K   s    '#$.*B 	OO O 	O
 
/Ol NO'NO NO 	NO
 NO 
NO`"Er   r   c                       e Zd ZdZddZddZy)r   z' Add line breaks to the html document. c                   d}| j                   j                  |j                        r|j                  dvr|j                  r|j                  j	                         s:t        |      r/| j                   j                  |d   j                        r||_        |D ]9  }| j                   j                  |j                        s)| j                  |       ; |j                  r|j                  j	                         s||_        yy)z8 Recursively add line breaks to `ElementTree` children. 
)codeprer   N)r   is_block_levelr   rY   rq   r6   _prettifyETreerZ   )r%   elemr   es       r   r   z$PrettifyTreeprocessor._prettifyETree  s     77!!$((+0OIITYY__%6D	dgg&<&<T!W[[&I	 +77))!%%0''*+ yy		 1DI !2r   c                   | j                  |       |j                  d      }|D ]D  }|j                  r|j                  j                         sd|_        1d|j                  z  |_        F |j                  d      }|D ]t  }t	        |      s|d   j
                  dk(  s"|d   }t	        |      r3|j                  @t        j                  |j                  j                         dz         |_        v y)z7 Add line breaks to `Element` object and its children. brr   z
%sr   r   r   N)
r   r   rZ   rq   r6   r   rY   r   r   rstrip)r%   r&   brsr   presr   r   s          r   r'   zPrettifyTreeprocessor.run  s     	D! iio 	+B77"''--/ 277*		+ yy 	MC3xCFJJ&01v4yTYY%: $ 1 1$))2B2B2Dt2K LDI	Mr   N)r   r(   r)   rm   r&   r(   r)   rm   )r+   r,   r-   r.   r   r'   r$   r   r   r   r     s    1Mr   r   c                      e Zd ZdZ ej
                  dj                  ej                  ej                              Z
ddZddZd	dZy)
r   z Restore escaped chars z	{}(\d+){}c                H    t        t        |j                  d                  S )Nr   )chrr   rF   )r%   rJ   s     r   	_unescapezUnescapeTreeprocessor._unescape  s    3qwwqz?##r   c                N    | j                   j                  | j                  |      S r   )REsubr   )r%   rY   s     r   r   zUnescapeTreeprocessor.unescape  s    ww{{4>>400r   c                n   |j                         D ]  }|j                  r/|j                  dk(  s | j                  |j                        |_        |j                  r | j                  |j                        |_        |j                         D ]&  \  }}|j                  || j                  |             (  y)z/ Loop over all elements and unescape all text. r   N)r   rY   r   r   rZ   itemsset)r%   r&   r   keyvalues        r   r'   zUnescapeTreeprocessor.run  s    IIK 		4DyyV!3 MM$))4	yy MM$))4	"jjl 4
UdmmE234		4r   N)rJ   zre.Match[str]r)   r   )rY   r   r)   r   r   )r+   r,   r-   r.   recompiler   r   STXr4   r   r   r   r'   r$   r   r   r   r     s9    !	L''$((;	<B$14r   r   )r   r	   r   r   r)   zutil.Registry[Treeprocessor])r   objectr)   r   )r.   
__future__r   r   xml.etree.ElementTreer   ElementTreetypingr   r   rk   r   r   markdownr	   r   r    	Processorr"   r   r   r   r$   r   r   <module>r      sk   ( # 	 % % %  !DNN (Qm Qh
$MM $MN4M 4r   