o
    jw                     @  s   d Z ddlmZ ddl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mZ dd
lmZmZmZmZmZ ddlmZmZ ddlmZmZmZ G dd dejZ G dd de
Z!dDddZ"dEd%d&Z#dFd+d,Z$dGd1d2Z%dHd7d8Z&dGd9d:Z'd;d<dd=d>dd?dIdBdCZ(dS )Jz*This is a python implementation of clip().    )annotationsN)islice)LiteralCallableOptional
NamedTuple   )width)iter_graphemes)	HyperlinkHyperlinkParams)_SGR_STATE_DEFAULT	_SGRState_sgr_state_update_sgr_state_is_active_sgr_state_to_sequence)
TextSizingTextSizingParams)_SEQUENCE_CLASSIFY_HORIZONTAL_CURSOR_MOVEMENTINDETERMINATE_EFFECT_SEQUENCEc                   @  s0   e Zd ZdZe Ze Ze Ze Z	dS )_HyperlinkActionz.Outcome of processing an OSC 8 hyperlink unit.N)
__name__
__module____qualname____doc__enumautoNO_CLOSEEMPTYOUTSIDEVISIBLE r"   r"   N/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/wcwidth/_clip.pyr      s    r   c                   @  sn   e Zd ZU dZded< dZded< dZded< dZd	ed
< dZd	ed< dZ	d	ed< dZ
ded< dZded< dS )_HyperlinkResultzn
    Result of processing an OSC 8 hyperlink.

    Only the fields relevant to each action are populated.
    r   actionr   int	close_endinner_width stropen_seqclipped_inner	close_seqclipped_width
hl_col_endN)r   r   r   r   __annotations__r'   r(   r+   r,   r-   r.   r/   r"   r"   r"   r#   r$   "   s   
 r$   resultr*   captured_styleOptional[_SGRState]returnc                 C  s0   |durt | }r||  } t|r| d7 } | S )z
    Apply SGR prefix/suffix around *result*.

    If an SGR state was captured at the first visible character, prefix the result with the
    corresponding SGR sequence and suffix with a reset if any styles are active.
    Nz[0m)r   r   )r1   r2   prefixr"   r"   r#   _apply_sgr_wrap3   s   r6   textstartr&   endfillchartabsizeambiguous_widthcontrol_codes$Literal['parse', 'strict', 'ignore']paramsr   	match_endcolc             
   C  s   t | |\}
}|
|fdkrttjS | ||
 }t||||d}|dkr,ttj|dS |	| }||ks8|	|kr@ttj||dS td||	 }||	 }t	||||||d|d}t||||d}ttj
||| || ||dS )	z
    Process an OSC 8 hyperlink unit.

    Finds the matching close sequence, measures the inner text width, and determines whether the
    hyperlink is empty, outside the clip window, or visible (requiring inner-text clipping).
    )rB   )r=   r;   r<   r   )r'   )r'   r(   F)r:   r;   r<   propagate_sgrr=   )r'   r(   r+   r,   r-   r.   r/   )r   Z
find_closer$   r   r   r	   r   r    maxclipr!   Z	make_openZ
make_close)r7   r8   r9   r:   r;   r<   r=   r?   r@   rA   Zclose_startr'   Z
inner_textr(   r/   Zinner_clip_startZinner_clip_endr,   r.   r"   r"   r#   _process_hyperlinkB   sL   
rF   cellsdict[int, tuple[str, int]]	sequenceslist[tuple[int, int, str]]c                 C  sX  i }|D ]\}}}| |g ||f q| D ]}	|	  q| r(t|  nd}
|r2t| nd}t|
|}g }d}t||}||kr||dD ]	\}}|| qL||kr_|d7 }qB|| v rs| | \}}|| ||7 }n||  kr}|
krn n|| |d7 }||ksFt| D ]}||kr|| D ]	\}}|| qqd	|S )z
    Reconstruct the output string from painter's algorithm state.

    Walks columns left-to-right, interleaving escape sequences and cell content, filling gaps with
    *fillchar*.
    rB   r   r"   r   r)   )

setdefaultappendvaluessortrD   keysmingetsortedjoin)rG   rI   r8   r9   r:   Zseqs_by_colZcol_posorderZseq_textentriesZmax_cell_colZmax_seq_colZmax_colpartsZwalk_colZ	col_limit_Z	cell_textZcell_wcr"   r"   r#   _reconstruct_painter   s>   






