U
    Sh;                    @  s  d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	 ddl
mZmZ ddlmZmZ ddlmZ ddlmZmZmZ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Z ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z& ddl"m'Z( ddl)m*Z* ddl+m!Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddlGmHZHmIZI ddlJmKZKmLZLmMZMmNZNmOZOmPZP ddlQmRZRmSZS ddlTmUZUmVZV ddlWmWZW erdd lXmYZY d!e(fd"d#d$d%ZZe[d&Z\e[d'Z]e[d(Z^dEd)d*d+d,d-d.Z_G d/d0 d0e>Z`d1d"d+d2d3d4d5d6Zad7d8d9d:d;Zbe[d<Zcd8d8d=d>d?ZddFd)d@dAd8dBdCdDZedS )Gz-Convert Markdown-it tokens to docutils nodes.    )annotationsN)OrderedDict)contextmanagersuppress)datedatetime)
ModuleType)TYPE_CHECKINGAnyCallableIterableIteratorMutableMappingSequencecast)urlparse)nodes)get_language)	DirectiveDirectiveError
directivesroles)Parser)Include)
StringList)Filter)ReporterSystemMessagenew_document)Lexer
LexerErrorNumberLines)
MarkdownIt)
escapeHtml)RendererProtocol)Token)SyntaxTreeNode)	inventory)findall)MdParserConfigUrlSchemeType)MockIncludeDirectiveMockingErrorMockInlinerMockRSTParser	MockStateMockStateMachine)MarkupErrorparse_directive_text)MystWarningscreate_warning   )html_to_nodes)BuildEnvironmentZnotsetnodes.documentreturnc                 C  sP   t jdd dkr(ddlm} ||}nddlm} ||fd }t| |dS )	zJCreate a new docutils document, with the parser classes' default settings.N   )r      r   )get_default_settings)OptionParser)
components)settings)docutils__version_info__Zdocutils.frontendr=   r>   get_default_valuesr   )source_pathZ
parser_clsr=   r@   r>    rE   T/root/rtd-docs/venv/lib/python3.8/site-packages/myst_parser/mdit_to_docutils/base.pymake_documentA   s    
rG   z^([a-zA-Z][a-zA-Z0-9+.-]*):z8{{\s*(uri|scheme|netloc|path|params|query|fragment)\s*}}z+^[\s]{0,3}([`]{3,10}|[~]{3,10}|[:]{3,10})\{r&   
int | Noneint)tokendefaultr:   c                 C  s0   t | dds&|dk	r|S td|  | jd S )z%Retrieve the initial line of a token.mapNztoken map not set: r   )getattr
ValueErrorrL   )rJ   rK   rE   rE   rF   
token_line[   s
    rO   c                   @  sP  e Zd ZdZdZdddddZdd	d
dZddddddZeddddZ	dddddddddddZ
dddd d!Zd"dd#d$d%d&Zddd'd(Zddd)d*Zddd-d.d/d-dd0d1d2Zedd3d.d4d5d6d7Zd8dd9d:d;Zd8dd9d<d=Zd>d8dd?d@dAZddddCd8d3dDdEdFddGdHdIZdJd-ddKdLdMZdNdddOdPZd8dd9dQdRZd8dd9dSdTZd8dd9dUdVZd8dd9dWdXZd8dd9dYdZZd8dd9d[d\Zd8dd9d]d^Zd8dd9d_d`Zd8dd9dadbZ d8dd9dcddZ!d8dd9dedfZ"d8dd9dgdhZ#d8dd9didjZ$e%dd-dkdldmdnZ&d+dodde'j(dfddpd.d-dpddqdrd3ds	dtduZ)d8dd9dvdwZ*d8dd9dxdyZ+ed.ddzd{Z,d8d-d3d3dd|d}d~Z-d8dd9ddZ.d8dd9ddZ/dd8dddddZ0d8dd9ddZ1d8dd9ddZ2d8dddddZ3d8dd9ddZ4d8dd9ddZ5dpdpdpdpddddZ6d8dd9ddZ7d8dd9ddZ8d8dd9ddZ9d8dd9ddZ:d8dd9ddZ;dddd-ddddZ<d8dd9ddZ=d8dd9ddZ>d8dd9ddZ?d8dd9ddZ@d8dd9ddZAd8dd9ddZBd8dd9ddZCd8dd9ddZDd8dd9ddZEd8dd9ddZFd8dd9ddZGd8dd9ddZHd8dd9ddZId8dd9ddZJd8dd9ddZKd8dd9ddÄZLd8dd9ddńZMd8dd9ddǄZNd8dd9ddɄZOddʜd8dddFdd˜dd̈́ZPddddd-dFd>dΜddЄZQd8dd9dd҄ZRd8dd9ddԄZSd8d.dd՜ddׄZTdS )DocutilsRendererzA markdown-it-py renderer to populate (in-place) a `docutils.document` AST.

    Note, this render is not dependent on Sphinx.
    rA   r"   None)parserr:   c                 C  s,   || _ dd tj| tjdD | _d| _dS )z,Load the renderer (called by ``MarkdownIt``)c                 S  s(   i | ] \}}| d r|dkr||qS )render_render_children)
startswith.0kvrE   rE   rF   
<dictcomp>o   s
   
  z-DocutilsRenderer.__init__.<locals>.<dictcomp>)	predicateN)mdinspect
getmembersismethodrules_inventories)selfrR   rE   rE   rF   __init__l   s
    zDocutilsRenderer.__init__strnamec                 C  s8   |dkrt d| dt dt| j d| ddS )z.Warn when the renderer has not been setup yet.)	md_env	md_config
md_optionsdocumentcurrent_nodereporterlanguage_module_rst_heading_offset_level_to_section'z;' attribute is not available until setup_render() is calledz' object has no attribute 'N)AttributeErrortype__name__)rb   rf   rE   rE   rF   __getattr__w   s    
zDocutilsRenderer.__getattr__dict[str, Any]zMutableMapping[str, Any])optionsenvr:   c                 C  sl   || _ || _|d | _|dt | _|d| j| _| jj| _t| jj	j
| _d| _d| ji| _i | _dS )z-Setup the renderer with per render variables.Zmyst_configrj   rk   r   N)rg   ri   rh   getrG   rj   rk   rl   get_language_rstr@   language_coderm   rn   ro   _heading_slugs)rb   rv   rw   rE   rE   rF   setup_render   s    

 zDocutilsRenderer.setup_renderzBuildEnvironment | Noner9   c                 C  s(   z| j jjW S  tk
r"   Y dS X dS )z'Return the sphinx env, if using Sphinx.N)rj   r@   rw   rq   rb   rE   rE   rF   
sphinx_env   s    zDocutilsRenderer.sphinx_envNline	append_tor3   rH   znodes.Element | Noneznodes.system_message | None)messagesubtyper   r   r:   c                C  s   t | j||||dS )zGenerate a warning, logging if it is necessary.

        If the warning type is listed in the ``suppress_warnings`` configuration,
        then ``None`` will be returned and no warning logged.
        r   )r4   rj   )rb   r   r   r   r   rE   rE   rF   r4      s    zDocutilsRenderer.create_warningzlist[Token])tokensr:   c           	      C  s  |D ]B}|j sq|j d d |j d d g|_ |jp6g D ]}|j |_ q8qt|}| jdi  |jddD ]R}g }|jD ]<}|jdkr|jd }| jd |g | qx|| qx||_qj|jD ]T}d|j | j	kr| j	d|j  | q| j
