
    /VhG                       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mZ dd
lZdd
lZdd
lZddlm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jB                  d      Z"d%dZ# e
d      d&d       Z$ e
d      d'd(d       Z%d)dZ&d)dZ'd)dZ(d*dZ)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)parseBoolValueAMP_SUBSTITUTE
deprecatedHTML_PLACEHOLDER_REAtomicString)UnescapeTreeprocessor)RE_AMPN)deepcopy)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      G/home/dcms/DCMS/lib/python3.12/site-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*   0   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&   uniquer4   8   sq    
)2R AGGAJAGGAJ(9::BB7"B )2 GGBKIr(   z0Use `render_inner_html` and `striptags` instead.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?   D   sa     D[[] a&KKa()KKN	
 774=  r(   zIUse `run_postprocessors`, `render_inner_html` and/or `striptags` instead.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   )r3   rawresmdstrip_entitiess      r&   	_html_subz#stashedHTML2text.<locals>._html_subT   s{    	,,,,S_=C ff\2s+&&.C8C
 I& 	771:	s   1A& & B	B	)r3   zre.Match[str]returnstr)r   r   )r=   rH   rI   rJ   s    `` r&   stashedHTML2textrM   Q   s    
 ""9d33r(   c                8    t               }|j                  |       S )z+ Unescape Markdown backslash escaped text. )r   r:   )r=   r>   s     r&   r:   r:   c   s    A::dr(   c                   | j                  d      x}dk7  rT| j                  d|      x}dk7  r=| d|  | |dz   d  } | j                  d      x}dk7  r| j                  d|      x}dk7  r=| j                  d      x}dk7  rT| j                  d|      x}dk7  r=| d|  | |dz   d  } | j                  d      x}dk7  r| j                  d|      x}dk7  r=d	j                  | j                               } | S )
zL Strip HTML tags and return plain text. Note: HTML entities are unaffected. z<!--z-->N   <>r    )findr;   split)r=   startends      r&   
strip_tagsrY   i   s    IIf%%5"
,5%9P2P#UW1Wv,S1WX/0 IIf%%5"
,5%9P2P#UW1W IIcN"5r
)diiU6K/KsPR.Rv,S1WX/0 IIcN"5r
)diiU6K/KsPR.R 88DJJL!DKr(   c                    d| v rt        j                  d|       } d| v r| j                  dd      } d| v r| j                  dd      } | S )z Escape character data. &z&amp;rR   z&lt;rS   z&gt;)r   r   replace)r=   s    r&   escape_cdatar]   w   sL    
d{zz'4(
d{||C(
d{||C(Kr(   c                f    |j                   D ]  }|j                  |       }  | j                         S )z4 Run postprocessors from Markdown instance on text. )postprocessorsrunr    )r=   rH   pps      r&   run_postprocessorsrb      s0     vvd|::<r(   c                    t        |j                  |             }|j                  d      dz   }|j                  d      }||| j	                         }t        ||      S )z< Fully render inner html of an `etree` element as a string. rS   r   rR   )r:   
serializerindexrindexr    rb   )r<   rH   r=   rW   rX   s        r&   render_inner_htmlrg      sZ     BMM"%&D JJsOaE
++c
Cc?  "DdB''r(   c                   t        | j                  d      d      | S t        |       } | j                  d      D ]  }d}t	        |      D ]v  }|j
                  dk(  rG|j                  dd      j                  d      r&|j                  xs d | }|j                  |       Y|s\|j                  xs d | |_        d}x |s|j                  xs d | |_
         | S )zL Remove footnote references from a copy of the element, if any are present. supNz	.//sup/..r   r1   fnref)nextiterr   findallreversedtagget
startswithtailremover=   )rootparent
carry_textchilds       r&   remove_fnrefsrx      s     DIIed#+D>D,,{+ =
f% 	 EyyE!eiib&9&D&DW&M %

 0b1*>
e$ %

 0b1*>

	  #[[.B/
