
    -Be7                         d 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	Zd
 Z ej(                  d      Zd Zd ZddZd Zd Z G d de      Z G d de      Zd Zy)an  
Table of Contents Extension for Python-Markdown
===============================================

See <https://Python-Markdown.github.io/extensions/toc>
for documentation.

Oringinal code Copyright 2008 [Jack Miller](https://codezen.org/)

All changes Copyright 2008-2014 The Python Markdown Project

License: [BSD](https://opensource.org/licenses/bsd-license.php)

   )	Extension   )Treeprocessor)code_escapeparseBoolValueAMP_SUBSTITUTEHTML_PLACEHOLDER_REAtomicString)UnescapeTreeprocessor    Nc                 &   |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      7lib/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"   $   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   uniquer,   ,   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_namer7   8   sa     D[[] a&KKa()KKN	
 774=  r    c                 >    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   )r+   rawresmdstrip_entitiess      r   	_html_subz#stashedHTML2text.<locals>._html_subF   s{    	,,,,S_=C ff\2s+&&.C8C
 I& 	771:	s   1A& & B	B	)r	   r   )r5   r@   rA   rB   s    `` r   stashedHTML2textrC   D   s    
 ""9d33r    c                 8    t               }|j                  |       S )z Unescape escaped text. )r   r2   )r5   r6   s     r   r2   r2   U   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 )a<  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popr0   reversed)	toc_listordered_listlastlevelsparentstcurrent_levelto_popps	            r   nest_toc_tokensrU   [   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                   H     e Zd Z fdZd Zd Zd Zd Zd Zd Z	d Z
 xZS )	TocTreeprocessorc                    t         |   |       |d   | _        |d   | _        t	        |d         dz
  | _        |d   | _        |d   | _        |d   | _        t        |d         | _
        |d	   | _        t        |d
   d      | _        | j                  
|d
   | _        |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
anchorlinkanchorlink_class	permalinkFpermalink_classpermalink_titlez[Hh][123456]	toc_depth-)super__init__rY   rZ   r'   
base_levelr   sepr\   r   use_anchorsr^   use_permalinksr`   ra   r   compile
header_rgxr/   strsplittoc_top
toc_bottom)selfr@   configx	__class__s       r   re   zTocTreeprocessor.__init__   sA   X&G_
f[12Q6i(+&,)&*>? &'9 :,VK-@%H&"("5D%&78%&78**^4f[)3/C6+;N4N=CK=P=V=VWZ=[,\SV,\)DL$/DL!&"56DO -]s   >D<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)rk   r%   tag
iterparent)rp   nodechilds      r   rx   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)rx   r3   r.   r   r5   rY   rI   range)rp   rootelemrT   r6   r5   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. rH      zh%dN)r'   rw   rf   )rp   r~   rG   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Elementr5   attribr^   r0   rI   remove)rp   r6   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                  |       y )Nr   Tz%spara;r   r   r   rZ   )	r   r   ri   r   r5   r   r`   ra   r0   )rp   r6   r   r_   s       r   add_permalinkzTocTreeprocessor.add_permalink   s    MM#&	!00D8 $n4#22 	 $'=	 $($8$8	!(,(<(<IW%	r    c                    t        j                  d      }| j                  |j                  d<   | j                  r6t        j
                  |d      }d|j                  d<   | j                  |_        fd ||       d| j                  j                  v r(| j                  j                  d   j                  |       |S )z' Return a string div given a toc list. divr   spantoctitlec                 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   rF   )r   
SubElementgetr5   r   )rL   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)
r   r   r\   r   rZ   r   r5   r@   treeprocessorsrun)rp   rL   r   headerr   s       @r   build_toc_divzTocTreeprocessor.build_toc_div   s    mmE""nn

7 ::%%c62F%/FMM'"**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  rq|j)                  t#        |j
                  d         |j                  d   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)   rH   zdata-toc-labelF)rA   )rG   r)   r   )FN)$setiterr   r(   r/   rw   rl   rk   r%   r   r7   r2   rC   r@   r,   r   rg   r'   rn   ro   r0   r   r   rh   r   ri   r   rU   r   rY   r   
serializerpostprocessorsr   
toc_tokenstoc)
rp   docused_idsr4   r   r5   	innertextr   r   pps
             r   r   zTocTreeprocessor.run  sE   5((* 	.Bryy RYYt_-	. 
((* 	<B"&&#&4??+@+@+Hr"| ryy( ()9$)H II&,T\\)TXX-NPX&YBIIdOrvvbz?dll2s266":$//7Y%%!$RVVBZ iio 0'		6F(MN GGE!'  $ryy0		"23##OOB		$8&&m;&&r299T?;7	<: %Z0
  ,;;S) gg  %''(( 	B&&+C	'r    )__name__
__module____qualname__re   rx   r   r   r   r   r   r   __classcell__rs   s   @r   rW   rW      s+    7.	2*!
	</r    rW   c                   .     e Zd ZeZ fdZd Z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t         dgddgddgd| _        t        |   di | y )Nz[TOC]zhText to find and replace with Table of Contents - Set to an empty string to disable. Defaults to "[TOC]"r   z<Title to insert into TOC <div> - Defaults to an empty stringr   z6CSS class(es) used for the link. Defaults to "toclink"Fz8True if header should be a self link - Defaults to Falsetoclinkr   zQTrue or link text if a Sphinx-style permalink should be added - Defaults to False
headerlinkz9CSS class(es) used for the link. Defaults to "headerlink"zPermanent linkz?Title attribute of the permalink - Defaults to 'Permanent link'1zBase level for headers.zdFunction to generate anchors based on header text - Defaults to the headerid ext's slugify function.rc   z Word separator. Defaults to "-".r   a%  Define the range of section levels to include inthe Table of Contents. A single integer (b) definesthe bottom section level (<h1>..<hb>) only.A string consisting of two digits separated by a hyphenin between ("2-5"), define the top (t) and thebottom (b) (<ht>..<hb>). Defaults to `6` (bottom).)rY   rZ   r\   r]   r^   r_   r`   ra   r[   r   r   rb    )r   rq   rd   re   )rp   kwargsrs   s     r   re   zTocExtension.__init__D  s    PQ 45  23 !/0 "+"9!: 9: !-!; < !1!? @ 89KL ABOP=%
N 	"6"r    c                     |j                  |        || _        | j                          | j                  || j	                               }|j
                  j                  |dd       y )Nr      )registerExtensionr@   resetTreeProcessorClass
getConfigsr   register)rp   r@   tocexts      r   extendMarkdownzTocExtension.extendMarkdownn  sS    
T"

((T__->? 	""65!4r    c                 H    d| j                   _        g | j                   _        y )Nr   )r@   r   r   )rp   s    r   r   zTocExtension.resetz  s    r    )	r   r   r   rW   r   re   r   r   r   r   s   @r   r   r   @  s    )(#T
5 r    r   c                      t        di | S )Nr   )r   )r   s    r   makeExtensionr     s    !&!!r    )F)T)__doc__r   r   r   r   utilr   r   r   r	   r
   r   r   r1   r   xml.etree.ElementTreer   ElementTreer   r"   rj   r$   r,   r7   rC   r2   rU   rW   r   r   r   r    r   <module>r      s     * a a 2 	   % %B3
 RZZ*+
		!4"<~c} cL< 9 < ~"r    