d	|j tjt|dd
| jd qdS )zRender the tokens.r   r5   	foot_refsT)Zinclude_selffootnote_referencelabelrS   No render method for: rK   r   N)rL   childrenr&   rg   
setdefaultwalkrr   metaappendr`   r4   r3   RENDER_METHODrO   rk   )	rb   r   rJ   Ztoken_childZ	node_treenodeZnew_childrenchildr   rE   rE   rF   _render_tokens   s2    





zDocutilsRenderer._render_tokenszSequence[Token]r8   )r   rg   r:   c                 C  s0   |  || |   | t| |   | jS )a)  Run the render on a token stream.

        :param tokens: list on block tokens to render
        :param options: params of parser instance
        :param md_env: the markdown-it environment sandbox associated with the tokens,
            containing additional metadata like reference info
        )r|   _render_initialiser   list_render_finaliserj   )rb   r   rv   rg   rE   rE   rF   render   s
    
zDocutilsRenderer.renderc                 C  s$   | j t| jj| jd| jd dS )z&Initialise the render of the document.r   )rj   r   rl   N)rk   extendhtml_meta_to_nodesrh   	html_metarj   rl   r}   rE   rE   rF   r      s    z#DocutilsRenderer._render_initialisec                 C  s  | j | j_| j r,| jr,| j | jj| jj d< | jdg D ]0}| jd|d  t	j
|d d d | jd q:t }t| jtjD ]}|d	 |krd
||d	 < q|r| jjr| jtjdgd |D ]z}| jd |g }t|dkr| jd| dt	j| jd t|dk r2| jd| dt	j| jd q| |d  q| jdi }|r| jdk	r~| jj| jji }||d< dD ]n}||d}	|	dkrqtt|	tt|	}
| jd |
_|
d d|  | j|
d|  qdS )z$Finalise the render of the document.
myst_slugsZduplicate_refsz Duplicate reference definition: r   rL   r   r5   r   refnameTZ	footnotesclassesr   z0Multiple footnote definitions found for label: 'rp   )r   z*No footnote definitions found for label: 'Z	wordcountN)wordsminutessourcenamesz
wordcount-)r{   rj   r   r~   metadataZdocnamerg   rx   r4   r3   ZMD_DEF_DUPEr   r(   r   r   rh   Zfootnote_transitionrk   r   
transitionlenZMD_FOOTNOTE_DUPEZMD_FOOTNOTE_MISSINGrender_footnote_referencer   Zsubstitution_definitionrd   Textr   Znote_substitution_def)rb   Zdup_refr   refnodeZfootrefZfoot_ref_tokensZwordcount_metadatar   keyvalueZsubstitution_noderE   rE   rF   r     sf    



  z!DocutilsRenderer._render_finaliseFr   rI   boolzNone | nodes.Element)textlinenoinlinetemp_root_nodeheading_offsetr:   c           	   	     s   |rj |jnj |d j}|rD|d jdkrD|d |D ](}|jrH|jd | |jd | g|_qHt fdd}|  | W 5 Q R X dS )a  Render unparsed text (appending to the current node).

        :param text: the text to render
        :param lineno: the starting line number of the text, within the full source
        :param inline: whether the text is inline or block
        :param temp_root_node: If set, allow sections to be created as children of this node
        :param heading_offset: offset heading levels by this amount
        
r   Zfront_matterr5   c                  3  sb   j }  _ d k	r:tj }jdd }jd< d V  | _ d k	r^|jd< |_d S )Nr   )rn   dictro   itemsrg   rx   )Zcurrent_heading_offsetZcurrent_level_to_sectionZcurrent_root_noder   rb   r   rE   rF   _restorei  s    

z5DocutilsRenderer.nested_render_text.<locals>._restoreN)	r\   ZparseInlinerg   parserr   poprL   r   r   )	rb   r   r   r   r   r   r   rJ   r   rE   r   rF   nested_render_textJ  s    
 z#DocutilsRenderer.nested_render_textnodes.ElementzIterator[None])r   r   r:   c                 c  s,   |r| j | | j }|| _ dV  || _ dS )z9Context manager for temporarily setting the current node.N)rk   r   )rb   r   r   rk   rE   rE   rF   current_node_context|  s    z%DocutilsRenderer.current_node_contextr&   )rJ   r:   c                 C  sd   |j pg D ]T}d|j | jkr8| jd|j  | q
| jd|j tjt|dd| jd q
dS )zRender the children of a token.rS   r   r   r   r   N)r   rr   r`   r4   r3   r   rO   rk   )rb   rJ   r   rE   rE   rF   rT     s    

z DocutilsRenderer.render_childrenc              	   C  s.   t t t||_W 5 Q R X | jd |_dS )zCCopy the line number and document source path to the docutils node.r   N)r   rN   rO   r   rj   r   )rb   r   rJ   rE   rE   rF   add_line_and_source_path  s    
z)DocutilsRenderer.add_line_and_source_pathzlist[nodes.Element])nodes_rJ   r:   c                 C  s6   |D ],}|  || t| D ]}|  || qqdS )zyCopy the line number and document source path to the docutils nodes,
        and recursively to all descendants.
        N)r   r(   )rb   r   rJ   r   r   rE   rE   rF   add_line_and_source_path_r  s    z+DocutilsRenderer.add_line_and_source_path_rclass
convertersaliaseszSequence[str]z&dict[str, Callable[[str], Any]] | Nonezdict[str, str] | None)rJ   r   keysr   r   r:   c          	      C  s  |dkri }|dkri }|j  D ]\}}|||}||kr@q"|dkr`|d t|  q"|dkrtt|}|d | | j	
|| q"||krz|| t|}W nF tk
r   | jd|d|j | tjt|dd	|d
 Y q"Y nX |||< q"dS )a  Copy attributes on the token to the docutils node.

        :param token: the token to copy attributes from
        :param node: the node to copy attributes to
        :param keys: the keys to copy from the token (after aliasing)
        :param converters: a dictionary of converters for the attributes
        :param aliases: a dictionary mapping the token key name to the node key name
        Nr   r   idr   zInvalid z attribute value: r   r   r   )attrsr   rx   r   rd   splitr   fully_normalize_namer   rj   note_explicit_targetrN   r4   r3   INVALID_ATTRIBUTErO   )	rb   rJ   r   r   r   r   r   r   rf   rE   rE   rF   copy_attributes  s4    

