a
    `a\#                     @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	d>ddZ
d?ddZdd Zd	d
 Zdd Zdd Zdd Zd@ddZdd Zdd Zdd ZeddZeddZeddZeddZed dZed!dZed"dZed#dZed$d%Zed&dZed'd(Zed)dZ ed*dZ!ed+dZ"ed,dZ#ed-dZ$ed.dZ%ed/dZ&ed0dZ'ed1dZ(ed2dZ)ed3dZ*ed4dZ+ed5dZ,ed6dZ-ed7dZ.ed8dZ/ed9d%Z0ed:d%Z1ed;dZ2ed<dZ3ed=dZ4dS )AzY
Functions to aid writing python scripts that process the pandoc
AST serialized as JSON.
    Nc                    s   t dr*tj| d t fdd n| d  t|t	
  }z"t   t	jd  d  W n& ty   t	jd  d	  Y n0 |r|d
| 7 }t j |S )a  Generate filename based on content

    The function ensures that the (temporary) directory exists, so that the
    file can be written.

    By default, the directory won't be cleaned up,
    so a filter can use the directory as a cache and
    decide not to regenerate if there's no change.

    In case the user preferres the files to be temporary files,
    an environment variable `PANDOCFILTER_CLEANUP` can be set to
    any non-empty value such as `1` to
    make sure the directory is created in a temporary location and removed
    after finishing the filter. In this case there's no caching and files
    will be regenerated each time the filter is run.

    Example:
        filename = get_filename4code("myfilter", code)
    ZPANDOCFILTER_CLEANUP)prefixc                      s
   t  S )N)shutilrmtree Zimagedirr   ,lib/python3.9/site-packages/pandocfilters.py<lambda>.       z#get_filename4code.<locals>.<lambda>z-imageszCreated directory 
zCould not create directory "z"
.)osgetenvtempfileZmkdtempatexitregisterhashlibZsha1encodesysgetfilesystemencodingZ	hexdigestmkdirstderrwriteOSErrorpathjoin)moduleZcontentextfnr   r   r   get_filename4code   s    

r   c                 C   s6   g }| D ]$\}}||kr|}q| ||g q||fS )z&get value from the keyvalues (options)append)kvkeyvaluereskvr   r   r   	get_value;   s    r'   c                 C   s6   g }d}t | d\}}|dur,t|g}d}|||fS )a  get caption from the keyvalues (options)

    Example:
      if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        caption, typef, keyvals = get_caption(keyvals)
        ...
        return Para([Image([ident, [], keyvals], caption, [filename, typef])])
     captionNzfig:)r'   Str)r!   r)   Ztypefr#   r$   r   r   r   get_captionE   s    

r+   c                 K   s&   z
||  W S  t y    | Y S 0 dS )zget the extension for the result, needs a default and some specialisations

    Example:
      filetype = get_extension(format, "png", html="svg", latex="eps")
    N)KeyError)formatdefaultZ
alternatesr   r   r   get_extensionY   s    
r/   c              	      s   t | trg }| D ]}t |trd|v r |d d|v r@|d nd}|du rh|t|  qt |tr|D ]}|t|  qvq|t|  q|t|  q|S t | tr fdd|  D S | S dS )a  Walk a tree, applying an action to every object.
    Returns a modified tree.  An action is a function of the form
    `action(key, value, format, meta)`, where:

    * `key` is the type of the pandoc object (e.g. 'Str', 'Para') `value` is
    * the contents of the object (e.g. a string for 'Str', a list of
      inline elements for 'Para')
    * `format` is the target output format (as supplied by the
      `format` argument of `walk`)
    * `meta` is the document's metadata

    The return of an action is either:

    * `None`: this means that the object should remain unchanged
    * a pandoc object: this will replace the original object
    * a list of pandoc objects: these will replace the original object; the
      list is merged with the neighbors of the orignal objects (spliced into
      the list the original object belongs to); returning an empty list deletes
      the object
    tcNc                    s    i | ]\}}|t | qS r   )walk).0r%   r&   actionr-   metar   r   
<dictcomp>   r	   zwalk.<locals>.<dictcomp>)
isinstancelistdictr    r2   items)xr5   r-   r6   Zarrayitemr$   zr   r4   r   r2   g   s$    


r2   c                 C   s   t | g dS )zALike `toJSONFilters`, but takes a single action as argument.
    N)toJSONFilters)r5   r   r   r   toJSONFilter   s    r@   c                 C   sx   zt jtjjdd}W n" ty8   tdtj}Y n0 | }t	tj
dkr\tj
d }nd}tjt| || dS )aY  Generate a JSON-to-JSON filter from stdin to stdout

    The filter:

    * reads a JSON-formatted pandoc document from stdin
    * transforms it by walking the tree and performing the actions
    * returns a new JSON-formatted pandoc document to stdout

    The argument `actions` is a list of functions of the form
    `action(key, value, format, meta)`, as described in more
    detail under `walk`.

    This function calls `applyJSONFilters`, with the `format`
    argument provided by the first command-line argument,
    if present.  (Pandoc sets this by default when calling
    filters.)
    zutf-8)encoding   r(   N)ioTextIOWrapperr   stdinbufferAttributeErrorcodecs	getreaderreadlenargvstdoutr   applyJSONFilters)actionsZinput_streamsourcer-   r   r   r   r?      s    r?   r(   c                 C   s\   t |}d|v r|d }n|d r2|d d }ni }|}| D ]}t||||}q>t |S )a  Walk through JSON structure and apply filters

    This:

    * reads a JSON-formatted pandoc document from a source string
    * transforms it by walking the tree and performing the actions
    * returns a new JSON-formatted pandoc document as a string

    The `actions` argument is a list of functions (see `walk`
    for a full description).

    The argument `source` is a string encoded JSON object.

    The argument `format` is a string describing the output format.

    Returns a the new JSON-formatted pandoc document.
    r6   r   ZunMeta)jsonloadsr2   dumps)rO   rP   r-   docr6   Zalteredr5   r   r   r   rN      s    

rN   c                    s(   g   fdd}t | |di  d S )z^Walks the tree x and returns concatenated string content,
    leaving out all formatting.
    c                    s   | dv r  | nj| dkr,  |d  nR| dkrD  |d  n:| dkrX  d n&| dkrl  d n| dkr~  d d S )	N)r*   Z
MetaStringCoderB   Math	LineBreak 	SoftBreakSpacer   )r"   valr-   r6   resultr   r   go   s    zstringify.<locals>.gor(   )r2   r   )r<   r^   r   r\   r   	stringify   s    r_   c                    s<    pi    dd}  dg } fdd D }|||gS )zJReturns an attribute list, constructed from the
    dictionary attrs.
    idr(   classesc                    s(   g | ] }|d kr|dkr| | gqS )ra   r`   r   )r3   r<   attrsr   r   