|<FK= Kr(   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levelrP   r   N)lenpopr8   rn   )	toc_listordered_listlastlevelsparentstcurrent_levelto_popps	            r&   nest_toc_tokensr      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__r   r   r/   
base_levelr'   sepr   r   r   use_anchorsr   use_permalinksr   r   r   r   compile
header_rgxr7   rL   rV   toc_top
toc_bottom)selfrH   configx	__class__s       r&   r   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)r   r-   ro   
iterparent)r   noderw   s      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   r;   r6   r    r=   r   r|   range)r   rt   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/   ro   r   )r   r   r{   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=   attribr   r8   r|   rs   )r   r>   elem_idanchorr   s        r&   
add_anchorzTocTreeprocessor.add_anchor2  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   r   r   r   )r   r   r   r	   r=   r   r   r   r   rr   insertr8   )r   r>   r   r   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   r1   r   rz   )r   
SubElementrp   r=   r   )r~   ru   r   itemr   linkbuild_etree_uls         r&   r   z6TocTreeprocessor.build_toc_div.<locals>.build_etree_ulZ  s    !!&$/B  9%%b$/''C0 HHVR0	&)DHHT2,>&>F#
#"4
#3R89 Ir(   prettify)r~   listru   etree.ElementrK   r   )r   r   r   r   r   r   r   r=   rH   treeprocessorsr`   )r   r~   r   headerr   s       @r&   build_toc_divzTocTreeprocessor.build_toc_divN  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        t        |      | j                        }t        |      }d|j                  vrFt        | j                  t!        j"                  |      | j$                        |      |j                  d<   d}d|j                  v rMt'        t#        |j                  d         | j                        }t)        t        |            }|j                  d= t+        |j
                  d         | j,                  k\  rht+        |j
                  d         | j.                  k  rC|j1                  t+        |j
                  d         t#        |j                  d         |||d       | j2                  r| j5                  ||j                  d          | j6                  dvs| j9                  ||j                  d           t;        |      }| j=                  |      }| j>                  r| jA                  ||       | j                  jC                  |      }	| j                  jD                  D ]  }
|
jG                  |	      }	 || j                  _$        |	| j                  _%        y )Nr1   r   data-toc-labelrP   )r{   r1   r   r9   r   )FN)&setrl   r   r0   r7   ro   rL   r   r-   r   rg   rx   rH   rY   r4   r'   r9   r:   r   rb   r]   r/   r   r   r8   r   r   r   r   r   r   r   r   rd   r_   r`   
toc_tokenstoc)r   docused_idsr<   r   	innerhtmlr   data_toc_labelr   r   ra   s              r&   r`   zTocTreeprocessor.runm  sj   5((* 	.Bryy RYYt_-	. 
((* 	<B"&&#&4??+@+@+Hr"-mB.?I	!), ryy(&,T\\$--:Mtxx-XZb&cBIIdO!##ryy0%7K[A\8]_c_f_f%gN'
>(BCD		"23rvvbz?dll2s266":$//7Y%%!$RVVBZ&ryy7 $ )*8'  ##OOB		$8&&m;&&r299T?;=	<@ %Z0
  ,;;S) gg  %''(( 	B&&+C	'r(   )rH   r   r   zdict[str, Any])r   r   rK   z-Iterator[tuple[etree.Element, etree.Element]])rt   r   r   r   rK   None)r   r   rK   r   )r>   r   r   rL   rK   r   )r~   r   rK   r   )r   r   rK   r   )__name__
__module____qualname____doc__r   r   r   r   r   r   r   r`   __classcell__r   s   @r&   r   r      s.    072	2*!
  >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`.r   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).)r   r   r   r   r   r   r   r   r   r   r   r'   r$   r    )r'   r   r   r   )r   kwargsr   s     r&   r   zTocExtension.__init__  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)registerExtensionrH   resetTreeProcessorClass
getConfigsr   register)r   rH   tocexts      r&   extendMarkdownzTocExtension.extendMarkdown  sQ    
T"

((T__->?
""65!4r(   c                H    d| j                   _        g | j                   _        y )Nr   )rH   r   r   )r   s    r&   r   zTocExtension.reset  s    r(   )rK   r   )	r   r   r   r   r   r   r   r   r   r   s   @r&   r   r     s    )2#h5 r(   r   c                     t        di | S )Nr   )r   )r   s    r&   makeExtensionr     s    !&!!r(   )F)r#   rL   r$   rL   r%   boolrK   rL   )r#   rL   r$   rL   rK   rL   )r1   rL   r2   zMutableSet[str]rK   rL   )r<   r   rK   rL   )T)r=   rL   rH   r   rI   r   rK   rL   )r=   rL   rK   rL   )r=   rL   rH   r   rK   rL   )r<   r   rH   r   rK   rL   )rt   r   rK   r   )0r   
__future__r   r   r   r   r   utilr   r	   r
   r   r   r   serializersr   r   r9   r   copyr   xml.etree.ElementTreer   ElementTreetypingr   r   r   r   markdownr   r'   r*   r   r,   r4   r?   rM   r:   rY   r]   rb   rg   rx   r   r   r   r   r   r(   r&   <module>r      s    #  * ` ` 2   	    % % ; ;!B3
 RZZ*+
	 >?	! @	! WX4 Y4"	
(.>Bp} pfB 9 B J"r(   