
    e;                    6   d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
mZmZ ddlmZ dd	lZdd	lZdd	lZdd	lmc mZ dd
lmZmZmZmZ erddlmZ dddZddZ ej:                  d      ZddZddZ dddZ!d dZ"d Z# G d de      Z$ G d de      Z%d Z&y	)!z
Add table of contents support to Python-Markdown.

See the [documentation](https://Python-Markdown.github.io/extensions/toc)
for details.
    )annotations   )	Extension   )Treeprocessor)code_escapeparseBoolValueAMP_SUBSTITUTEHTML_PLACEHOLDER_REAtomicString)UnescapeTreeprocessorN)TYPE_CHECKINGAnyIterator
MutableSet)Markdownc                &   |s7t        j                  d|       } | j                  dd      j                  d      } t	        j
                  dd|       j                         j                         } t	        j
                  dj                  |      ||       S )z, Slugify a string, to make it URL friendly. NFKDasciiignorez[^\w\s-] z[{}\s]+)	unicodedata	normalizeencodedecoderesubstriplowerformat)value	separatorunicodes      9/usr/lib/python3/dist-packages/markdown/extensions/toc.pyslugifyr%   $   st    %%fe4Wh/66w?FF;E*00288:E66*##I.	5AA    c                    t        | |d      S )zP Slugify a string, to make it URL friendly while preserving Unicode characters. T)r#   )r%   )r!   r"   s     r$   slugify_unicoder(   .   s    5)T22r&   z^(.*)_([0-9]+)$c                    | |v s| sXt         j                  |       }|r2d|j                  d      t        |j                  d            dz   fz  } nd| dfz  } | |v rU| sX|j	                  |        | S )z@ Ensure id is unique in set of ids. Append '_1', '_2'... if not z%s_%dr   r   )
IDCOUNT_REmatchgroupintadd)ididsms      r$   uniquer2   6   sq    
)2R AGGAJAGGAJ(9::BB7"B )2 GGBKIr&   c                    g }| j                         D ]H  }t        |t              r%|j                  t	        j
                  |             8|j                  |       J dj                  |      j                         S )zGet title name.r   )itertext
isinstancer   appendhtmlunescapejoinr   )eltextcs      r$   get_namer=   B   sa     D[[] a&KKa()KKN	
 774=  r&   c                @    dfd}t        j                  ||       S )zN Extract raw HTML from stash, reduce to plain text and swap with placeholder. c                   	 j                   j                  t        | j                  d               }t        j                  dd|      }rt        j                  dd|      }|S # t        t
        f$ r | j                  d      cY S w xY w)z& Substitute raw html with plain text. r   r   z	(<[^>]+>)r   z(&[\#a-zA-Z0-9]+;))	htmlStashrawHtmlBlocksr-   r,   
IndexError	TypeErrorr   r   )r1   rawresmdstrip_entitiess      r$   	_html_subz#stashedHTML2text.<locals>._html_subP   s{    	,,,,S_=C ff\2s+&&.C8C
 I& 	771:	s   1A& & B	B	)r1   zre.Match[str]returnstr)r   r   )r;   rF   rG   rH   s    `` r$   stashedHTML2textrK   N   s    
 ""9d33r&   c                8    t               }|j                  |       S )z Unescape escaped text. )r   r8   )r;   r<   s     r$   r8   r8   _   s    A::dr&   c                (   g }t        |       r| j                  d      }g |d<   |d   g}|j                  |       g }| r| j                  d      }|d   }g |d<   ||d   k  rP|j                          d}t        |      D ]  }||d   k  r|dz  } n |r|d|  }|d|  }|j                  |       ||d   k(  r|r|d   d   n|j                  |       n6|d   j                  |       |j                  |       |j                  |       |}| r|S )aV  Given an unsorted list with errors and skips, return a nested one.

        [{'level': 1}, {'level': 2}]
        =>
        [{'level': 1, 'children': [{'level': 2, 'children': []}]}]

    A wrong list is also converted:

        [{'level': 2}, {'level': 1}]
        =>
        [{'level': 2, 'children': []}, {'level': 1, 'children': []}]
    r   childrenlevelr   N)lenpopr6   reversed)	toc_listordered_listlastlevelsparentstcurrent_levelto_popps	            r$   nest_toc_tokensr]   e   sJ    L
8}||AZw-D! QAgJMAjM vbz)

 !'* A$'
2!	
 #HfW-F%hw/G m, r
*,3Z("FF1I
 Z ''*t$m,DI L r&   c                  \     e Zd ZdZd
 fdZddZddZddZddZddZ	ddZ
dd	Z xZS )TocTreeprocessorz& Step through document and build TOC. c                   t         |   |       |d   | _        |d   | _        t	        |d         dz
  | _        |d   | _        |d   | _        |d   | _        |d   | _	        t        |d	         | _        |d
   | _        t        |d   d      | _        | j                  
