o
    +eG                     @  sz  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  mZ ddlmZmZmZmZ er]ddlmZ dAdBddZdCddZ e!dZ"dDddZ#e
ddEd"d#Z$e
d$dFdGd*d+Z%dHd,d-Z&dHd.d/Z'dHd0d1Z(dId2d3Z)dJd4d5Z*dKd7d8Z+d9d: Z,G d;d< d<eZ-G d=d> d>eZ.d?d@ Z/d
S )Lz
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)MarkdownFvaluestr	separatorunicodeboolreturnc                 C  sL   |st d| } | ddd} tdd|   } td||| S )z, Slugify a string, to make it URL friendly. ZNFKDasciiignorez[^\w\s-] z[{}\s]+)	unicodedata	normalizeencodedecoderesubstriplowerformat)r   r   r    r&   7lib/python3.10/site-packages/markdown/extensions/toc.pyslugify&   s
   r(   c                 C  s   t | |ddS )zP Slugify a string, to make it URL friendly while preserving Unicode characters. T)r   )r(   )r   r   r&   r&   r'   slugify_unicode0   s   r)   z^(.*)_([0-9]+)$ididsMutableSet[str]c                 C  sb   | |v s| s*t | }|rd|dt|dd f } nd| df } | |v s| r||  | 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)r*   r+   mr&   r&   r'   unique8   s   
