o
    jx                  	   @  sD  d Z ddlmZ ddl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mZ ddl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%	dJdKddZ&dLd)d*Z'dMd/d0Z(dNd5d6Z)dOd;d<Z*dNd=d>Z+		?dPd@dAddBdCddDdEdQdHdIZ,dS )Rz*This is a python implementation of clip().    )annotationsN)islice)LiteralCallableOptional
NamedTuple   )width)iter_graphemes)	HyperlinkHyperlinkParams)_SGR_PATTERN_SGR_STATE_DEFAULT	_SGRState_sgr_state_update_sgr_state_is_active_sgr_state_to_sequence)_clamp_ambiguous_width)
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$   /root/aizidognhua/tmp/workspace/projects/ec89d86c-575f-41c9-af57-ac45cbdbf775/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/   r0   r1   r$   r$   r$   r%   r&   %   s   
 r&   resultr,   captured_styleOptional[_SGRState]	end_stylereturnc                 C  s<   |durt | }r||  } t|du r|n|r| d7 } | S )aZ  
    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 remain active at the end
    of the clipped region.

    *end_style* is the style in effect after the final SGR sequence emitted within the clip window,
    or ``None`` when no such sequence was emitted, the style at the first visible character is still
    in effect.  This matches :func:`wcwidth.propagate_sgr`, which decides the trailing reset by SGR
    state at the end of each line.
    Nz[0m)r   r   )r3   r4   r6   prefixr$   r$   r%   _apply_sgr_wrap6   s   r9   textstartr(   endfillchartabsizeambiguous_widthterm_program
bool | str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s9|
|krAt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).
    )rG   )rB   r>   r?   r@   r   )r)   )r)   r*   F)r=   r>   r?   r@   propagate_sgrrB   )r)   r*   r-   r.   r/   r0   r1   )r   
find_closer&   r   r    r	   r!   r"   maxclipr#   	make_open
make_close)r:   r;   r<   r=   r>   r?   r@   rB   rD   rE   rF   close_startr)   
inner_textr*   r1   inner_clip_startinner_clip_endr.   r0   r$   r$   r%   _process_hyperlinkL   sR   
	rR   cellsdict[int, tuple[str, int]]	sequenceslist[tuple[int, int, str]]c                 C  s\  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 ru| | \}}|| ||prd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*.
    rG   r   r$   r   r+   )

setdefaultappendvaluessortrJ   keysmingetsortedjoin)rS   rU   r;   r<   r=   seqs_by_colcol_posorderseq_textentriesmax_cell_colmax_seq_colmax_colpartswalk_col	col_limit_	cell_textcell_wcr$   r$   r%   _reconstruct_painter   s>   





ro   rH   boolstrict4tuple[str, Optional[_SGRState], Optional[_SGRState]]c                   s  g }
d}d}d}d}|rt nd}|t| k rh| | }||kr:|dvr:|dur)n?| d|d }|dkr7n1|}q|dkrt| |}|sQ|
| |d7 }q|ddur{|r{|dur{t|| }|durv||k rv|
|  |}| }qt	
|  }rt| |||||||	|| |d}|jtju r|
|  | }nS|jtju r|j}nI|jtju r||j7 }|j}n:|
|j |
|j |
|j |r|du r|}|r|durt|jD ]}t|| }|}q||j7 }|j}q|d	 }dur|d
pd}|d}|dusJ ttj||	d||}||}||krK|| |krK|
|  |rF|du rF|}||7 }n4||k r{|| |kr{g  d fdd}t||||||||}|
  |rz|du rz|}n||7 }| }q| }|rt|rt 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 rn nI|
| nC||kr1|| |kr1|
| |r0|du r0|}n'||k rX|| |krX|
|t$||| t%||   |rX|du rX|}||7 }|t|7 }|t| k sd&|
||fS )z
    Clip text without cursor movement (simple append-to-output path).

    Returns ``(result, captured_style, end_style)``.  The caller applies SGR wrapping.
    r   N	r   rG   