rY   rC   boolstricttuple[str, Optional[_SGRState]]c                  s  g }	d}
d}d}|rt nd}|t| k r:| | }|
|kr8|dvr8|dur'n| d|d }|dkr5n|}q|dkrxt| |}|sO|	| |d7 }q|ddurh|rh|durht|| }| }qt	
|  }rt| |||||||| |
d
}|jtju r|	|  | }n;|jtju r|j}n1|jtju r|
|j7 }
|j}n"|	|j |	|j |	|j |r|du r|}|
|j7 }
|j}q|d	 }durW|d
}|d}|dur|dusJ ttj||d||}||}|
|kr|
| |kr|	|  |r|du r|}|
|7 }
n3|
|k rN|
| |krNg  d fdd}t||
|||||}
|	  |rM|du rM|}n|
|7 }
| }q| }|rnt|rntd| d||	| | }q|dkr|dkr|
||
|   }|
|k r||
  kr|k rn n|	d |r|du r|}|
d7 }
|
|k sn|	d |d7 }qtt | |d}t!||d}|dkr||
  kr|k rn nI|	| nC|
|kr|
| |kr|	| |r|du r|}n'|
|k r*|
| |kr*|	|t"||
| t#||
   |r*|du r*|}|
|7 }
|t|7 }|t| k sd$|	|fS )z
    Clip text without cursor movement (simple append-to-output path).

    Returns ``(result, captured_style)``.  The caller applies SGR wrapping.
    r   Nz	r   rB   
sgr_paramsr?   r@   rA   ts_metats_textts_termr=   sr*   _wr&   _colr4   Nonec                   s     |  d S )N)rL   )rd   re   rf   Zts_partsr"   r#   	_ts_write'  s   z_clip_simple.<locals>._ts_write*Indeterminate cursor sequence at position , 	 r8   r<   r)   )rd   r*   re   r&   rf   r&   r4   rg   )%r   lenfindr   matchrL   groupr   r9   r   parserF   r%   r   r   r   r'   r    r(   r+   r,   r-   r   r   from_paramsdisplay_widthmake_sequence_text_sizing_clipextendr   
ValueErrornextr
   r	   rP   rD   rS   )r7   r8   r9   rC   r<   r:   r;   r[   r=   outputrA   idxr2   current_stylecharZnext_escmhl_staterr`   ra   rb   tsts_widthri   seqnext_tabgrapheme
grapheme_wr"   rh   r#   _clip_simple   s   	




















"  r   r   r   write_cellsCallable[[str, int, int], None]c                   s   |}||kr|| |kr || || S ||ks%|| |kr)|| S td|| }t||| | }	jjg }
jjdkrnttj	jjD ]	}|

|f qOtjjt|
 D ]	}|

df qcntj	D ]}|

|t||d f qsg  d fdd	}|| }d}|
D ]T\}}|| }||kr|}q||	kr n@t||	t|| }||kr|dkrψ s|t|| } 
||f n|| |t|| }t|D ]
}|d
||  q|}q|| || S )z
    Emit tokens for a text-sizing (OSC 66) sequence, clipped to (start, end).

    Calls *write_cells(text, width, col)* for each emitted cell or sequence. Returns new column
    position.
    r   r)   ro   	flush_colr&   r4   rg   c                   s    sd S dd  D }t dd  D }tjjdkr t|ndjjjjjjjj}t	|d
|j ||     d S )Nc                 S  s   g | ]}|d  qS )r   r"   .0ur"   r"   r#   
<listcomp>  s    z4_text_sizing_clip.<locals>.flush.<locals>.<listcomp>c                 s  s    | ]}|d  V  qdS )r   Nr"   r   r"   r"   r#   	<genexpr>  s    z3_text_sizing_clip.<locals>.flush.<locals>.<genexpr>r   r)   )sumr   r?   r	   rp   	numeratordenominatorZvertical_alignZhorizontal_alignr   rS   
terminatorrw   clear)r   ZtextsZtotal_wr?   Zpending_unitsscaler   r   r"   r#   flush  s    z _text_sizing_clip.<locals>.flushr   N)r   r&   r4   rg   )rv   rw   rD   rP   r?   r   r	   r   r
   r7   rL   rangerp   )r   rA   r8   r9   r:   r<   r   r   Z	rel_startZrel_endZunitsgrW   r   Zflush_col_posZunit_posZ	unit_textZunit_wZunit_endZoverlapZ	abs_startir"   r   r#   rx   f  sR   
rx   c          #        s  i t  g }	d}
d}d}d rtnd	d'd( fdd}|t| k r| | }||kr< dur<|dkr<n|dkrt| |}|sb|	||
|f |
d7 }
r] du r] |d7 }q#|ddur{r{dur{t| | }q#t	
|  }rt| ||||||| |d
}|jtju r|	||
| f |
d7 }
r du r | }nP|jtju r|j}nF|jtju r||j7 }|j}n7|	||
|jf |
d7 }
r du r ||j|j|dd ||j7 }|	||
|jf |
d7 }
|j}|j}q#|d }durK|d}|d}|dur%|dus'J ttj||d||}t||||||}rF du rF | }q#| }|rbt|rbtd| d||d }dur||rut|d nd}| }q#|d }dur|rt|nd}|| }||k r||krtt ||t!||D ]	}|d| q|}| }q#|d }dur|rt|nd}|r||krtd| d| d | d!t d|| }| }q#|	||
| f |
d7 }
r du r | }q#|d"krd}|d7 }q#|d#kr*|dkr%|d8 }|d7 }q#|d$krz|dkr_||||   }||k r^||  krM|k rUn n|d| |d7 }||k sAn|	||
d$f |
d7 }
ru du ru |d7 }q#t"t#| |d%}t$||d&} | dkr||  kr|k rn nR|	||
|f |
d7 }
r du r n;||kr||  |kr||| | n(||k r||  |krt ||}!tt!|||  |! D ]}"|d|!|"  q|| 7 }|t|7 }|t| k s*t%|	|| fS ))z
    Clip text with cursor movement (painter's algorithm path).

    Returns ``(result, captured_style)``.  The caller applies SGR wrapping.
    r   NFrd   r*   wr&   	write_colis_hyperlinkrZ   r4   rg   c                   s   t |D ]I}|| }|dkr)|d dd dkr)df|d < |d  |dd dkrBdf|d < |d  |d | q| |f|< |rdt |D ]	}||  qZrn du rp dS dS dS )zIWrite *w* cells of text *s* at *write_col*, handling wide-char splitting.r   r   )r)   r      N)r   rQ   discardpopadd)rd   r   r   r   offsetZsrc_colr2   rG   r~   r:   Zhyperlink_cellsrC   r"   r#   _write_cells  s"    z#_clip_painter.<locals>._write_cellsr]   r   r^   r_   T)r   r`   ra   rb   rc   rj   rk   hpa_n
cforward_ncbackward_nz!Cursor left movement at position z would move z cells left from column z, exceeding string startrl   rn   ro   )F)
rd   r*   r   r&   r   r&   r   rZ   r4   rg   )&setr   rp   r   rr   rL   rs   r   r9   r   rt   rF   r%   r   r   r   r'   r    r(   r+   r,   r.   r-   r/   r   r   ru   rx   r   rz   r&   r   rD   rP   r{   r
   r	   rY   )#r7   r8   r9   rC   r<   r:   r;   r[   r=   rI   Z	seq_orderrA   r}   r   r   r   r   r   r`   ra   rb   r   r   r   r   Z	n_forwardZmove_endr   r   Z