z DocutilsRenderer.copy_attributesznodes.section)sectionlevelr:   c                   s   t  fdd| jD }| j| } |krr|d  krrd| d  }|dkrZd  d}| j|tj|j| jd	 || || j <  fd
d| j D | _dS )zGUpdate the section level state, with the new current section and level.c                 3  s   | ]} |kr|V  qd S NrE   )rW   section_levelr   rE   rF   	<genexpr>  s   z>DocutilsRenderer.update_section_level_state.<locals>.<genexpr>r5   z(Non-consecutive header level increase; Hz to Hr   zDocument headings start at Hz, not H1r   c                   s   i | ]\}}| kr||qS rE   rE   )rW   r   r   r   rE   rF   rZ     s    z?DocutilsRenderer.update_section_level_state.<locals>.<dictcomp>N)	maxro   r4   r3   ZMD_HEADING_NON_CONSECUTIVEr   rk   r   r   )rb   r   r   Zparent_levelparentmsgrE   r   rF   update_section_level_state  s&    



z+DocutilsRenderer.update_section_level_statezlist[SyntaxTreeNode]c                 C  s@   d}|p
g D ].}|j dkr&||j7 }q|| |jp4g 7 }q|S )zSpecial kludge for image `alt` attributes to conform CommonMark spec.

        Don't try to use it! Spec requires to show `alt` content with stripped markup,
        instead of simple escaping.
         r   )rr   contentrenderInlineAsTextr   )rb   r   resultrJ   rE   rE   rF   r     s    
z#DocutilsRenderer.renderInlineAsTextc              	   C  s`   t |jr|jd jnd}| j||dd | || | j|dd | | W 5 Q R X d S )Nr   r   r   r   r   Tr   )r   	paragraphr   r   r   r   r   rT   )rb   rJ   pararE   rE   rF   render_paragraph	  s
    z!DocutilsRenderer.render_paragraphc                 C  s   |  | d S r   )rT   rb   rJ   rE   rE   rF   render_inline  s    zDocutilsRenderer.render_inlinec                 C  s   | j t|j d S r   )rk   r   r   r   r   r   rE   rE   rF   render_text  s    zDocutilsRenderer.render_textc              	   C  s\   t  }|jr|j|d< | j||dd | || | j|dd | | W 5 Q R X d S )NZbulletr   r   Tr   )r   Zbullet_listmarkupr   r   r   rT   )rb   rJ   	list_noderE   rE   rF   render_bullet_list  s    
z#DocutilsRenderer.render_bullet_listc              	   C  s   d}d|j kr0ddddddt|j d |}tj|dd	}|j|d
< | j||dd | || | j|dd | 	| W 5 Q R X d S )NarabicstyleZ
loweralphaZ
upperalphaZ
lowerromanZ
upperroman)decimalzlower-alphazupper-alphazlower-romanzupper-romanr   )Zenumtypeprefixsuffix)r   r   startr   Tr   )
r   rx   rd   r   Zenumerated_listr   r   r   r   rT   )rb   rJ   r   r   rE   rE   rF   render_ordered_list  s"    
 
z$DocutilsRenderer.render_ordered_listc              	   C  sL   t  }| j||dd | || | j|dd | | W 5 Q R X d S )Nr   r   Tr   )r   Z	list_itemr   r   r   rT   )rb   rJ   Z	item_noderE   rE   rF   render_list_item1  s
    z!DocutilsRenderer.render_list_itemc              	   C  s<   t  }| || | j|dd | | W 5 Q R X d S NTr   )r   Zemphasisr   r   rT   rb   rJ   r   rE   rE   rF   	render_em8  s    zDocutilsRenderer.render_emc                 C  s   | j td d S )Nr   )rk   r   r   r   r   rE   rE   rF   render_softbreak>  s    z!DocutilsRenderer.render_softbreakc                 C  s4   | j tjdddd | j tjdddd d S )Nr   z<br />
htmlformatz\\
latex)rk   r   r   rawr   rE   rE   rF   render_hardbreakA  s    z!DocutilsRenderer.render_hardbreakc              	   C  s<   t  }| || | j|dd | | W 5 Q R X d S r   )r   strongr   r   rT   r   rE   rE   rF   render_strongE  s    zDocutilsRenderer.render_strongc              
   C  s   t  }| j||dd | || | j|ddr | | d|jkrt |jd d}| || | j|dd& | jt	|jd t
|ddd W 5 Q R X W 5 Q R X d S )	Nr   r   Tr   attributionr   r   r   )r   Zblock_quoter   r   r   rT   r   r   r   rd   rO   )rb   rJ   quoter   rE   rE   rF   render_blockquoteK  s    

z"DocutilsRenderer.render_blockquotec                 C  s$   t  }| || | j| d S r   )r   r   r   rk   r   r   rE   rE   rF   	render_hr[  s    zDocutilsRenderer.render_hrc                 C  sf   t |j|j}| || | j||ddddd d|krVd|d krV|d d | j| d S )N)r   r   languager   )lexerlr   coder   )r   literalr   r   r   r   rk   r   rE   rE   rF   render_code_inline`  s    z#DocutilsRenderer.render_code_inlinez	list[int])emphasize_lines	num_linesr:   c                   sL   ddl m} ||  }t fdd|D r:td   fdd|D S )zeParse the `emphasize_lines` argument.

        Raises ValueError if the argument is invalid.
        r   )parselinenosc                 3  s   | ]}| kV  qd S r   rE   )rW   ir  rE   rF   r   v  s     z2DocutilsRenderer._parse_linenos.<locals>.<genexpr>zout of range(1-c                   s   g | ]}| k r|d  qS )r5   rE   )rW   xr  rE   rF   
<listcomp>y  s      z3DocutilsRenderer._parse_linenos.<locals>.<listcomp>)Zsphinx.utilr  anyrN   )r  r  r  hl_linesrE   r  rF   _parse_linenosm  s
    
zDocutilsRenderer._parse_linenosr5   z
str | Noneztype[nodes.Element]zlist[int] | str | None)	r   
lexer_namenumber_lineslineno_startr   r   node_clsr  r:   c	              
   C  s  | j dk	r||||pdd}	|r<d|	d< |dkr<d|i|	d< t|trz| |t| }W n: tk
r }
 z| jd	|
 tj	|d
 W 5 d}