<listcomp>   r	   zattributes.<locals>.<listcomp>)get)rc   identra   Zkeyvalsr   rb   r   
attributes   s
    rg   c                    s    fdd}|S )Nc                     sf   t | }|kr0t d t d t| dkr>g }nt | dkrT| d }nt| } |dS )Nz	 expects z arguments, but given r   rB   )r0   r1   )rK   
ValueErrorstrr9   )argsZlenargsZxseltTypenumargsr   r   fun   s    
zelt.<locals>.funr   )rl   rm   rn   r   rk   r   elt   s    ro   PlainrB   Para	CodeBlock   RawBlock
BlockQuoteOrderedList
BulletListDefinitionListHeader   HorizontalRuleTable   DivNullr*   EmphStrong	StrikeoutSuperscript	Subscript	SmallCapsQuotedCiterU   rZ   rW   rV   	RawInlineLinkImageNoterY   Span)N)N)r(   )5__doc__rH   r   rC   rQ   r   r   r   r   r   r   r'   r+   r/   r2   r@   r?   rN   r_   rg   ro   rp   rq   rr   rt   ru   rv   rw   rx   ry   r{   r|   r~   r   r*   r   r   r   r   r   r   r   r   rU   rZ   rW   rV   r   r   r   r   rY   r   r   r   r   r   <module>   sh   
#

*!
"






























