o
    Ni7X                  	   @   s  d Z 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m	Z	 z+e
  ed e d p8e d Ze ZW d   n1 sGw   Y  W n   dZY zee W n eefyh   dZY nw G dd deZG d	d
 d
eZdd Zdd ZG dd de	ZG dd de	ZG dd dZG dd deZG dd deZG dd deZG dd deZG dd deZG dd  d eZ G d!d" d"eZ!G d#d$ d$eZ"dS )%z
I/O classes provide a uniform API for low-level input and output.  Subclasses
exist for a variety of input/output mechanisms.
reStructuredText    N)TransformSpecignore   c                   @      e Zd ZdS )
InputErrorN__name__
__module____qualname__ r   r   ?/home/ubuntu/.local/lib/python3.10/site-packages/docutils/io.pyr   +       r   c                   @   r   )OutputErrorNr   r   r   r   r   r   ,   r   r   c              
   C   s4   zt | jt |kW S  tttfy   Y dS w )aN  Test, whether the encoding of `stream` matches `encoding`.

    Returns

    :None:  if `encoding` or `stream.encoding` are not a valid encoding
            argument (e.g. ``None``) or `stream.encoding is missing.
    :True:  if the encoding argument resolves to the same value as `encoding`,
    :False: if the encodings differ.
    N)codecslookupencodingLookupErrorAttributeError	TypeError)streamr   r   r   r   check_encoding/   s
   
r   c                 C   s   | j j d|  S )z5Return string representation of Exception `err`.
    z: )	__class__r	   )errr   r   r   error_string?   s   r   c                   @   s   e Zd ZdZdZdZ		dddZdd Zd	d
 Zdd Z	e
dZ	 ejdfejdfejdfejdfejdffZ	 dd Zdd ZdS )Inputah  
    Abstract base class for input wrappers.

    Docutils input objects must provide a `read()` method that
    returns the source, typically as `str` instance.

    Inheriting `TransformSpec` allows input objects to add
    "transforms" and "unknown_reference_resolvers" to the "Transformer".
    (Optional for custom input objects since Docutils 0.19.)
    inputNstrictc                 C   s6   || _ 	 || _	 || _	 || _	 |s| j| _d | _d S N)r   error_handlersourcesource_pathdefault_source_pathsuccessful_encoding)selfr    r!   r   r   r   r   r   __init__U   s   zInput.__init__c                 C      d| j | j| jf S )Nz%s: source=%r, source_path=%r)r   r    r!   r$   r   r   r   __repr__i   s   
zInput.__repr__c                 C      t )z,Return input as `str`. Define in subclasses.NotImplementedErrorr'   r   r   r   readm      z
Input.readc           	      C   s  | j r| j  dkrt|tsJ dt|tr|S | j r"| j g}n!| |}|r-|g}ndg}tjdd}|rC| dkrC|| |D ]'}zt||| j}|| _	|W   S  t
tfyl } z|}W Y d}~qEd}~ww t
ddd	d
 |D  dt| d)a  
        Decode `data` if required.

        Return Unicode `str` instances unchanged (nothing to decode).

        If `self.encoding` is None, determine encoding from data
        or try UTF-8 and the locale's preferred encoding.
        The client application should call ``locale.setlocale()`` at the
        beginning of processing::

            locale.setlocale(locale.LC_ALL, '')

        Raise UnicodeError if unsuccessful.

        Provisional: encoding detection will be removed in Docutils 1.0.
        unicodez;input encoding is "unicode" but `data` is no `str` instancezutf-8F)do_setlocaleNz=Unable to decode input data.  Tried the following encodings: z, c                 s   s    | ]}t |V  qd S r   )repr).0encr   r   r   	<genexpr>   s    zInput.decode.<locals>.<genexpr>.
())r   lower
isinstancestrdetermine_encoding_from_datalocalegetpreferredencodingappendr   r#   UnicodeErrorr   joinr   )	r$   dataencoding_candidatesdata_encodingfallbackr2   decodedr   errorr   r   r   decodeq   s:   




zInput.decodes   coding[:=]\s*([-\w.]+)zutf-32z	utf-8-sigzutf-16c                 C   s`   | j D ]\}}||r|  S q| dd D ]}| j|}|r-|dd  S qdS )z
        Try to determine the encoding of `data` by looking *in* `data`.
        Check for a byte order mark (BOM) or an encoding declaration.
        N   r   ascii)byte_order_marks