~
X Y nX t|t
tfrd|	kri |	d< ||	d d< n||dg|r|gng  d}	z t||pd| jjrdnd}W n` tk
rb }
 z@| jjt|
fdd d|fd|ffD  t||pLdd}W 5 d}
~
X Y nX |rt|||t|  }|D ]4\}}|r|	tj|||d7 }	n|	t|7 }	q|dk	r||	_|dk	r||	_|	S )a  Create a literal block with syntax highlighting.

        This mimics the behaviour of the `code-block` directive.

        In docutils, this directive directly parses the text with the pygments lexer,
        whereas in sphinx, the lexer name is only recorded as the `language` attribute,
        and the text is lexed later by pygments within the `visit_literal_block`
        method of the output format ``SphinxTranslator``.

        Note, this function does not add the literal block to the document.
        Nnone)r   TZlinenosr5   ZlinenostartZhighlight_argszemphasize_lines: r   r  r  r   r   shortc                 S  s   i | ]\}}|d k	r||qS r   rE   )rW   rf   r   rE   rE   rF   rZ     s    zBDocutilsRenderer.create_highlighted_code_block.<locals>.<dictcomp>r   r   )r~   
isinstancerd   r  r   
splitlinesrN   r4   r3   r   r   tupler   rh   Zhighlight_code_blocksr    rl   warningr!   r   r   r   r   r   )rb   r   r  r  r  r   r   r  r  r   errZ
lex_tokensr   r   rE   rE   rF   create_highlighted_code_block{  sp    

 
 $  

z.DocutilsRenderer.create_highlighted_code_blockc              	   C  s   |j r|j  d nd }d}d}d|jkr:t|jdnd }d|jkrntt t|jd }d}W 5 Q R X | j|j	|||| j
d t|dpd |d}| ||d	 | j| d S )
Nr   r5   Femphasize-lineslineno-startTr   )r  r  r   r   r  r   )infor   r   rd   rx   r   rN   rI   r  r   rj   rO   r   rk   r   )rb   rJ   r   r  r  r  r   rE   rE   rF   render_code_block  s,    

	z"DocutilsRenderer.render_code_blockc           
   	   C  s  |j r|j  ndjdd}|r(|d nd}t|dkr@|d nd}| jjs| jjs|dkrf| |S |dr|	dr| 
||dd |S || jjkrd	d
 |j D }d|kr|d|d< | j
||||dS |s| jdk	r| jjd| jjj}d}|| jjk}d|jkr(t|jdnd}d|jkr^tt t|jd }d}W 5 Q R X | j|j|||| jd t|dpd|d}	| ||	d | j|	 dS )zRender a fenced code block.r   r5   maxsplitr   z
{eval-rst}{}c                 S  s   i | ]\}}|t |qS rE   )rd   rV   rE   rE   rF   rZ     s      z1DocutilsRenderer.render_fence.<locals>.<dictcomp>r   rf   additional_optionsNhighlight_languager  r  Tr   )r  r  r   r   r  r   ) r  stripr   r   rh   commonmark_onlygfm_onlyrender_restructuredtextrU   endswithrender_directiveZfence_as_directiver   r   r   r~   Z	temp_datarx   configr&  Znumber_code_blocksrd   r   rN   rI   r  r   rj   rO   r   rk   r   )
rb   rJ   partsrf   	argumentsrv   r  r  r  r   rE   rE   rF   render_fence  sX    
    
	zDocutilsRenderer.render_fencec                 C  s   | j dk	od| jjko| jjS )zOnly add mathjax ignore classes if using sphinx,
        and using the ``dollarmath`` extension, and ``myst_update_mathjax=True``.
        NZ
dollarmath)r~   rh   Zenable_extensionsZupdate_mathjaxr}   rE   rE   rF   blocks_mathjax_processing  s
    

z*DocutilsRenderer.blocks_mathjax_processing)rJ   r   r   
title_noder:   c           	   
   C  s   t |}t|}|d | | j|| || jjkr>dS zt|| j	| jj
}W nD tk
r } z&| jt|tjt|dd| jd W 5 d}~X Y n$X ||d< |j|d d |f| j	|< dS )z6Generate a heading target, and add it to the document.r   Nr   r   r   slugZids)clean_astextr   r   r   rj   Znote_implicit_targetrh   Zheading_anchorscompute_unique_slugr{   Zheading_slug_func	Exceptionr4   rd   r3   ZHEADING_SLUGrO   rk   r   )	rb   rJ   r   r   r2  implicit_textrf   r3  errorrE   rE   rF   generate_heading_target%  s*    	

z(DocutilsRenderer.generate_heading_targetc              	   C  sn  t |jd | j }| jdddk	o4| j| jd k}|st| jtjtj	fstj
|jd|d}| || | ||d | j|dd | | W 5 Q R X | |||| dS t	 }| || | ||d |dkr| jr|d	 d
dg | || t|jr|jd jnd}| || || | | | | W 5 Q R X | |||| || _dS )z#Render a heading, e.g. `# Heading`.r5   r   Nr   r   r   Tr   r   Ztex2jax_ignoreZmathjax_ignorer   )rI   tagrn   rg   rx   rk   r  r   rj   r   rubricr   r   r   r   rT   r9  r1  r   r   titler   r   )rb   rJ   r   Zparent_of_temp_rootr;  Znew_sectionr2  rE   rE   rF   render_headingS  s8    
zDocutilsRenderer.render_headingc                 C  s  | j js| j js| j jr"| |S d|jkrLdt|jd  krL| |S tt|	dp\d}|
drv| ||S t|}|dkrdn|d}|| j jkr| || j j| S |dkr| |S |d	kr| |S |d
kr| |S |jdkr| |S | |S )a  Parse `<http://link.com>` or `[text](link "title")` syntax to docutils AST:

        - If `myst_all_links_external` is True, forward to `render_link_url`
        - If the link token has a class attribute containing `external`,
            forward to `render_link_url`
        - If the link is an id link (e.g. `#id`), forward to `render_link_anchor`
        - If the link has a schema, and the schema is in `url_schemes` (e.g. `http:`),
          forward to `render_link_url`
        - If the link has an `inv:` schema, forward to `render_link_inventory`
        - If the link is an autolink/linkify type link, forward to `render_link_url`
        - Otherwise, forward to `render_link_internal`
        r   Zexternalhrefr   #Nr5   invpathprojectauto)rh   r(  r)  Zall_links_externalrender_link_urlr   rd   r   r   attrGetrU   render_link_anchorREGEX_SCHEMEmatchgroupZurl_schemesrender_link_inventoryrender_link_pathrender_link_projectr  render_link_unknown)rb   rJ   r>  Zscheme_matchschemerE   rE   rF   render_link  s2    
 






