U
    Oe]                  
   @   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	 zBe
 0 ed e d ppe d Ze ZW 5 Q R X W nD ek
r Z zdejkrdZndZW 5 dZ[X Y n   dZY nX zee W n eefk
r   dZY nX 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.
ZreStructuredText    N)TransformSpecignore   zunknown locale: UTF-8utf-8c                   @   s   e Zd ZdS )
InputErrorN__name__
__module____qualname__ r   r   //tmp/pip-unpacked-wheel-rro3auwd/docutils/io.pyr   3   s    r   c                   @   s   e Zd ZdS )OutputErrorNr   r   r   r   r   r   4   s    r   c              
   C   s:   zt | jt |kW S  tttfk
r4   Y dS X dS )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_encoding7   s    
r   c                 C   s   | j j d|  S )z5Return string representation of Exception `err`.
    z: )	__class__r   )errr   r   r   error_stringG   s    r   c                   @   sp   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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   s.   || _ || _|| _|| _|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__]   s    zInput.__init__c                 C   s   d| j | j| jf S )Nz%s: source=%r, source_path=%r)r   r   r   r"   r   r   r   __repr__q   s    
zInput.__repr__c                 C   s   t dS )z,Return input as `str`. Define in subclasses.NNotImplementedErrorr$   r   r   r   readu   s    z
Input.readc                 C   s
  | j r&| j  dkr&t|ts&tdt|tr4|S | j rD| j g}n<| |}|rZ|g}n&dg}trvtdkrv|t |d |D ]V}z&t||| j}|| _	|
ddW   S  ttfk
r } z|}W 5 d}~X Y qX qtdd	d
d |D  dt| ddS )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, locale encoding, and (as last ressort) 'latin-1'.
        The client application should call ``locale.setlocale`` at the
        beginning of processing::

            locale.setlocale(locale.LC_ALL, '')

        Raise UnicodeError if unsuccessful.

        Provisional:
          - Raise UnicodeError (instead of falling back to the locale
            encoding) if decoding the source with the default encoding (UTF-8)
            fails and Python is started in `UTF-8 mode`.

            Raise UnicodeError (instead of falling back to "latin1") if both,
            default and locale encoding, fail.

          - Only remove BOM (U+FEFF ZWNBSP at start of data),
            no other ZWNBSPs.
        unicodez;input encoding is "unicode" but `data` is no `str` instancer   zlatin-1u   ﻿ Nz=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AssertionErrordetermine_encoding_from_data_locale_encodingappendr   r!   replaceUnicodeErrorr   joinr   )r"   dataZencoding_candidatesdata_encodingr-   decodedr   errorr   r   r   decodey   s.    




$zInput.decodes   coding[:=]\s*([-\w.]+)r   z	utf-16-bez	utf-16-lec                 C   s`   | j D ]\}}||r|  S q| dd D ](}| j|}|r2|dd  S q2d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groupr?   )r"   r;   Zstart_bytesr   linematchr   r   r   r5      s    

z"Input.determine_encoding_from_datac                 C   s(   z| j  W S  tk
r"   Y dS X dS )z>Return True, if the input source is connected to a TTY device.FN)r   isattyr   r$   r   r   r   rJ      s    zInput.isatty)NNNr   )r   r	   r
   __doc__component_typer    r#   r%   r(   r?   recompilerE   r   BOM_UTF8BOM_UTF16_BEBOM_UTF16_LErB   r5   rJ   r   r   r   r   r   M   s      
F
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   s,   || _ |pd| _|| _|| _|s(| j| _d S )Nr   )r   r   destinationdestination_pathdefault_destination_path)r"   rT   rU   r   r   r   r   r   r#      s    
zOutput.__init__c                 C   s   d| j | j| jf S )Nz'%s: destination=%r, destination_path=%r)r   rT   rU   r$   r   r   r   r%     s    zOutput.__repr__c                 C   s   t dS )z#Write `data`. Define in subclasses.Nr&   r"   r;   r   r   r   write  s    zOutput.writec                 C   sL   | j r*| j  dkr*t|ts&td|S t|ts8|S || j | jS d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` instanceN)r   r1   r2   r3   r4   encoder   rW   r   r   r   rY   
  s    

zOutput.encode)NNNr   )
r   r	   r
   rK   rL   rV   r#   r%   rX   rY   r   r   r   r   rR      s       
rR   c                   @   s2   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backslashreplacer8   c                 C   s^   |dkrt j}n|sd}nt|tr.t|d}|| _|pJt|ddpJtpJd| _|| _	|| _
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   rA   )sysstderrr2   r3   openrT   getattrr6   r   encoding_errorsdecoding_errors)r"   rT   r   ra   rb   r   r   r   r#   &  s    