startswith
splitlinescoding_slugsearchgrouprE   )r$   r?   start_bytesr   linematchr   r   r   r9      s   
z"Input.determine_encoding_from_datac                 C   "   z| j  W S  ty   Y dS w )z>Return True, if the input source is connected to a TTY device.F)r    isattyr   r'   r   r   r   rR      
   zInput.isattyNNNr   )r	   r
   r   __doc__component_typer"   r%   r(   r,   rE   recompilerK   r   BOM_UTF32_BEBOM_UTF32_LEBOM_UTF8BOM_UTF16_BEBOM_UTF16_LErH   r9   rR   r   r   r   r   r   E   s*    

6r   c                   @   s>   e Zd ZdZdZdZ		dddZdd Zd	d
 Zdd Z	dS )Outputak  
    Abstract base class for output wrappers.

    Docutils output objects must provide a `write()` method that
    expects and handles one argument (the output).

    Inheriting `TransformSpec` allows output objects to add
    "transforms" and "unknown_reference_resolvers" to the "Transformer".
    (Optional for custom output objects since Docutils 0.19.)
    outputNr   c                 C   s8   || _ 	 |pd| _	 || _	 || _	 |s| j| _d S d S )Nr   )r   r   destinationdestination_pathdefault_destination_path)r$   r`   ra   r   r   r   r   r   r%      s   
zOutput.__init__c                 C   r&   )Nz'%s: destination=%r, destination_path=%r)r   r`   ra   r'   r   r   r   r(      s   zOutput.__repr__c                 C   r)   )z#Write `data`. Define in subclasses.r*   r$   r?   r   r   r   write   r-   zOutput.writec                 C   sH   | j r| j  dkrt|tsJ d|S t|ts|S || j | jS )a?  
        Encode and return `data`.

        If `data` is a `bytes` instance, it is returned unchanged.
        Otherwise it is encoded with `self.encoding`.

        Provisional: If `self.encoding` is set to the pseudo encoding name
        "unicode", `data` must be a `str` instance and is returned unchanged.
        r.   z<output encoding is "unicode" but `data` is no `str` instance)r   r6   r7   r8   encoder   rc   r   r   r   re      s   

zOutput.encoderT   )
r	   r
   r   rU   rV   rb   r%   r(   rd   re   r   r   r   r   r^      s    
r^   c                   @   s8   e Zd ZdZ			dddZdd Zd	d
 Zdd ZdS )ErrorOutputz
    Wrapper class for file-like error streams with
    failsafe de- and encoding of `str`, `bytes`, `unicode` and
    `Exception` instances.
    Nbackslashreplacereplacec                 C   sd   |du rt j}n|sd}n
t|trt|d}|| _	 |p&t|ddp&tp&d| _	 || _		 || _
dS )a  
        :Parameters:
            - `destination`: a file-like object,
                        a string (path to a file),
                        `None` (write to `sys.stderr`, default), or
                        evaluating to `False` (write() requests are ignored).
            - `encoding`: `destination` text encoding. Guessed if None.
            - `encoding_errors`: how to treat encoding errors.
        NFwr   rG   )sysstderrr7   r8   openr`   getattr_locale_encodingr   encoding_errorsdecoding_errors)r$   r`   r   ro   rp   r   r   r   r%     s$   

zErrorOutput.__init__c              	   C   s   | j sdS t|trt|}z	| j | W dS  ty-   | j || j| j Y dS  t	yi   t|trG| j || j| j Y dS | j t
jt
jfv rZ| j j| Y dS | j t|| j| j Y dS w )z
        Write `data` to self.destination. Ignore, if self.destination is False.

        `data` can be a `bytes`, `str`, or `Exception` instance.
        N)r`   r7   	Exceptionr8   rd   UnicodeEncodeErrorre   r   ro   r   rj   rk   stdoutbufferrp   rc   r   r   r   rd   2  s*   

zErrorOutput.writec                 C   s<   | j tjtjfv rdS z| j   W dS  ty   Y dS w )z
        Close the error-output stream.

        Ignored if the destination is` sys.stderr` or `sys.stdout` or has no
        close() method.
        N)r`   rj   rs   rk   closer   r'   r   r   r   ru   L  s   zErrorOutput.closec                 C   rQ   )z=Return True, if the destination is connected to a TTY device.F)r`   rR   r   r'   r   r   r   rR   Z  rS   zErrorOutput.isatty)NNrg   rh   )r	   r
   r   rU   r%   rd   ru   rR   r   r   r   r   rf   
  s    