zDocutilsRenderer.render_linkzNone | UrlSchemeType)rJ   
conversionr:   c              	     s  t  }| || dddddg}| jjr>d|jd< d|jd< | j|||ddid	 tt|	d
pdd}d}|dk	r*| j
|}t|}||j|j|j|j|j|jd d|krtt fdd|d }| j
|}d|kr|jdks|jstt fdd|d }d|kr*|d |d  t||d< |dk	rn| j|dd | jt | W 5 Q R X n$| j|dd | | W 5 Q R X dS )z{Render link token (including autolink and linkify),
        where the link has been identified as an external URL.
        r   r   reftitletargetrelZ_blankznoreferer noopenerr<  r   r>  r   N)urirN  netlocrA  paramsqueryfragmenturlc                   s     | ddS Nr5   r   rx   rI  rH  parsedrE   rF   <lambda>      z2DocutilsRenderer.render_link_url.<locals>.<lambda>rC  c                   s     | ddS rZ  r[  r\  r]  rE   rF   r_    r`  r   refuriTr   ) r   	referencer   rh   Zlinks_external_new_tabr   r   r   rd   rE  r\   normalizeLinkTextr   rN  rU  rA  rV  rW  rX  resubREGEX_URI_TEMPLATEZnormalizeLinkr  r   r   r#   r   rk   r   r   rT   )rb   rJ   rP  ref_nodeZattribute_keysrT  r7  Z_parsedrE   r]  rF   rD    s\    

   




z DocutilsRenderer.render_link_urlc                 C  s&   | j dtjt|d| jd | |S )z&Render a link token like `<path:...>`.z,`path:` scheme not yet supported in docutilsr   r   )r4   r3   NOT_SUPPORTEDrO   rk   rD  r   rE   rE   rF   rK    s    z!DocutilsRenderer.render_link_pathc                 C  sf   t t|dpd}|dr*|dd }|dr@| ||S | jdtjt|d| j	d	 | 
|S )
z)Render a link token like `<project:...>`.r>  r   zproject:   Nr?  z>`project:` scheme for file paths not yet supported in docutilsr   r   )r   rd   rE  rU   rF  r4   r3   rh  rO   rk   rD  )rb   rJ   destinationrE   rE   rF   rL    s    

z$DocutilsRenderer.render_link_project)rJ   rR  r:   c              	   C  s|   t  }| || d|d< | j||d< | j||dddid | j| |jdkrx| 	| | 
| W 5 Q R X d	S )
zuRender link token like `[text](#target)`, to a local target.

        :target: the target id, e.g. `#target`
        TZid_linkra  r   r   rQ  r<  rQ  r   rC  N)r   rb  r   r\   rc  r   rk   r   r  r   rT   )rb   rJ   rR  rg  rE   rE   rF   rF    s       
z#DocutilsRenderer.render_link_anchorc              	   C  sv   t  }| || | j||dddid tt|dp:d|d< | j| | j	|dd	 | 
| W 5 Q R X d
S )aa  Render link token `[text](link "title")`,
        where the link has not been identified as an external URL::

            <reference refname="link" title="title">
                text

        `text` can contain nested syntax, e.g. `[**bold**](link "title")`.

        Note, this is overridden by `SphinxRenderer`, to use `pending_xref` nodes.
        rk  r<  rQ  r   r>  r   r   Tr   N)r   rb  r   r   r   rd   rE  rj   Znote_refnamer   rT   )rb   rJ   rg  rE   rE   rF   rM    s       z$DocutilsRenderer.render_link_unknownc              	   C  sX  | j tt|dpd}|jdko.t|j}t|}|j	}d\}}}|j
r|j
d}	tt |	d }|	d }|	d }W 5 Q R X | j||||d	}
|
st||||}| jd
|tjt|dd| jd dS t|
dkrRd}t||||}ddd |
d| D }t|
|kr(|d7 }| jd|d| tjt|dd| jd |
d }tjdddd}t|j|j|j|j|d< | || | j ||dddid |j!rt"|j!|j#n|j#|d< d|kr|j$ d|j% & |d< | j'| |r"| (| | )| W 5 Q R X n2|j*r>|'t+|j* n|'t,|j|j dS )a  Create a link to an inventory object.

        This assumes the href is of the form `<scheme>:<path>#<target>`.
        The path is of the form `<invs>:<domains>:<otypes>`,
        where each of the parts is optional, hence `<scheme>:#<target>` is also valid.
        Each of the path parts can contain the `*` wildcard, for example:
        `<scheme>:key:*:obj#targe*`.
        `\*` is treated as a plain `*`.
        r>  r   rC  )NNN:r   r5   r;   )rR  invsdomainsotypeszNo matches for r   r   N   z, c                 S  s$   g | ]}t |j|j|j|jqS rE   )r'   filter_stringr@  domainotyperf   )rW   mrE   rE   rF   r
  c  s   z:DocutilsRenderer.render_link_inventory.<locals>.<listcomp>z, ...zMultiple matches for : F)ZinternalZ	inv_matchrk  r<  rQ  r   ra   )-r\   rc  r   rd   rE  r  r   r   r   rX  rA  r   r   
IndexErrorget_inventory_matchesr'   rq  r4   r3   ZIREF_MISSINGrO   rk   r   joinZIREF_AMBIGUOUSr   rb  r@  rr  rs  rf   r   r   base_url	posixpathlocrB  versionr'  r   r   rT   r   r   r  )rb   rJ   r>  explicitZ	uri_partsrR  rm  rn  ro  
path_partsmatchesZ
filter_strZshow_numZmatches_strrH  rg  rE   rE   rF   rJ  3  s    

   


      
z&DocutilsRenderer.render_link_inventoryzlist[inventory.InvMatch])rm  rn  ro  rR  r:   c                C  s   | j dkri | _ | jj D ]\}\}}|dkr<t|dn|}| jd|d|  ztj	||d}	W n< t
k
r }
 z| d|d|
 tj W 5 d}
~
X Y qX |	| j |< qttj| j ||||dS )zjReturn inventory matches.

        This will be overridden for sphinx, to use intersphinx config.
        Nzobjects.invzLoading inventory ru  )rz  zFailed to load inventory )rm  rn  ro  targets)ra   rh   Zinventoriesr   r{  ry  rl   r  r'   Zfetch_inventoryr6  r4   r3   ZINV_LOADr   Zfilter_inventories)rb   rm  rn  ro  rR  r   rT  rA  Z	load_pathr@  excrE   rE   rF   rx    s,    
z&DocutilsRenderer.get_inventory_matchesc                 C  s   |  | d S r   )render_html_blockr   rE   rE   rF   render_html_inline  s    z#DocutilsRenderer.render_html_inlinec                 C  s"   t |jt|| }| j| d S r   )r6   r   rO   rk   r   )rb   rJ   Z	node_listrE   rE   rF   r    s    z"DocutilsRenderer.render_html_blockc              	   C  s   t  }| || tt|dp$d}| jdd d k	rlt	|slt
jt
j| jddt
j|}||d< | |jpg |d< | j||dtjtjdd d	d
dddd | j| d S )Nsrcr   relative-imagesrT  alt)r   r   r<  widthheightalignc                 S  s   t | dS )N)leftcenterright)r   choice)r	  rE   rE   rF   r_    r`  z/DocutilsRenderer.render_image.<locals>.<lambda>)r  r  r  r  r  r  )whar   )r   imager   r   rd   rE  rg   rx   rG  rH  osrA  normpathry  r   r   r   r   Z length_or_percentage_or_unitlessZlength_or_unitlessrk   r   )rb   rJ   Zimg_noderj  rE   rE   rF   render_image  s<     

zDocutilsRenderer.render_imagec              	   C  sJ   t  }| || | ||d | j|dd | | W 5 Q R X dS )zRender an inline span token.r   Tr   N)r   r   r   r   r   rT   r   rE   rE   rF   render_span  s
    zDocutilsRenderer.render_spanc              	   C  s   t |dd}t|jtrdzt|j}W qj tjjtjj	fk
r`   | j
dtj|| jd Y dS X n|j}t|ts| j
dt| tj|| jd dS dd | D }|r| j|| jjjd	}| j| |d
r| jjr| d|d
  d dS )z Pass document front matter data.r   r   zMalformed YAMLr   NzYAML is not a dict: c                 S  s   i | ]\}}|d kr||qS ))mystZmystnbsubstitutionsr   rE   rV   rE   rE   rF   rZ     s    z8DocutilsRenderer.render_front_matter.<locals>.<dictcomp>)rz   r<  z# )rO   r  r   rd   yamlZ	safe_loadrR   ZParserErrorscannerZScannerErrorr4   r3   ZMD_TOPMATTERrk   r   rr   r   dict_to_fm_field_listrj   r@   rz   r   rx   rh   Ztitle_to_headerr   )rb   rJ   positiondatafields