sgr_paramsrD   rE   rF   ts_metats_textr+   ts_termrB   sr,   _wr(   _colr7   Nonec                   s     |  d S N)rX   )r{   r|   r}   ts_partsr$   r%   	_ts_writeG  s   z_clip_simple.<locals>._ts_write*Indeterminate cursor sequence at position , 	 r;   r?   r@   )r{   r,   r|   r(   r}   r(   r7   r~   )'r   lenfindr   matchrX   groupr   r<   r   parserR   r'   r   r    r!   r)   r"   r*   r-   r.   r/   r   finditerr   r   from_paramsdisplay_widthmake_sequence_text_sizing_clipextendr   
ValueErrornextr
   r	   r\   rJ   r_   ) r:   r;   r<   rH   r?   r@   r=   r>   rq   rB   outputrF   idxr4   r6   current_stylecharnext_escmhl_statersgr_mrw   rx   ry   tsts_widthr   seqnext_tabgrapheme
grapheme_wr$   r   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+   r   	flush_colr(   r7   r~   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   rD   r	   r   	numeratordenominatorvertical_alignhorizontal_alignr   r_   
terminatorr   clear)r   textstotal_wrD   pending_unitsscaler   r   r$   r%   flush  s    z _text_sizing_clip.<locals>.flushr   N)r   r(   r7   r~   )r   r   rJ   r\   rD   r   r	   r   r
   r:   rX   ranger   )r   rF   r;   r<   r=   r?   r@   r   r   	rel_startrel_endunitsgrk   r   flush_col_posunit_pos	unit_textunit_wunit_endoverlap	abs_startir$   r   r%   r     s^   