!rf   c                   @   s8   e Zd ZdZ			dddZdd	 Zd
d Zdd ZdS )	FileInputz5
    Input for single, simple file-like objects.
    Nr   Trc              
   C   s   t | |||| || _t | _|du r=|r8zt||| j| jd| _W n- t	y7 } zt
|j|j|d}~ww tj| _nt| j| jdu rQtd| j| jjf |sfz| jj| _W dS  tye   Y dS w dS )a  
        :Parameters:
            - `source`: either a file-like object (which is read directly), or
              `None` (which implies `sys.stdin` if no `source_path` given).
            - `source_path`: a path to a file, which is opened for reading.
            - `encoding`: the expected text encoding of the input file.
            - `error_handler`: the encoding error handler to use.
            - `autoclose`: close automatically after read (except when
              `sys.stdin` is the source).
            - `mode`: how the file is to be opened (see standard function
              `open`). The default is read only ('r').
        Nr   errorsFzOEncoding clash: encoding given is "%s" but source is opened with encoding "%s".)r   r%   	autocloserf   _stderrrl   r   r   r    OSErrorr   errnostrerrorrj   stdinr   r=   namer!   r   )r$   r    r!   r   r   rz   moderD   r   r   r   r%   g  s4   
zFileInput.__init__c                 C   sp   z.| j s t| jdr | jj }| |}d| dg }n| j }W | jr-| 	  |S | jr7| 	  w w )zA
        Read and decode a single file, return as `str`.
        rt   
 )
r   hasattrr    rt   r,   rE   r>   rJ   rz   ru   rc   r   r   r   r,     s   


zFileInput.readc                 C   s   |   dS )zC
        Return lines of a single file as list of strings.
        T)r,   rJ   r'   r   r   r   	readlines  s   zFileInput.readlinesc                 C   s   | j tjur| j   d S d S r   )r    rj   r   ru   r'   r   r   r   ru     s   zFileInput.close)NNNr   Trw   )r	   r
   r   rU   r%   r,   r   ru   r   r   r   r   rv   b  s    
(rv   c                   @   sB   e Zd ZdZdZdZ	 			dddZd	d
 Zdd Zdd Z	dS )
FileOutputz,Output for single, simple file-like objects.z<file>ri   Nr   Tc                 C   s   t | |||| d| _|| _|durtjdtdd |dur"|| _t | _	|du r5|r0d| _n t
j| _n|rPt| jdrP|| jjkrPtd| jj|f | j	d	 |sez| jj| _W dS  tyd   Y dS w dS )
aA  
        :Parameters:
            - `destination`: either a file-like object (which is written
              directly) or `None` (which implies `sys.stdout` if no
              `destination_path` given).
            - `destination_path`: a path to a file, which is opened and then
              written.
            - `encoding`: the text encoding of the output file.
            - `error_handler`: the encoding error handler to use.
            - `autoclose`: close automatically after write (except when
              `sys.stdout` or `sys.stderr` is the destination).
            - `handle_io_errors`: ignored, deprecated, will be removed.
            - `mode`: how the file is to be opened (see standard function
              `open`). The default is 'w', providing universal newline
              support for text files.
        TNz_io.FileOutput: init argument "handle_io_errors" is ignored and will be removed in Docutils 2.0.rF   )
stacklevelFr   z?Warning: Destination mode "%s" differs from specified mode "%s")file)r^   r%   openedrz   warningswarnDeprecationWarningr   rf   r{   rj   rs   r`   r   printr   ra   r   )r$   r`   ra   r   r   rz   handle_io_errorsr   r   r   r   r%     sB   



zFileOutput.__init__c              
   C   sp   d| j vr| j| jd}ni }zt| j| j fi || _W n ty2 } z	t|j|j	| jd }~ww d| _