field_listrE   rE   rF   render_front_matter  s@    

 z$DocutilsRenderer.render_front_matterznodes.field_list)r  rz   r   r:   c           
   
   C  s  t  }| jd | |_|_t|j}| D ]\}}t|t	t
tttfsTt|}t	|}t  }| jd | |_|_||kr| | | j||dd W 5 Q R X n|t ||7 }t  }	||	_|	t |dt |7 }	|	t j|f|g 7 }	||	7 }q.|S )ai  Render each key/val pair as a docutils ``field_node``.

        Bibliographic keys below will be parsed as Markdown,
        all others will be left as literal text.

        The field list should be at the start of the document,
        and will then be converted to a `docinfo` node during the
        `docutils.docutils.transforms.frontmatter.DocInfo` transform (priority 340),
        and bibliographic keys (or their translation) will be converted to nodes::

            {'author': docutils.nodes.author,
            'authors': docutils.nodes.authors,
            'organization': docutils.nodes.organization,
            'address': docutils.nodes.address,
            'contact': docutils.nodes.contact,
            'version': docutils.nodes.version,
            'revision': docutils.nodes.revision,
            'status': docutils.nodes.status,
            'date': docutils.nodes.date,
            'copyright': docutils.nodes.copyright,
            'dedication': docutils.nodes.topic,
            'abstract': docutils.nodes.topic}

        Also, the 'dedication' and 'abstract' will be placed outside the `docinfo`,
        and so will always be shown in the document.

        If using sphinx, this `docinfo` node will later be extracted from the AST,
        by the `DoctreeReadEvent` transform (priority 880),
        calling `MetadataCollector.process_doc`.
        In this case keys and values will be converted to strings and stored in
        `app.env.metadata[app.env.docname]`

        See
        https://www.sphinx-doc.org/en/master/usage/restructuredtext/field-lists.html
        for docinfo fields used by sphinx.

        r   Tr   r   )r   r  rj   r   r   r   Zbibliographic_fieldsr   r  rd   rI   floatr   r   jsondumpsr   r   r   r  field
field_namer   
field_body)
rb   r  rz   r   r  Zbibliofieldsr   r   bodyZ
field_noderE   rE   rF   r    s&    (


z&DocutilsRenderer.dict_to_fm_field_listc              	   C  sR  |j s
t|j d }|j st|j d }|j s2tt }|d  dg7  < | ||d | || | j| t|j }d| g| }tj	t|d}||7 }|D ]}tj
|d}	||	7 }qt }
||
7 }| |
 | | W 5 Q R X t|j dkrN|j d }t }||7 }| |$ |j p0g D ]}| | q2W 5 Q R X d S )	Nr   r   zcolwidths-autor   d   )cols)colwidthr5   )r   AssertionErrorr   tabler   r   rk   r   r   tgroupcolspectheadr   render_table_rowtbody)rb   rJ   header
header_rowr  ZmaxcolsZ	colwidthsr  r  r  r  r  r  Zbody_rowrE   rE   rF   render_tableL  s8    







zDocutilsRenderer.render_tablec                 C  s   t  }| j|dd |jp g D ]}t  }t |jrD|jd jnd}|d}|r|dkr|d dt	t
|d	d
   | j|dd* | j|dd | | W 5 Q R X W 5 Q R X q"W 5 Q R X d S )NTr   r   r   r   )ztext-align:leftztext-align:rightztext-align:centerr   ztext-rl  r5   )r   rowr   r   entryr   r   rE  r   r   rd   r   rT   )rb   rJ   r  r   r  r   r   rE   rE   rF   r  t  s"    
$ z!DocutilsRenderer.render_table_rowc                 C  sZ   | j dtjt|d| jd | jtjdddd | | | jtjdddd d	S )
zRender a strikethrough token.z8Strikethrough is currently only supported in HTML outputr   r   r   z<s>r   r   z</s>N)	r4   r3   ZSTRIKETHROUGHrO   rk   r   r   r   rT   r   rE   rE   rF   render_s  s    
zDocutilsRenderer.render_sc                 C  s.   |j }t||}| || | j| d S r   r   r   mathr   rk   r   rb   rJ   r   r   rE   rE   rF   render_math_inline  s    z#DocutilsRenderer.render_math_inlinec                 C  s4   |j }tj||dd d}| || | j| d S NFnowrapnumberr   r   
math_blockr   rk   r   r  rE   rE   rF   render_math_inline_double  s    z*DocutilsRenderer.render_math_inline_doublec                 C  s.   |j }t||}| || | j| d S r   r  r  rE   rE   rF   render_math_single  s    z#DocutilsRenderer.render_math_singlec                 C  s4   |j }tj||dd d}| || | j| d S r  r  r  rE   rE   rF   render_math_block  s    z"DocutilsRenderer.render_math_blockc                 C  s`   |j }|j}tj||dd d}| || t|}|d | | j|| | j	| d S )NFr  r   )
r   r  r   r  r   r   r   rj   r   rk   )rb   rJ   r   r   r   rf   rE   rE   rF   render_math_block_label  s    
z(DocutilsRenderer.render_math_block_labelc                 C  sJ   t j|j|jddgd}|jd dkr.d|d< | || | j| d S )NTZamsmath)r  r   Znumbered*)r   r  r   r   r   rk   r   r   rE   rE   rF   render_amsmath  s       zDocutilsRenderer.render_amsmathc                 C  sx   |j d }td| d}| || | sFd|d< | j| n|t|7 }||d< | j| | j	
| dS )zdFootnote references are added as auto-numbered,
        .i.e. `[^a]` is read as rST `[#a]_`
        r   z[^]r5   rC  r   N)r   r   r   r   isdigitrj   Znote_autofootnote_refr   Znote_footnote_refrk   r   )rb   rJ   rR  r   rE   rE   rF   render_footnote_ref  s    