r   c          (        s  i t  g dd}
d}d d}rtndd}	d+d, fdd}|t| k r<| | }|
|kr|dvr|du sLd|  krJ|k rpn n$t| d| d| d|k r`d}nt| |}|du rldn| }|dk r durzn| d|d }|dkrn|}q)|dkrht	
| |}|s|
|f d7 |d7 }q)|ddurڈrڈdurt|  dur|
|k rՈ|
| f d7 }| }q)t|  }rut| ||||||	|| |
d}|jtju r|
| f d7 | }ne|jtju r|j}nZ|jtju r*|
|j7 }
|j}nJ|
|jf d7 ||j|j|
dd |
|j7 }
|
|jf d7 rndurnt|jD ]}t| }qa|j}
|j}q)|d }dur|dpd}|d}|dusJ tt j!||	d||}t"||
|||||}
| }q)| }|rt#
|rt$d| d||d  }dur|rt%|d nd}
| }q)|d! }dur|rt%|nd}|
| }|
|k r||krt&t|
|t'||D ]	}|d| q|}
| }q)|d" } durU| r-t%| nd}!|rE|!|
krEt$d#| d$|! d%|
 d&|
|!8 }
|
dk rPd}
| }q)|
| f d7 | }q)|dkrtd}
|d7 }q)|dkr|
dkr|
d8 }
|d7 }q)|d'kr|dkr|
||
|   }"t&t|
|t'|"|D ]	}#|d(d|# q|"}
n|
d'f d7 |d7 }q)t(t)| |d)}$t*|$||d*}%|%dkr||
  kr|k rn nH|
|$f d7 n;|
|kr|
|% |kr||$|%|
 n(|
|k r,|
|% |kr,t||
}&t&t'||
|% |& D ]}'|d|&|'  q |
|%7 }
|t|$7 }|t| k s0t+|| |fS )-z
    Clip text with cursor movement (painter's algorithm path).

    Returns ``(result, captured_style, end_style)``.  The caller applies SGR wrapping.
    r   NFr{   r,   wr(   	write_colis_hyperlinkrp   r7   r~   c                   s  |dkr| r || f d7 r du r dS t|D ]I}|| }|dkrE|d dd dkrEdf|d < |d  |dd dkr^df|d < |d  |d | q | |f|< |rt|D ]	}||  qvr du r dS dS dS )zIWrite *w* cells of text *s* at *write_col*, handling wide-char splitting.r   r   N)r+   r      )rX   r   r]   discardpopadd)r{   r   r   r   offsetsrc_colr4   rS   r   r=   hyperlink_cellsrH   	seq_orderrU   r$   r%   _write_cells  s0    z#_clip_painter.<locals>._write_cellsrs   rt   rG   r   ru   rv   T)r   rw   rx   r+   ry   rz   r   r   hpa_n
cforward_ncbackward_nz!Cursor left movement at position z would move z cells left from column z, exceeding string startr   r   r   r   )F)
r{   r,   r   r(   r   r(   r   rp   r7   r~   ),setr   r   rJ   rfindr   searchr<   r   r   r   rX   r   r   r   r   rR   r'   r   r    r!   r)   r"   r*   r-   r.   r0   r/   r   r   r1   r   r   r   r   r   r   r(   r   r\   r   r
   r	   ro   )(r:   r;   r<   rH   r?   r@   r=   r>   rq   rB   rF   r   r6   next_movementr   r   foundr   r   r   r   r   rw   rx   ry   r   r   r   r   	n_forwardmove_endr   r   
n_backwardr   fill_colr   r   
clip_startr   r$   r   r%   _clip_painter  sT   "













  ;r   rG   r      Tr   F)r=   r>   r?   rH   rB   
overtypingr@   r   Optional[bool]c                C  s   t |d}|dk r|dkrtd| tj}||krdS |  r+|  r+| || S t|}d| v }
|r9|
s9d}|du rS|dkoQd	| v pQd
| v pQ|
oQtt	| }n|r[|dkr[d}|r_t
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 output. If a wide character (width of 2) is
    split at a 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 unless
    ``overtyping=False`` is set.  Cursor movement control codes are parsed for their effects instead
    of ignored.  For these operations, it is assumed that ``text`` begins at column 0.

    For text containing **OSC 8 hyperlinks**, the visible text inside a hyperlink is clipped to the
    requested column range and the hyperlink sequence is rebuilt::

        >>> 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), default ``0``.
    :param end: Absolute ending column (exclusive).  The default value, ``-1``,
        signifies "to the end of the line", clipping only from *start* without
        requiring the caller to measure the display width of *text*.
    :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, matching :func:`propagate_sgr`.  The result begins with
        any style active at the start position, retains any style changes
        occurring within the clipped region at their original position, and
        ends with a reset sequence if styles are active at the end position.
    :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'``.
    :param term_program: Terminal software identifier for table correction.
        ``False`` (default) disables override lookup.  ``True`` reads the
        ``TERM_PROGRAM`` or ``TERM`` environment variable for auto-detection.
        Accepts a canonical terminal name matching :func:`list_term_programs`,
        such as from XTVERSION_, ENQ_, or ``TERM_PROGRAM``.

        .. versionadded:: 0.8.0

    :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 ``end`` is negative and not ``-1``, or 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'
        >>> clip('\x1b[1mbold\x1b[m normal', 1, 9)
        '\x1b[1mold\x1b[m norm'

    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).

    .. versionchanged:: 0.8.4
       ``start`` now defaults to ``0`` and ``end`` to ``-1``, meaning "to the
       end of the line"::

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

    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   rG   z5end must be -1 (to end of line) or non-negative, got r+   rt   FNignorer   r   rq   )
r:   r;   r<   rH   r?   r@   r=   r>   rq   rB   )rJ   r   sysmaxsizeisasciiisprintabler   rp   r   r   r   r   r9   )r:   r;   r<   r=   r>   r?   rH   rB   r   r@   has_escfn_clipr$   r$   r%   rK     sF   
wrK   r   )r3   r,   r4   r5   r6   r5   r7   r,   )r:   r,   r;   r(   r<   r(   r=   r,   r>   r(   r?   r(   r@   rA   rB   rC   rD   r   rE   r(   rF   r(   r7   r&   )rS   rT   rU   rV   r;   r(   r<   r(   r=   r,   r7   r,   )r:   r,   r;   r(   r<   r(   rH   rp   r?   r(   r@   rA   r=   r,   r>   r(   rq   rp   rB   rC   r7   rr   )r   r   rF   r(   r;   r(   r<   r(   r=   r,   r?   r(   r@   rA   r   r   r7   r(   )r   rG   )r:   r,   r;   r(   r<   r(   r=   r,   r>   r(   r?   r(   rH   rp   rB   rC   r   r   r@   rA   r7   r,   )-r   
__future__r   r   r   	itertoolsr   typingr   r   r   r   _widthr	   r   r
   	hyperlinkr   r   	sgr_stater   r   r   r   r   r   
_constantsr   text_sizingr   r   escape_sequencesr   r   r   Enumr   r&   r9   rR   ro   r   r   r   rK   r$   r$   r$   r%   <module>   sH     	

F
7 
@
X  