|d   | _        |d   | _        |d   | _        t        |d   d      | _        t#        j$                  d      | _        t)        |d   t*              r@d|d   v r9|d   j-                  d      D cg c]  }t	        |       c}\  | _        | _        y d| _        t	        |d         | _        y c c}w )Nmarkertitle	baselevelr   r%   r"   	toc_classtitle_class
anchorlinkanchorlink_class	permalinkFpermalink_classpermalink_titlepermalink_leadingz[Hh][123456]	toc_depth-)super__init__ra   rb   r-   
base_levelr%   seprd   re   r	   use_anchorsrg   use_permalinksri   rj   rk   r   compile
header_rgxr5   rJ   splittoc_top
toc_bottom)selfrF   configx	__class__s       r$   ro   zTocTreeprocessor.__init__   sd   !(+ /
f[12Q6i(+&, &} 5!/|0D!E%+,>%?,VK-@%H&"("5D$*+<$=$*+<$=.<VDW=XZ_.`**^4f[)3/C6+;N4N=CK=P=V=VWZ=[,\SV,\)DL$/DL!&"56DO -]s   Ec              #     K   |D ]V  }| j                   j                  |j                        r)|j                  dvs8||f | j                  |      E d{    X y7 w)z? Iterator wrapper to get allowed parent and child all at once. )precodeN)ru   r+   tag
iterparent)ry   nodechilds      r$   r   zTocTreeprocessor.iterparent   sY       	2E??((3		8XEk!??5111	2 2s   +A!A!A!AA!c                n   | j                  |      D ]  \  }}dj                  |j                               j                         }|s6|j                  sC|j                  j                         | j
                  k(  skt        |      dk(  szt        t        |            D ]  }||   |k(  s|||<      y)z Replace marker with elem. r   r   N)r   r9   r4   r   r;   ra   rQ   range)ry   rootelemr\   r<   r;   is          r$   replace_markerzTocTreeprocessor.replace_marker   s    ood+ 	FQ771::<(..0D vv!&&,,.DKK7CFaKs1v Atqy#!	r&   c                p    t        |j                  d         | j                  z   }|dkD  rd}d|z  |_        y)z. Adjust header level according to base level. rP      zh%dN)r-   r   rp   )ry   r   rO   s      r$   	set_levelzTocTreeprocessor.set_level   s4    DHHRL!DOO319E5=r&   c                \   t        j                  d      }|j                  |_        d|z   |j                  d<   | j                  |j                  d<   d|_        |D ]  }|j                  |        t        |      r |j                  |d          t        |      r |j                  |       y )Na#hrefclassr   r   )etreeElementr;   attribrg   r6   rQ   remove)ry   r<   elem_idanchorr   s        r$   
add_anchorzTocTreeprocessor.add_anchor   s    s#ff #gf!%!6!6g 	 DMM$	 !fHHQqTN !f	r&   c                   t        j                  d      }| j                  du r	dt        z  n| j                  |_        d|z   |j
                  d<   | j                  |j
                  d<   | j                  r| j                  |j
                  d<   | j                  r+|j                  |_	        d|_        |j                  d	|       y |j                  |       y )
Nr   Tz%spara;r   r   r   rb   r   r   )r   r   rs   r
   r;   r   ri   rj   rk   tailinsertr6   )ry   r<   r   rh   s       r$   add_permalinkzTocTreeprocessor.add_permalink   s    MM#&	!00D8 $n4#22 	 $'=	 $($8$8	!(,(<(<IW%!!VVINAFHHQ	"HHYr&   c                   t        j                  d      }| j                  |j                  d<   | j                  rLt        j
                  |d      }| j                  r| j                  |j                  d<   | j                  |_        dfd ||       d| j                  j                  v r(| j                  j                  d   j                  |       |S )z' Return a string div given a toc list. divr   spanc                0   t        j                  |d      }| D ]y  }t        j                  |d      }t        j                  |d      }|j                  dd      |_        d|j                  dd      z   |j                  d<   |d	   sn |d	   |       { |S )
Nullir   namer   r   r/   r   rN   )r   
SubElementgetr;   r   )rT   parentr   itemr   linkbuild_etree_uls         r$   r   z6TocTreeprocessor.build_toc_div.<locals>.build_etree_ul  s    !!&$/B  9%%b$/''C0 HHVR0	&)DHHT2,>&>F#
#"4
#3R89 Ir&   prettify)rT   listr   etree.ElementrI   r   )r   r   rd   r   rb   r   re   r;   rF   treeprocessorsrun)ry   rT   r   headerr   s       @r$   build_toc_divzTocTreeprocessor.build_toc_div  s    mmE""nn

7 ::%%c62F)-)9)9g&**FK
	 	x%///GG"":.2237
r&   c                    t               }|j                         D ]/  }d|j                  v s|j                  |j                  d          1 g }|j                         D ]  }t	        |j
                  t              s| j                  j                  |j
                        sE| j                  |       t        |      }d|j                  vrRt        t        || j                              }t        | j                  || j                         |      |j                  d<   t#        |j
                  d         | j$                  k\  rt#        |j
                  d         | j&                  k  rz|j)                  t#        |j
                  d         |j                  d   t        t        t+        |j                  j-                  d|            | j                  d            d       d|j                  v r|j                  d= | j.                  r| j1                  ||j                  d          | j2                  dvs| j5                  ||j                  d           t7        |      }| j9                  |      }| j:                  r| j=                  ||       | j                  j?                  |      }| j                  j@                  D ]  }	|	jC                  |      } || j                  _"        || j                  _#        y )Nr/   rP   zdata-toc-labelF)rG   )rO   r/   r   )FN)$setiterr   r.   r5   r   rJ   ru   r+   r   r=   r8   rK   rF   r2   r%   rq   r-   rw   rx   r6   r   r   rr   r   rs   r   r]   r   ra   r   
serializerpostprocessorsr   
toc_tokenstoc)
ry   docused_idsr:   r   r;   	innertextr   r   pps
             r$   r   zTocTreeprocessor.run$  sM   5((* 	.Bryy RYYt_-	. 
((* 	<B"&&#&4??+@+@+Hr"| ryy( ()9$)H II&,T\\)TXX-NPX&YBIIdOrvvbz?dll2s266":$//7Y%%!$RVVBZ iio ()9'		6F(MN GGE* !'  $ryy0		"23##OOB		$8&&m;&&r299T?;7	<: %Z0
  ,;;S) gg  %''(( 	B&&+C	'r&   )rF   r   rz   zdict[str, Any])r   r   rI   z-Iterator[tuple[etree.Element, etree.Element]])r   r   r   r   rI   None)r   r   rI   r   )r<   r   r   rJ   rI   r   )rT   r   rI   r   )r   r   rI   r   )__name__
__module____qualname____doc__ro   r   r   r   r   r   r   r   __classcell__r|   s   @r$   r_   r_      s.    072	2*!
  >/r&   r_   c                  0     e Zd ZeZ fdZd ZddZ xZS )TocExtensionc                    ddgddgddgddgd	d
gddgddgddgddgd	dgddgt         dgddgddgd| _        	 t        |   di | y )Nz[TOC]zeText to find and replace with Table of Contents. Set to an empty string to disable. Default: `[TOC]`.r   z;Title to insert into TOC `<div>`. Default: an empty string.toctitlez2CSS class used for the title. Default: `toctitle`.r   z4CSS class(es) used for the link. Default: `toclink`.Fz7True if header should be a self link. Default: `False`.toclinkz5CSS class(es) used for the link. Defaults: `toclink`.r   zPTrue or link text if a Sphinx-style permalink should be added. Default: `False`.
headerlinkz7CSS class(es) used for the link. Default: `headerlink`.zPermanent linkz<Title attribute of the permalink. Default: `Permanent link`.z\True if permalinks should be placed at start of the header, rather than end. Default: False.1z%Base level for headers. Default: `1`.zFFunction to generate anchors based on header text. Default: `slugify`.rm   zWord separator. Default: `-`.r   a'  Define the range of section levels to include in the Table of Contents. A single integer (b) defines the bottom section level (<h1>..<hb>) only. A string consisting of two digits separated by a hyphen in between (`2-5`) defines the top (t) and the bottom (b) (<ht>..<hb>). Default: `6` (bottom).)ra   rb   re   rd   rf   rg   rh   ri   rj   rk   rc   r%   r"   rl    )r%   rz   rn   ro   )ry   kwargsr|   s     r$   ro   zTocExtension.__init__Z  s     $ Q P M P R! e W  !"`  n" FGa >?)O.
^ 	/"6"r&   c                    |j                  |        || _        | j                          | j                  || j	                               }|j
                  j                  |dd       y)z% Add TOC tree processor to Markdown. r      N)registerExtensionrF   resetTreeProcessorClass