z$DocutilsRenderer.render_footnote_refc              	   C  s   |j d }t }| || |d | | sJd|d< | j| n|td|7 }| j	| | j
|| | j|dd | | W 5 Q R X d S )Nr   r   r5   rC  r   Tr   )r   r   footnoter   r   r  rj   Znote_autofootnoter   Znote_footnoter   r   rT   )rb   rJ   rR  r  rE   rE   rF   r     s    
z*DocutilsRenderer.render_footnote_referencec                 C  s>   t |j|j}|d  dg7  < | || | j| d S )Nr   block_break)r   commentr   r   rk   r   )rb   rJ   r  rE   rE   rF   render_myst_block_break  s    z(DocutilsRenderer.render_myst_block_breakc                 C  sT   |j }t|}t|}|d | | || | j|| j | j| d S )Nr   )	r   r   r   rR  r   r   rj   r   rk   )rb   rJ   r   rf   rR  rE   rE   rF   render_myst_target  s    

z#DocutilsRenderer.render_myst_targetc                 C  s    | j t|j|j  d S r   )rk   r   r   r  r   r'  r   rE   rE   rF   render_myst_line_comment  s    z)DocutilsRenderer.render_myst_line_commentc                 C  s   |j d }|j}d| d|j d}|jr2t|nd}t|| j|| j\}}|s| jd| dt	j
|| jd | j| d S t| }||||||\}	}
|  j|	|
 7  _d S )	Nrf   rl  z:``r   zUnknown interpreted text role "z".r   )r   r   rL   rO   r   Zrolerm   rl   r4   r3   ZUNKNOWN_ROLErk   r   r-   )rb   rJ   rf   r   Z	rawsourcer   Z	role_funcmessagesZinliner_nodesZ	messages2rE   rE   rF   render_myst_role  s,    
   