d S )Nbrx   T)r   r   r   rl   ra   r`   r|   r   r}   r~   r   )r$   kwargsrD   r   r   r   rl     s   


zFileOutput.openc                 C   sF  | j s|   t|tr&t| j| jdu r&tjdkr!|	dtj}| 
|}zsz| j| W n` tyt } z9t|trjz	| jj| W n$ tyi   t| j| jdu rgtd| j d| jj d| j d|w W Y d}~n d}~w ttfy } ztd| j d	t| dd}~ww W | jr|   |S | jr|   w w )
aB  Write `data` to a single file, also return it.

        `data` can be a `str` or `bytes` instance.
        If writing `bytes` fails, an attempt is made to write to
        the low-level interface ``self.destination.buffer``.

        If `data` is a `str` instance and `self.encoding` and
        `self.destination.encoding` are  set to different values, `data`
        is encoded to a `bytes` instance using `self.encoding`.

        Provisional: future versions may raise an error if `self.encoding`
        and `self.destination.encoding` are set to different values.
        Fr   zEncoding of z (z&) differs 
  from specified encoding (r5   Nz2Unable to encode output data. output-encoding is: r4   )r   rl   r7   r8   r   r`   r   oslineseprh   re   rd   r   bytesrt   r   
ValueErrorra   r=   r   r   rz   ru   )r$   r?   r   r   r   r   rd     s\   




	
zFileOutput.writec                 C   s*   | j tjtjfvr| j   d| _d S d S )NF)r`   rj   rs   rk   ru   r   r'   r   r   r   ru   $  s   

zFileOutput.close)NNNr   TNN)
r	   r
   r   rU   rb   r   r%   rl   rd   ru   r   r   r   r   r     s    
/.r   c                   @   s   e Zd ZdZdZdS )BinaryFileOutputzL
    A version of docutils.io.FileOutput which writes to a binary file.
    wbN)r	   r
   r   rU   r   r   r   r   r   r   *  s    r   c                   @      e Zd ZdZdZdd ZdS )StringInputz'Input from a `str` or `bytes` instance.<string>c                 C   s   |  | jS )z`Return the source as `str` instance.

        Decode, if required (see `Input.decode`).
        )rE   r    r'   r   r   r   r,   8  s   zStringInput.readNr	   r
   r   rU   r"   r,   r   r   r   r   r   3  s    r   c                   @   r   )StringOutputz=Output to a `bytes` or `str` instance.

    Provisional.
    r   c                 C   s   |  || _| jS )av  Store `data` in `self.destination`, and return it.

        If `self.encoding` is set to the pseudo encoding name "unicode",
        `data` must be a `str` instance and is stored/returned unchanged
        (cf. `Output.encode`).

        Otherwise, `data` can be a `bytes` or `str` instance and is
        stored/returned as a `bytes` instance
        (`str` data is encoded with `self.encode()`).

        Attention: the `output_encoding`_ setting may affect the content
        of the output (e.g. an encoding declaration in HTML or XML or the
        representation of characters as LaTeX macro vs. literal character).
        )re   r`   rc   r   r   r   rd   H  s   zStringOutput.writeNr	   r
   r   rU   rb   rd   r   r   r   r   r   @  s    r   c                   @   r   )	NullInputzDegenerate input: read nothing.z
null inputc                 C      dS )zReturn an empty string.r   r   r'   r   r   r   r,   a  r-   zNullInput.readNr   r   r   r   r   r   [      r   c                   @   r   )
NullOutputz!Degenerate output: write nothing.znull outputc                 C   r   )zDo nothing, return None.Nr   rc   r   r   r   rd   l  r-   zNullOutput.writeNr   r   r   r   r   r   f  r   r   c                   @   r   )DocTreeInputzm
    Adapter for document tree input.

    The document tree must be passed in the ``source`` parameter.
    zdoctree inputc                 C   s   | j S )zReturn the document tree.)r    r'   r   r   r   r,   {  s   zDocTreeInput.readNr   r   r   r   r   r   q  s    r   )#rU   __docformat__r   r:   r   rW   rj   r   docutilsr   catch_warningssimplefilter	getlocalegetdefaultlocalern   r6   r   r   r   r|   r   r   r   r   r   r^   rf   rv   r   r   r   r   r   r   r   r   r   r   r   <module>   sR   	



 >XK}	