getConfigsr   register)ry   rF   tocexts      r$   extendMarkdownzTocExtension.extendMarkdown  sQ    
T"

((T__->?
""65!4r&   c                H    d| j                   _        g | j                   _        y )Nr   )rF   r   r   )ry   s    r$   r   zTocExtension.reset  s    r&   )rI   r   )	r   r   r   r_   r   ro   r   r   r   r   s   @r$   r   r   V  s    )2#h5 r&   r   c                     t        di | S )Nr   )r   )r   s    r$   makeExtensionr     s    !&!!r&   )F)r!   rJ   r"   rJ   r#   boolrI   rJ   )r!   rJ   r"   rJ   rI   rJ   )r/   rJ   r0   zMutableSet[str]rI   rJ   )r:   r   rI   rJ   )T)r;   rJ   rF   r   rG   r   rI   rJ   )r;   rJ   rI   rJ   )'r   
__future__r   r   r   r   r   utilr   r	   r
   r   r   r   r   r7   r   xml.etree.ElementTreer   ElementTreetypingr   r   r   r   markdownr   r%   r(   rt   r*   r2   r=   rK   r8   r]   r_   r   r   r   r&   r$   <module>r      s    #  * a a 2 	   % % ; ;!B3
 RZZ*+
		!4">Bm} m`B 9 B J"r&   