z!DocutilsRenderer.render_myst_rolec              	   C  s  |j r|j  ndjdd}|r(|d nd}t|dkr@|d nd}|dr|dr|jdr|jdk	svtd	|j	 }d
|j |_||_| 
||dd |S tjdd}| || | ||d |r|d | | j|dd | |jt|d W 5 Q R X dS )z0Render a div block, with ``:`` colon delimiters.r   r5   r  r   r!  r"  z:::Nz!"colon_fence" must have a `token`r   r#  T)Zis_divr   r   r   )r  r'  r   r   rU   r+  r   rJ   r  copyr,  r   	containerr   r   r   r   r   rO   )rb   rJ   r.  rf   r/  Zlinear_tokenr  rE   rE   rF   render_colon_fence  s"    
z#DocutilsRenderer.render_colon_fencec                 C  s  t jddgd}| ||d | || d|d ko>| jdk	}| j|dd	 d}|jp^g D ]|}|jd
kr(t  }| || | j|dd	 t 	|jr|jd j
nd}| || | | | | W 5 Q R X |rddlm} || j|jd|j|jd| jd}| j| W 5 Q R X q`|jdkr|dkrb| jjdt|d}|  j|g7  _| |> t  }	| |	| | j|	dd	 | | W 5 Q R X W 5 Q R X q`| jjd|j t|d}
|  j|
g7  _q`W 5 Q R X dS )zRender a definition list.simpler  r   r   Zglossaryr   NTr   dtr   r   )make_glossary_term)Znode_idrj   ddz?Found a definition in a definition list, with no preceding termr  zIExpected a term/definition as a child of a definition list, but found a: )r   Zdefinition_listr   r   r~   r   r   rr   Zdefinition_list_itemtermr   rT   Zsphinx.domains.stdr  r   r   rj   rk   r   rl   r8  rO   
definition)rb   rJ   r   Z
make_termsitemr   r  r  r8  r  	error_msgrE   rE   rF   	render_dl&  s\    	
 
zDocutilsRenderer.render_dlc           	   
   C  sV  t jdgd}| ||d | || | j|dd |jpBg dd }|rH|d}|jdkr| jj	d	|j t
|d
}|  j|g7  _qHt  }| || ||7 }t  }| || ||7 }| | | | W 5 Q R X t  }| || ||7 }|rL|d jdkrL|d}| | | | W 5 Q R X qLW 5 Q R X dS )zRender a field list.r  r   r   Tr   Nr   Zfieldlist_namezCExpected a fieldlist_name as a child of a field_list, but found a: r  Zfieldlist_body)r   r  r   r   r   r   r   rr   rl   r8  rO   rk   r  r  rT   r  )	rb   rJ   r  r   r   r  r  r  r  rE   rE   rF   render_field_lista  s:    



z"DocutilsRenderer.render_field_listc                 C  sx   t  }| jd |d< | jj|_| j|_dt| |j }t || |D ]}|d rJ| j|| qJ| j	
|j dS )z4Render the content of the token as restructuredtext.r   r   r   N)rG   rj   r@   rl   rO   r   r.   r   r   rk   r   r   )rb   rJ   ZnewdocZpseudosourcer   rE   rE   rF   r*    s    
z(DocutilsRenderer.render_restructuredtextr$  )rJ   rf   r/  r%  r:   c                C  s0   t |}| j|||j||d}|  j|7  _dS )zRender special fenced code blocks as directives.

        :param token: the token to render
        :param name: the name of the directive
        :param arguments: The remaining text on the same line as the directive name.
        r$  N)rO   run_directiver   rk   )rb   rJ   rf   r/  r%  r  Z
nodes_listrE   rE   rF   r,    s    z!DocutilsRenderer.render_directive)rf   
first_liner   r  r%  r:   c                 C  s  || j _t|| j| j }|\}}|sP| jd|tj|d}	|	rH|	gng | S t|t	r~tj
|jd< tj|jd< tj|jd< zt|||||d}
W nH tk
r } z*| jjd| d| |d}|g W Y S d	}~X Y nX |
jD ]8}| j|d
|j |j|jd	k	r|jn|| jd qt|t	rHt| |||
j|
j|
j|d}nLt| |}t| ||}|||
j|
jt|
j| j d ||
jd|
j||d	}z|  }W n t!k
r } z0| jj"|j#|j|d}|t$%||7 }|g}W 5 d	}~X Y n^ t&k
rL } z>| jjd| d|j'j( d
| t$%|||d}|g W Y S d	}~X Y nX t)|t*sjt+d| dt,t-|D ]6}t)|| t$j.svt+d| d| d||  qv|S )a  Run a directive and return the generated nodes.

        :param name: the name of the directive
        :param first_line: The text on the same line as the directive name.
            May be an argument or body text, dependent on the directive
        :param content: All text after the first line. Can include options.
        :param position: The line number of the first line
        :param additional_options: Additional options to add to the directive,
            above those parsed from the content.

        zUnknown directive type: r  r  zrelative-docszheading-offset)r   r%  zDirective 'z': Nru  r   )rf   klassr/  rv   r  r   r   r   )	rf   r/  rv   r   r   Zcontent_offsetZ
block_textstatestate_machinez' cannot be mocked: zDirective "z" must return a list of nodes.z"" returned non-Node object (index z): )/rj   current_liner   	directiverm   r4   r3   ZUNKNOWN_DIRECTIVE
issubclassr   flagZoption_specrA  Znonnegative_intr2   r1   rl   r8  warningsr   rr   r   rk   r+   r/  rv   r  r0   r/   r   Zbody_offsetry  runr   Zsystem_messager   r   literal_blockr,   	__class__rs   r  r   r  ranger   Node)rb   rf   r  r   r  r%  outputZdirective_classr  Z	warn_noder^  r8  Z_warningZdirective_instancer  r  r   Zmsg_noder  r  r  rE   rE   rF   r    s      





  
 
 zDocutilsRenderer.run_directivec                 C  s   | j |dd dS )z#Render inline substitution {{key}}.Tr   Nrender_substitutionr   rE   rE   rF   render_substitution_inline(  s    z+DocutilsRenderer.render_substitution_inlinec                 C  s   | j |dd dS )z"Render block substitution {{key}}.Fr   Nr  r   rE   rE   rF   render_substitution_block,  s    z*DocutilsRenderer.render_substitution_block)rJ   r   r:   c              
   C  sn  t |}| jj}| jdk	r&| j|d< tjtjd}z|d|j d	|}W nN t
k
r } z0| jd|jj d| tj|| jd W Y dS d}~X Y nX |d|j d}d	d
 |tjjD }	t| jdt | j_|	| jj}
|
r| jd|
 tj|| jd dS | jj|	 z4|rJt|sJ| j||dd n| || W 5 | jj|	 X dS )a  Substitutions are rendered by:

        1. Combining global substitutions with front-matter substitutions
           to create a variable context (front-matter takes priority)
        2. Add the sphinx `env` to the variable context (if available)
        3. Create the string content with Jinja2 (passing it the variable context)
        4. If the substitution is inline and not a directive,
           parse to nodes ignoring block syntaxes (like lists or block-quotes),
           otherwise parse to nodes with all syntax rules.

        Nrw   )Z	undefinedz{{z}}zSubstitution error:ru  r   c                 S  s   h | ]}|j d kr|j qS )rw   re   )rW   nrE   rE   rF   	<setcomp>V  s    
 z7DocutilsRenderer.render_substitution.<locals>.<setcomp>sub_referencesz!circular substitution reference: Tr   )rO   rh   r  r~   jinja2EnvironmentZStrictUndefinedZfrom_stringr   r   r6  r4   r  rs   r3   ZSUBSTITUTIONrk   r   Zfind_allr   NamerM   rj   setr  intersectionupdatedifference_updateREGEX_DIRECTIVE_STARTrH  r   )rb   rJ   r   r  Zvariable_contextrw   renderedr8  astZ
referencesZcyclicrE   rE   rF   r  0  sJ    


	z$DocutilsRenderer.render_substitution)FNr   )F)r   )N)r   )N)Urs   
__module____qualname____doc__Z
__output__rc   rt   r|   propertyr~   r4   r   r   r   r   r   r   r   rT   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  staticmethodr  r   r  r  r  r0  r1  r9  r=  rO  rD  rK  rL  rF  rM  rJ  rx  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r*  r,  r  r  r  r  rE   rE   rE   rF   rP   d   s   (L   2  -#	 S3
.4. @
V%%* A(
	;% zrP   ru   r   z*list[nodes.pending | nodes.system_message])r  rj   r   rl   r:   c                 C  sT  | sg S g }|   D ]8\}}t|p&d}t|}|d |_||_||d< z|sZtdt| D ]j\}	}
d|
kr|	dkr|
|d< qfd|
krtd|
 |
dd	\}}|r|std
|
 |||	 < qfW nN tk
r" } z.|
d| d| d}|| W Y qW 5 d}~X Y nX ttdd|gd}|| || q|S )zReplicate the `meta` directive,
    by converting a dictionary to a list of pending meta nodes

    See:
    https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#html-metadata
    r   r   r   z
No content=r   rf   z
no '=' in r5   z
malformed z"Error parsing meta tag attribute "z": .Nwriterr   )	componentr   r   )r   rd   r   r   r   r   rN   	enumerater   lowerr8  r   pendingr   Znote_pending)r  rj   r   rl   r  r   r   r   Z	meta_noder  key_part	attr_nameZattr_valr8  r   r  rE   rE   rF   r   u  sB    	



r   r   rd   )r   r:   c                 C  sP   |   } t| tjD ]}d|d< qtt| tjD ]}|j| q6|  S )zCLike node.astext(), but ignore images.
    Copied from sphinx.
    r   r  )	deepcopyr(   r   r  r   r   r   removeZastext)r   Zimgr   rE   rE   rF   r4    s    
r4  z[^\w\u4e00-\u9fff\- ])r<  r:   c                 C  s   t d|  ddS )zDefault slugify function.

    This aims to mimic the GitHub Markdown format, see:

    - https://github.com/jch/html-pipeline/blob/master/lib/html/pipeline/toc_filter.rb
    - https://gist.github.com/asabaylus/3071099
    r   rv  -)_SLUGIFY_CLEAN_REGEXre  r  replace)r<  rE   rE   rF   default_slugify  s    r  zIterable[str]zNone | Callable[[str], str])
token_treeslugs	slug_funcr:   c                 C  sj   |dkrt n|}|  }|d }ddd |jp2g D }||}d}||krf| d| }|d7 }qF|S )zkCompute the slug for a token.

    This directly mirrors the logic in `mdit_py_plugins.anchors_plugin`
    Nr5   r   c                 s  s   | ]}|j d kr|jV  qdS ))r   Zcode_inlineN)rr   r   )rW   r   rE   rE   rF   r     s   
z&compute_unique_slug.<locals>.<genexpr>r  )r  Z	to_tokensry  r   )r  r  r  r   Zinline_tokenr<  r3  r  rE   rE   rF   r5    s    	

r5  )N)N)fr  
__future__r   r]   r  r  r{  rd  collectionsr   
contextlibr   r   r   r   typesr   typingr	   r
   r   r   r   r   r   r   urllib.parser   rA   r  r  r   Zdocutils.languagesr   Zdocutils.parsers.rstr   r   r   r   r   Z	RSTParserZ$docutils.parsers.rst.directives.miscr   Zdocutils.parsers.rst.languagesry   Zdocutils.statemachiner   Zdocutils.transforms.componentsr   Zdocutils.utilsr   r   r   Zdocutils.utils.code_analyzerr   r    r!   Zmarkdown_itr"   Zmarkdown_it.common.utilsr#   Zmarkdown_it.rendererr$   Zmarkdown_it.tokenr%   Zmarkdown_it.treer&   Zmyst_parserr'   Zmyst_parser._compatr(   Zmyst_parser.config.mainr)   r*   Zmyst_parser.mockingr+   r,   r-   r.   r/   r0   Zmyst_parser.parsers.directivesr1   r2   Zmyst_parser.warnings_r3   r4   r6   Zsphinx.environmentr7   rG   compilerG  rf  r   rO   rP   r   r4  r  r  r5  rE   rE   rE   rF   <module>   s   (
 

	              0
 