"
r3   z0Use `render_inner_html` and `striptags` instead.eletree.Elementc                 C  sF   g }|   D ]}t|tr|t| q|| qd| S )zGet title name.r   )itertext
isinstancer   appendhtmlunescapejoinr#   )r4   textcr&   r&   r'   get_nameD   s   
r>   zIUse `run_postprocessors`, `render_inner_html` and/or `striptags` instead.Tr<   mdr   strip_entitiesc                   s   d fdd}t || S )	zN Extract raw HTML from stash, reduce to plain text and swap with placeholder. r2   re.Match[str]r   r   c              	     s`   z j jt| d }W n ttfy   | d Y S w tdd|}r.tdd|}|S )z& Substitute raw html with plain text. r   r   z	(<[^>]+>)r   z(&[\#a-zA-Z0-9]+;))Z	htmlStashZrawHtmlBlocksr0   r/   
IndexError	TypeErrorr!   r"   )r2   rawresr?   r@   r&   r'   	_html_subT   s   z#stashedHTML2text.<locals>._html_subN)r2   rA   r   r   )r
   r"   )r<   r?   r@   rG   r&   rF   r'   stashedHTML2textQ   s   rH   c                 C  s   t  }|| S )z+ Unescape Markdown backslash escaped text. )r   r:   )r<   r=   r&   r&   r'   r:   c   s   
r:   c                 C  s   |  d }dkr6|  d| }dkr6| d|  | |d d  } |  d }dkr6|  d| }dks|  d }dkrl|  d| }dkrl| d|  | |d d  } |  d }dkrl|  d| }dksId	|  } | S )
zL Strip HTML tags and return plain text. Note: HTML entities are unaffected. z<!--z-->N   <>r    )findr;   split)r<   startendr&   r&   r'   
strip_tagsi   s   & && &rR   c                 C  s@   d| v r
t d| } d| v r| dd} d| v r| dd} | S )z Escape character data. &z&amp;rK   z&lt;rL   z&gt;)r   r"   replace)r<   r&   r&   r'   escape_cdataw   s   rU   c                 C  s   |j D ]}|| } q|  S )z4 Run postprocessors from Markdown instance on text. )postprocessorsrunr#   )r<   r?   ppr&   r&   r'   run_postprocessors   s   
rY   c                 C  s@   t || }|dd }|d}|||  }t||S )z< Fully render inner html of an `etree` element as a string. rL   r   rK   )r:   
serializerindexrindexr#   rY   )r4   r?   r<   rP   rQ   r&   r&   r'   render_inner_html   s
   

r]   rootc                 C  s   t | dddu r| S t| } | dD ]B}d}t|D ]-}|jdkr<|dddr<|jp1d | }|	| q|rJ|jpBd | |_d}q|rW|j
pQd | |_
q| S )zL Remove footnote references from a copy of the element, if any are present. supNz	.//sup/..r   r*   Zfnref)nextiterr   findallreversedtagget
startswithtailremover<   )r^   parentZ
carry_textchildr&   r&   r'   remove_fnrefs   s"   rk   c           	      C  s  g }t | r| d}g |d< |d g}|| g }| r| d}|d }g |d< ||d k r]|  d}t|D ]}||d krG|d7 }q: |rX|d|  }|d|  }|| ||d krq|rk|d d n|| n|d | || || |}| s|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levelrI   r   N)lenpopr8   rc   )	toc_listZordered_listZlastZlevelsparentstZcurrent_levelZto_poppr&   r&   r'   nest_toc_tokens   s>   







&rt   c                      sh   e Zd ZdZd# fddZd$ddZd%ddZd&ddZd'ddZd'ddZ	d(ddZ
d)d!d"Z  ZS )*TocTreeprocessorz& Step through document and build TOC. r?   r   configdict[str, Any]c                   s  t  | |d | _|d | _t|d d | _|d | _|d | _|d | _|d | _	t
|d	 | _|d
 | _t
|d d| _| jd u rK|d | _|d | _|d | _t
|d d| _td| _t|d trd|d v rdd |d dD \| _| _d S d| _t|d | _d S )Nmarkertitle	baselevelr   r(   r   	toc_classtitle_class
anchorlinkanchorlink_class	permalinkFpermalink_classpermalink_titlepermalink_leadingz[Hh][123456]	toc_depth-c                 S  s   g | ]}t |qS r&   )r0   ).0xr&   r&   r'   
<listcomp>  s    z-TocTreeprocessor.__init__.<locals>.<listcomp>)super__init__rx   ry   r0   
base_levelr(   sepr{   r|   r   use_anchorsr~   use_permalinksr   r   r   r!   compile
header_rgxr7   r   rO   toc_top
toc_bottom)selfr?   rv   	__class__r&   r'   r      s*   










$zTocTreeprocessor.__init__noder5   r   -Iterator[tuple[etree.Element, etree.Element]]c                 c  sB    |D ]}| j |js|jdvr||fV  | |E dH  qdS )z? Iterator wrapper to get allowed parent and child all at once. )ZprecodeN)r   r.   rd   
iterparent)r   r   rj   r&   r&   r'   r     s   
zTocTreeprocessor.iterparentr^   elemNonec                 C  s|   |  |D ]6\}}d|  }|sq|jr;|j | jkr;t|dkr;tt|D ]}|| |kr:|||<  nq,qdS )z Replace marker with elem. r   r   N)r   r;   r6   r#   r<   rx   rn   range)r   r^   r   rs   r=   r<   ir&   r&   r'   replace_marker  s   "
zTocTreeprocessor.replace_markerc                 C  s.   t |jd | j }|dkrd}d| |_dS )z. Adjust header level according to base level. rI      zh%dN)r0   rd   r   )r   r   rm   r&   r&   r'   	set_level+  s   zTocTreeprocessor.set_levelr=   elem_idr   c                 C  sr   t d}|j|_d| |jd< | j|jd< d|_|D ]}|| qt|r2||d  t|s'|| d S )Na#hrefclassr   r   )etreeElementr<   attribr~   r8   rn   rh   )r   r=   r   anchorr   r&   r&   r'   
add_anchor2  s   
zTocTreeprocessor.add_anchorc                 C  s   t d}| jdu rdt n| j|_d| |jd< | j|jd< | jr(| j|jd< | jr:|j|_	d|_|
d	| d S || d S )
Nr   Tz%spara;r   r   r   ry   r   r   )r   r   r   r   r<   r   r   r   r   rg   insertr8   )r   r=   r   r   r&   r&   r'   add_permalink>  s   

zTocTreeprocessor.add_permalinkrp   listc                   s|   t d}| j|jd< | jr!t |d}| jr| j|jd< | j|_d fd	d
  || d| jj	v r<| jj	d 
| |S )z' Return a string div given a toc list. divr   spanrp   r   ri   r5   r   c                   sl   t |d}| D ]+}t |d}t |d}|dd|_d|dd |jd< |d	 r3 |d	 | q|S )
Nullir   namer   r   r*   r   rl   )r   
SubElementre   r<   r   )rp   ri   r   itemr   linkbuild_etree_ulr&   r'   r   Z  s   z6TocTreeprocessor.build_toc_div.<locals>.build_etree_ulZprettifyN)rp   r   ri   r5   r   r5   )r   r   r{   r   ry   r   r|   r<   r?   treeprocessorsrW   )r   rp   r   headerr&   r   r'   build_toc_divN  s   

zTocTreeprocessor.build_toc_divdocc              	   C  s  t  }| D ]}d|jv r||jd  qg }| D ]}t|jtr| j|jr| 	| t
t|| j}t|}d|jvrRt| t|| j||jd< d}d|jv rntt|jd | j}tt|}|jd= t|jd | jkrt|jd | jkr|t|jd |jd |||d | jr| ||jd  | jdvr| ||jd  qt|}| |}| jr|  || | j!|}	| jj"D ]}
|
#|	}	q|| j_$|	| j_%d S )Nr*   r   data-toc-labelrI   )rm   r*   r   r9   r   )FN)&setra   r   r1   r7   rd   r   r   r.   r   r]   rk   r?   rR   r3   r(   r9   r:   r   rY   rU   r0   r   r   r8   r   r   r   r   rt   r   rx   r   rZ   rV   rW   
toc_tokenstoc)r   r   Zused_idsr4   r   Z	innerhtmlr   Zdata_toc_labelr   r   rX   r&   r&   r'   rW   m  sP   


 
(

zTocTreeprocessor.run)r?   r   rv   rw   )r   r5   r   r   )r^   r5   r   r5   r   r   )r   r5   r   r   )r=   r5   r   r   r   r   )rp   r   r   r5   )r   r5   r   r   )__name__
__module____qualname____doc__r   r   r   r   r   r   r   rW   __classcell__r&   r&   r   r'   ru      s    





ru   c                      s2   e Zd ZeZ fddZdd Zd	ddZ  ZS )
TocExtensionc                   st   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 jdi | d S )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.Z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`.Ztoclinkz5CSS class(es) used for the link. Defaults: `toclink`.r   zPTrue or link text if a Sphinx-style permalink should be added. Default: `False`.Z
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).)rx   ry   r|   r{   r}   r~   r   r   r   r   rz   r(   r   r   r&   )r(   rv   r   r   )r   kwargsr   r&   r'   r     s@   /zTocExtension.__init__c                 C  s<   | |  || _|   | ||  }|j|dd dS )z% Add TOC tree processor to Markdown. r      N)ZregisterExtensionr?   resetTreeProcessorClassZ
getConfigsr   register)r   r?   Ztocextr&   r&   r'   extendMarkdown  s
   
zTocExtension.extendMarkdownr   r   c                 C  s   d| j _g | j _d S )Nr   )r?   r   r   )r   r&   r&   r'   r     s   zTocExtension.reset)r   r   )	r   r   r   ru   r   r   r   r   r   r&   r&   r   r'   r     s
    4r   c                  K  s   t di | S )Nr&   )r   )r   r&   r&   r'   makeExtension  s   r   )F)r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )r*   r   r+   r,   r   r   )r4   r5   r   r   )T)r<   r   r?   r   r@   r   r   r   )r<   r   r   r   )r<   r   r?   r   r   r   )r4   r5   r?   r   r   r   )r^   r5   r   r5   )0r   Z
__future__r   r   r   r   r   utilr   r   r	   r
   r   r   Zserializersr   r!   r9   r   copyr   Zxml.etree.ElementTreer   ZElementTreetypingr   r   r   r   Zmarkdownr   r(   r)   r   r-   r3   r>   rH   r:   rR   rU   rY   r]   rk   rt   ru   r   r   r&   r&   r&   r'   <module>   sD   









A 4E