n_backwardr   r   r   Z
clip_startr   r"   r   r#   _clip_painter  s:  















  )r   rm      Trt   )r:   r;   r<   rC   r=   
overtypingr   Optional[bool]c                C  s   t |d}||krdS |  r|  r| || S d| v }	|r#|	s#d}|du r=|dko;d| v p;d| v p;|	o;tt| }n|rE|dkrEd}|rItnt}
t|
| |||||||d	k|d
	 S )u  
    Clip text to display columns (start, end) while preserving all terminal sequences.

    This function extracts a substring based on visible column positions rather than
    character indices. Terminal escape sequences are preserved in the output since
    they have zero display width. If a wide character (width 2) is split at
    either boundary, it is replaced with ``fillchar``.

    TAB characters (``\t``) are expanded to spaces up to the next tab stop,
    controlled by the ``tabsize`` parameter. When cursor movement is detected,
    a "painter's algorithm" is used, cursor movements actively change the write
    position, allowing cursor-left and carriage return to overwrite previously
    written cells. It is assumed that ``text`` begins at column 0.

    **OSC 8 hyperlinks** are handled specially: the visible text inside a hyperlink
    is clipped to the requested column range, and the hyperlink is rebuilt around
    the clipped text.  Empty hyperlinks (those with no remaining visible text after
    clipping) are removed::

        >>> clip('\x1b]8;;http://example.com\x07Click This link\x1b]8;;\x07', 6, 10)
        '\x1b]8;;http://example.com\x07This\x1b]8;;\x07'

    :param text: String to clip, may contain terminal escape sequences.
    :param start: Absolute starting column (inclusive, 0-indexed).
    :param end: Absolute ending column (exclusive).
    :param fillchar: Character to use when a wide character must be split at
        a boundary (default space). Must have display width of 1.
    :param tabsize: Tab stop width (default 8). Set to 0 to pass tabs through
        as zero-width (preserved in output but don't advance column position).
    :param ambiguous_width: Width to use for East Asian Ambiguous (A)
        characters. Default is ``1`` (narrow). Set to ``2`` for CJK contexts.
    :param propagate_sgr: If True (default), SGR (terminal styling) sequences
        are propagated. The result begins with any active style at the start
        position and ends with a reset sequence if styles are active.
    :param control_codes: How to handle control characters and sequences:

        - ``'parse'`` (default): Track horizontal cursor movement and clip
          hyperlink text.  Cursor overwrite is always allowed, with best effort
          results; indeterminate sequences (home, clear, reset, etc.) are
          preserved as zero-width.
        - ``'strict'``: Like ``parse``, but raises :exc:`ValueError` on
          sequences with indeterminate effects (cursor home, clear screen,
          reset, vertical movement, etc.) matching :func:`width` behavior.
          Also raises on out-of-bounds horizontal cursor movement.
        - ``'ignore'``: All control characters are treated as zero-width.
          Cursor movement is not tracked (fastest path).

    :param overtyping: Whether to use the painter's algorithm for cursor
        movement (``\b`` backspace, ``\r`` carriage return, and CSI cursor
        left/right/position sequences).  When ``None`` (default), auto-detects
        by scanning for these characters in *text*.  Set to ``False`` for improved
        performance when the caller knows *text* contains no cursor movement
        characters.  Set to ``True`` to force the painter's algorithm (useful
        for testing).  Has no effect when ``control_codes='ignore'``.

    :returns: Substring of ``text`` spanning display columns (start, end),
        with all terminal sequences preserved and wide characters at boundaries
        replaced with ``fillchar``.

    :raises ValueError: If ``control_codes='strict'`` and an indeterminate-effect
        sequence or out-of-bounds cursor movement is encountered.

    SGR (terminal styling) sequences are propagated by default. The result
    begins with any active style and ends with a reset::

        >>> clip('\x1b[1;34mHello world\x1b[0m', 6, 11)
        '\x1b[1;34mworld\x1b[0m'

    Set ``propagate_sgr=False`` to disable this behavior.

    .. versionadded:: 0.3.0

    .. versionchanged:: 0.5.0
       Added ``propagate_sgr`` parameter (default True).

    .. versionchanged:: 0.7.0
       Added ``control_codes`` parameter (default 'parse').
       OSC 8 hyperlink-aware clipping.  OSC 66 text sizing protocol support.
       Added ``overtyping`` parameter (default None, auto-detect).

    Example::

        >>> clip('hello world', 0, 5)
        'hello'
        >>> clip('中文字', 0, 3)  # Wide char split at column 3
        '中 '
        >>> clip('a\tb', 0, 10)  # Tab expanded to spaces
        'a       b'
    r   r)   r]   FNignorer   r   r[   )	r7   r8   r9   rC   r<   r:   r;   r[   r=   )	rD   isasciiisprintablerZ   r   searchr   r   r6   )r7   r8   r9   r:   r;   r<   rC   r=   r   Zhas_escZfn_clipr"   r"   r#   rE     s6   
erE   )r1   r*   r2   r3   r4   r*   )r7   r*   r8   r&   r9   r&   r:   r*   r;   r&   r<   r&   r=   r>   r?   r   r@   r&   rA   r&   r4   r$   )rG   rH   rI   rJ   r8   r&   r9   r&   r:   r*   r4   r*   )r7   r*   r8   r&   r9   r&   rC   rZ   r<   r&   r:   r*   r;   r&   r[   rZ   r=   r>   r4   r\   )r   r   rA   r&   r8   r&   r9   r&   r:   r*   r<   r&   r   r   r4   r&   )r7   r*   r8   r&   r9   r&   r:   r*   r;   r&   r<   r&   rC   rZ   r=   r>   r   r   r4   r*   ))r   
__future__r   r   	itertoolsr   typingr   r   r   r   _widthr	   r   r
   Z	hyperlinkr   r   Z	sgr_stater   r   r   r   r   Ztext_sizingr   r   Zescape_sequencesr   r   r   Enumr   r$   r6   rF   rY   r   rx   r   rE   r"   r"   r"   r#   <module>   s8    	


B
7 
,
U l