zErrorOutput.__init__c              	   C   s   | j s
dS t|trt|}z| j | W n tk
rX   | j || j| j Y nr t	k
r   t|tr| j || j| j n:| j t
jt
jfkr| j j| n| j t|| j| j Y nX dS )z
        Write `data` to self.destination. Ignore, if self.destination is False.

        `data` can be a `bytes`, `str`, or `Exception` instance.
        N)rT   r2   	Exceptionr3   rX   UnicodeEncodeErrorrY   r   ra   r   r]   r^   stdoutbufferrb   rW   r   r   r   rX   G  s(    


zErrorOutput.writec                 C   s>   | j tjtjfkrdS z| j   W n tk
r8   Y nX dS )z
        Close the error-output stream.

        Ignored if the destination is` sys.stderr` or `sys.stdout` or has no
        close() method.
        N)rT   r]   re   r^   closer   r$   r   r   r   rg   a  s    zErrorOutput.closec                 C   s(   z| j  W S  tk
r"   Y dS X dS )z=Return True, if the destination is connected to a TTY device.FN)rT   rJ   r   r$   r   r   r   rJ   o  s    zErrorOutput.isatty)NNr[   r8   )r   r	   r
   rK   r#   rX   rg   rJ   r   r   r   r   rZ     s      
!rZ   c                   @   s2   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kr|rzt||| jp<d| jd| _W q t	k
r| } zt
|j|j|W 5 d}~X Y qX qtj| _n(t| j| jdkrtd| j| jjf |sz| jj| _W n tk
r   Y nX 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 and then read.
            - `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').
        Nz	utf-8-sigr   errorsFzOEncoding clash: encoding given is "%s" but source is opened with encoding "%s".)r   r#   	autocloserZ   _stderrr_   r   r   r   OSErrorr   errnostrerrorr]   stdinr   r9   namer   r   )r"   r   r   r   r   rl   moder>   r   r   r   r#   |  s,    $
zFileInput.__init__c              	   C   s   zrz(| jtjkr| jj }n
| j }W nD ttfk
rn   | j	sh| j
rht| j
d}| }|  n Y nX W 5 | j r|   X | |}d| dg S )zU
        Read and decode a single file and return the data (Unicode string).
        rb
r*   )rl   rg   r   r]   rq   rf   r(   r9   r   r   r   r_   r?   r:   rD   )r"   r;   Zb_sourcer   r   r   r(     s    


zFileInput.readc                 C   s   |   dS )zK
        Return lines of a single file as list of Unicode strings.
        T)r(   rD   r$   r   r   r   	readlines  s    zFileInput.readlinesc                 C   s   | j tjk	r| j   d S r   )r   r]   rq   rg   r$   r   r   r   rg     s    zFileInput.close)NNNr   Tri   )r   r	   r
   rK   r#   r(   rv   rg   r   r   r   r   rh   w  s          
(rh   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 )
FileOutputz,Output for single, simple file-like objects.z<file>r\   Nr   Tc                 C   s   t | |||| d| _|| _|dk	r6tjdtdd |dk	rD|| _t | _	|dkrj|r`d| _qt
j| _n6|rt| jdr|| jjkrtd| jj|f | j	d	 |sz| jj| _W n tk
r   Y nX 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.r@   )
stacklevelFrs   z?Warning: Destination mode "%s" differs from specified mode "%s")file)rR   r#   openedrl   warningswarnDeprecationWarningrs   rZ   rm   r]   re   rT   hasattrprintrr   rU   r   )r"   rT   rU   r   r   rl   Zhandle_io_errorsrs   r   r   r   r#     sD    
  



zFileOutput.__init__c              
   C   sv   d| j kr| j| jd}ni }zt| j| j f|| _W n4 tk
rj } zt|j|j	| jW 5 d }~X Y nX d| _
d S )Nbrj   T)rs   r   r   r_   rU   rT   rn   r   ro   rp   rz   )r"   kwargsr>   r   r   r   r_     s    

zFileOutput.openc                 C   sL  | j s|   t|trLt| j| jdkrLtjdkrB|	dtj}| 
|}zz| j| W n tk
r } zrt|trz| jj| W nP tk
r   t| j| jdkrtd| j d| jj d| j dn|Y nX W 5 d}~X Y nD ttfk
r0 } z td| j d	t| dW 5 d}~X Y nX W 5 | jrF|   X |S )
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.
        Fru   zEncoding of z (z&) differs 
  from specified encoding (r0   Nz2Unable to encode output data. output-encoding is: r/   )rz   r_   r2   r3   r   rT   r   oslinesepr8   rY   rl   rg   rX   r   bytesrf   r   
ValueErrorrU   r9   r   r   )r"   r;   r   r   r   r   rX     s>    




zFileOutput.writec                 C   s&   | j tjtjfkr"| j   d| _d S )NF)rT   r]   re   r^   rg   rz   r$   r   r   r   rg   ?  s    
zFileOutput.close)NNNr   TNN)
r   r	   r
   rK   rV   rs   r#   r_   rX   rg   r   r   r   r   rw     s            
/.rw   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
   rK   rs   r   r   r   r   r   E  s   r   c                   @   s   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`).
        )r?   r   r$   r   r   r   r(   S  s    zStringInput.readNr   r	   r
   rK   r    r(   r   r   r   r   r   N  s   r   c                   @   s   e Zd ZdZdZdd ZdS )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).
        )rY   rT   rW   r   r   r   rX   c  s    zStringOutput.writeNr   r	   r
   rK   rV   rX   r   r   r   r   r   [  s   r   c                   @   s   e Zd ZdZdZdd ZdS )	NullInputzDegenerate input: read nothing.z
null inputc                 C   s   dS )zReturn an empty string.r*   r   r$   r   r   r   r(   |  s    zNullInput.readNr   r   r   r   r   r   v  s   r   c                   @   s   e Zd ZdZdZdd ZdS )
NullOutputz!Degenerate output: write nothing.znull outputc                 C   s   dS )zDo nothing, return None.Nr   rW   r   r   r   rX     s    zNullOutput.writeNr   r   r   r   r   r     s   r   c                   @   s   e Zd ZdZdZdd ZdS )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     s   r   )&rK   Z__docformat__r   localer   rM   r]   r{   Zdocutilsr   catch_warningssimplefilter	getlocalegetdefaultlocaler6   r1   r   r>   argsr   r   r   rn   r   r   r   r   r   rR   rZ   rh   rw   r   r   r   r   r   r   r   r   r   r   <module>   sR   	





 >XQ}	