
    iw                    4   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ej                  Z  G d de
          Z!d=dZ"d>d$Z#d?d)Z$d@d.Z%dAd3Z&d@d4Z'd5d6dd7d8dd9dBd<Z(dS )Cz*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                      e Zd ZdZ ej                    Z ej                    Z ej                    Z ej                    Z	dS )_HyperlinkActionz.Outcome of processing an OSC 8 hyperlink unit.N)
__name__
__module____qualname____doc__enumautoNO_CLOSEEMPTYOUTSIDEVISIBLE     T/home/piyush/.hermes/hermes-agent/venv/lib/python3.11/site-packages/wcwidth/_clip.pyr   r      sH        88ty{{HDIKKEdikkGdikkGGGr%   r   c                      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/   r0   r1   r2   r3   r$   r%   r&   r(   r(   "   s           IKHMIMJr%   r(   resultr.   captured_styleOptional[_SGRState]returnc                ^    |*t          |          x}r|| z   } t          |          r| dz  } | 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   )r5   r6   prefixs      r&   _apply_sgr_wrapr;   3   sG     !+N;;;6 	%f_F// 	 iFMr%   textstartr*   endfillchartabsizeambiguous_widthcontrol_codes$Literal['parse', 'strict', 'ignore']paramsr   	match_endcolc          
     X   t          j        | |          \  }
}|
|fdk    rt          t          j                  S | ||
         }t          ||||          }|dk    rt          t          j        |          S |	|z   }||k    s|	|k    rt          t          j        ||          S t          d||	z
            }||	z
  }t          ||||||d|          }t          ||||          }t          t          j
        |||                                ||                                ||          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).
    )rH   )rB   r@   rA   r   )r+   )r+   r,   F)r?   r@   rA   propagate_sgrrB   )r+   r,   r/   r0   r1   r2   r3   )r   
find_closer(   r   r    r
   r!   r"   maxclipr#   	make_open
make_close)r<   r=   r>   r?   r@   rA   rB   rD   rE   rF   close_startr+   
inner_textr,   r3   inner_clip_startinner_clip_endr0   r2   s                      r&   _process_hyperlinkrS   B   s   ( '1$	BBKY8++ 0 9:::i+,J-  K
 a 0 6)LLLL{"JUcSjj 0 8I,79 9 9 	9 1eck**3YN$n7'#  M ]  M
  !!#####%%#	 	 	 	r%   cellsdict[int, tuple[str, int]]	sequenceslist[tuple[int, int, str]]c                   i }|D ]1\  }}}|                     |g                               ||f           2|                                D ]}	|	                                 | r!t	          |                                           nd}
|r!t	          |                                          nd}t	          |
|          }g }d}t          ||          }||k    r|                    |d          D ]\  }}|                    |           ||k    r|dz  }C|| v r&| |         \  }}|                    |           ||z  }n*||cxk    r|
k    rn n|                    |           |dz  }||k    t          |                                          D ]+}||k    r#||         D ]\  }}|                    |           ,d	                    |          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*.
    rH   r   r$   r	   r-   )

setdefaultappendvaluessortrK   keysmingetsortedjoin)rT   rV   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cs                       r&   _reconstruct_painterrq      s#    57K$- F F w++22E83DEEEE%%''  (-53uzz||$$$2L-8@#k&&(()))bK,,,GEHGS!!I
i

&??8R88 	# 	#KAxLL""""s??MHu %hIvLL###HH0000L00000X&&&MH! i

& K$$&&'' ' 'y==*1~ ' '8X&&&&775>>r%   rI   boolstricttuple[str, Optional[_SGRState]]c               
   g }	d}
d}d}|rt           nd}|t          |           k     r| |         }|
|k    r,|dvr(|n|                     d|dz             }|dk    rn|}N|dk    r]t          j        | |          }|s|	                    |           |dz  }|                    d          ;|r9|7t          ||                                          }|                                }t          j
        |                                          x}r!t          | ||||||||                                |

  
        }|j        t          j        u r<|	                    |                                           |                                }n|j        t          j        u r|j        }n|j        t          j        u r|
|j        z  }
|j        }ne|	                    |j                   |	                    |j                   |	                    |j                   |r||}|
|j        z  }
|j        }!|                    d	          x}|                    d
          }|                    d          }||J t-          t/          j        ||          ||          }|                    |          }|
|k    r<|
|z   |k    r3|	                    |                                           |r||}|
|z  }
nM|
|k     rB|
|z   |k    r9g dfd}t7          ||
|||||          }
|	                               |r||}n|
|z  }
|                                }H|                                }|r)t;          j        |          rt=          d| d|          |	                    |           |                                }|dk    rj|dk    rH|
||
|z  z
  z   }|
|k     r6||
cxk    r|k     rn n|	                    d           |r||}|
dz  }
|
|k     6n|	                    d           |dz  }"t?          tA          | |                    }tC          ||          }|dk    r&||
cxk    r|k     rn n|	                    |           nz|
|k    r%|
|z   |k    r|	                    |           |r||}nO|
|k     rI|
|z   |k    r@|	                    |tE          ||
|z             tG          ||
          z
  z             |r||}|
|z  }
|t          |          z  }|t          |           k     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	   rH   
sgr_paramsrD   rE   rF   ts_metats_textts_termrB   sr.   _wr*   _colr8   Nonec                2                         |            d S )N)rZ   )r}   r~   r   ts_partss      r&   	_ts_writez_clip_simple.<locals>._ts_write'  s     *****r%   *Indeterminate cursor sequence at position , 	 r=   rA   r-   )r}   r.   r~   r*   r   r*   r8   r   )%r   lenfindr   matchrZ   groupr   r>   r   parserS   r)   r   r    r!   r+   r"   r,   r/   r0   r1   r   r   from_paramsdisplay_widthmake_sequence_text_sizing_clipextendr   
ValueErrornextr   r
   r^   rK   ra   )r<   r=   r>   rI   rA   r?   r@   rs   rB   outputrF   idxr6   current_stylecharnext_escmhl_staterry   rz   r{   tsts_widthr   seqnext_tabgrapheme
grapheme_wr   s                                @r&   _clip_simpler      s-   * F
C
C +/N*7A&&TM
D		//Cy #::$n44)
 yyq11H2~~C6>>"(s33A d###q ww|$$0]0}G` 1- K Keegg +0;;;x &%h!#quuwwC  
 8/888MM!'')),,,%%''CCX!1!777+CCX!1!9991=(C+CCMM!*---MM!/222MM!+...$ 7)?)61=(C+C 779---:''),,''),,*w/B/BB$0VVVW& & ++O<<%<<C(Nc$9$9MM""2"2"4"4555$ 7)?)68OCC3YY3>E#9#9*,H+ + + + + ++CX!# #C MM(+++$ 7)?)68OCeegg ''))C 7=cBB        MM#%%''C4<<{{'S7]";<Hnn))))c)))))c***( ;^-C-:N1HC Hnn d###1HCt3777888_EEE
 ??!!!!c!!!!!h'''E\\cJ.#55MM(### /!7!.3YY3+e33MM(c#sZ/?&@&@3uc??&RSTTT /!7!.zs8}}G D		//J 776??N**r%   r   r   write_cellsCallable[[str, int, int], None]c                                          |          }||k    r-||z   |k    r$                                  ||           ||z   S ||k    s	||z   |k    r||z   S t          d||z
            }t          |||z             |z
  }	 j        j        g }
 j        j        dk    rt          t           j	                   j        j                  D ]}|

                    |f           t           j        j        t          |
          z
            D ]}|

                    df           n@t           j	                  D ]+}|

                    |t          ||          z  f           ,g d
 fd}||z   }d}|
D ]\  }}||z   }||k    r|}||	k    r nt          ||	          t          ||          z
  }||k    r3|dk    r-s|t          ||          z   }
                    ||f           n@ ||           |t          ||          z   }t          |          D ]} |d	||z              |} ||           ||z   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*   r8   r   c                   sd S d D             }t          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                    g | ]
}|d          S )r   r$   .0us     r&   
<listcomp>z4_text_sizing_clip.<locals>.flush.<locals>.<listcomp>  s    ---!1---r%   c              3  &   K   | ]}|d          V  dS )r	   Nr$   r   s     r&   	<genexpr>z3_text_sizing_clip.<locals>.flush.<locals>.<genexpr>  s&      22qad222222r%   r   r-   )sumr   rD   r
   r   	numeratordenominatorvertical_alignhorizontal_alignr   ra   
terminatorr   clear)r   textstotal_wrD   pending_unitsscaler   r   s       r&   flushz _text_sizing_clip.<locals>.flush  s     	F--}---22M22222!)/A--CJJJ1I!6I$bi&@	B B
 	vrwwu~~r}==KKMM	 	 	 	r%   r	   )r   r*   r8   r   )r   r   rK   r^   rD   r   r
   r   r   r<   rZ   ranger   )r   rF   r=   r>   r?   rA   r   r   	rel_startrel_endunitsgrm   r   flush_col_posunit_pos	unit_textunit_wunit_endoverlap	abs_startir   r   s   `     `               @@r&   r   r   f  s     00H e||h#--B$$&&#666X~
czzS8^u,,X~ Aus{##I#sX~&&,GIOE#%E	yrw//AA 	% 	%ALL!U$$$$ryU344 	& 	&ALL"e%%%%	&  (( 	Q 	QALL!U1oFFFNOPPPP+-M          )OMH"  	6f$y  HwEh((3x+C+CCf!  ? #c(I&>&> >  )V!45555E-   c(I666I7^^ 8 8HaQ7777	E->r%   c                 #$%& i $t                      &g }	d}
d}d}d#rt          nd%	 d&d'#$%&fd}|t          |           k     r'| |         }||k    r
#|dk    rn|dk    rkt          j        | |          }|s)|	                    ||
|f           |
dz  }
r#%#|dz  }s|                    d          ;r9%7t          %|                                          %|                                }t          j
        |                                          x}rEt          | |||||||                                |
  
        }|j        t          j        u rJ|	                    ||
|                                f           |
dz  }
r#%#|                                }n|j        t          j        u r|j        }n|j        t          j        u r||j        z  }|j        }n{|	                    ||
|j        f           |
dz  }
r#%# ||j        |j        |d           ||j        z  }|	                    ||
|j        f           |
dz  }
|j        }|j        }1|                    d          x}|                    d          }|                    d          }||J t1          t3          j        ||          ||          }t7          ||||||          }r#%#|                                }|                                }|r)t9          j        |          rt;          d| d|          |                    d          x},|rt=          |          dz
  nd}|                                }P|                    d          x}x|rt=          |          nd}||z   }||k     rB||k    r<t?          tA          ||          tC          ||                    D ]} |d|           |}|                                }|                    d          x}]|rt=          |          nd}|r||k    rt;          d| d| d| d           tA          d||z
            }|                                }S|	                    ||
|                                f           |
dz  }
r#%#|                                }|d!k    r	d}|dz  }|d"k    r|dk    r|dz  }|dz  }|d#k    rj|dk    r:||||z  z
  z   }||k     r(||cxk    r|k     rn n |d|           |dz  }||k     (n#|	                    ||
d#f           |
dz  }
r#%#|dz  }5tE          tG          | |$                    }tI          ||%          } | dk    r4||cxk    r|k     r&n n|	                    ||
|f           |
dz  }
r#%#nr||k    r|| z   |k    r ||| |           nU||k     rO|| z   |k    rFtA          ||          }!t?          tC          ||| z             |!z
            D ]}" |d|!|"z              || z  }|t          |          z  }|t          |           k     'tK          $|	||          #fS )(z
    Clip text with cursor movement (painter's algorithm path).

    Returns ``(result, captured_style)``.  The caller applies SGR wrapping.
    r   NFr}   r.   wr*   	write_colis_hyperlinkrr   r8   r   c                    t          |          D ]}||z   }|dk    rE                    |dz
  d          d         dk    r"	df|dz
  <   
                    |dz
                                 |d          d         dk    r"	df|dz   <   
                    |dz                                  |d           
                    |           | |f|<   |r*t          |          D ]}
                    ||z              r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   r_   discardpopadd)r}   r   r   r   offsetsrc_colr6   rT   r   r?   hyperlink_cellsrI   s         r&   _write_cellsz#_clip_painter.<locals>._write_cells  sX    Ahh 		- 		-F&(G{{uyy1g>>qAQFF&.]gk"''!444yy'**1-22&.]gk"''!444IIgt$$$##G,,,,q6i 	8(( 8 8##I$67777 	+^3*NNN	+ 	+33r%   rv   r	   rw   rx   T)r   ry   rz   r{   r|   r   r   hpa_n
cforward_ncbackward_nz!Cursor left movement at position z would move z cells left from column z, exceeding string startr   r   r   )F)
r}   r.   r   r*   r   r*   r   rr   r8   r   )&setr   r   r   r   rZ   r   r   r>   r   r   rS   r)   r   r    r!   r+   r"   r,   r/   r0   r2   r1   r3   r   r   r   r   r   r   r*   r   rK   r^   r   r   r
   rq   )'r<   r=   r>   rI   rA   r?   r@   rs   rB   rV   	seq_orderrF   r   r   r   r   r   r   ry   rz   r{   r   r   r   r   	n_forwardmove_endr   r   
n_backwardr   r   r   
clip_startr   r6   rT   r   r   s'      ` `                             @@@@r&   _clip_painterr     sa   * )+E #O,.II
C
C +/N*7A&&TM +0+ + + + + + + + + + + +* D		//Cy #::.46>>"(s33A   #y$!7888Q	  3^%;%2Nq ww|$$0]0}G` 1- K Keegg +0;;;x &%h!#quuwwC  
 8/888$$c9aggii%@AAANI$ 7)?)6%%''CCX!1!777+CCX!1!9991=(C+CC$$c9aj%ABBBNI$ 7)?)6 L!/3.24 4 4 41?*C$$c9ak%BCCCNI,C+C 779---:''),,''),,*w/B/BB$0VVVW& & (UC? " " ! 3^%;%2Neegg ''))C 7=cBB        )))6(-4c%jj1nn1eegg  ggl333
@/9@C
OOOq	?99E!1!1"3sE??C#4F4FGG 5 5$Xq!4444eegg  !ww}555B1<CS---!
 j3..$2C 2 2%2 2?B2 2 2  
 !S:-..eegg c9aggii8999NI /!7!.%%''C 4<<C1HC 6>>Qwwq1HC 4<<{{'S7]";<Hnn))))c)))))$Xq#6661HC Hnn
   #y$!7888Q	  3^%;%2N1HC t3777888_EEE
 ??!!!!c!!!!!  #y(!;<<<Q	  3^%;%2NE\\cJ.#55L:s33333YY3+e33UCJCz)9 : :Z GHH ? ?Xq*v*=>>>>zs8}}M D		//P  y%hGGWWr%   r      Tr   )r?   r@   rA   rI   rB   
overtypingr   Optional[bool]c                  t          |d          }||k    rdS |                                 r|                                 r
| ||         S d| v }	|r|	sd}|2|dk    o*d| v p&d| v p"|	o t          t	          j        |                     }n
|r|dk    rd}|rt          nt          }
t           |
| |||||||d	k    |
	  	         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-   rv   FNignorer   r   rs   )	r<   r=   r>   rI   rA   r?   r@   rs   rB   )	rK   isasciiisprintablerr   r   searchr   r   r;   )r<   r=   r>   r?   r@   rA   rI   rB   r   has_escfn_clips              r&   rL   rL     s-   J qMME
e||r ||~~ $**,, E#I nG W   X% Kt^ Jtt| JH$:A$GGHH 	

 
 11
);mm|GGG#')#
 
 
 
 
r%   )r5   r.   r6   r7   r8   r.   )r<   r.   r=   r*   r>   r*   r?   r.   r@   r*   rA   r*   rB   rC   rD   r   rE   r*   rF   r*   r8   r(   )rT   rU   rV   rW   r=   r*   r>   r*   r?   r.   r8   r.   )r<   r.   r=   r*   r>   r*   rI   rr   rA   r*   r?   r.   r@   r*   rs   rr   rB   rC   r8   rt   )r   r   rF   r*   r=   r*   r>   r*   r?   r.   rA   r*   r   r   r8   r*   )r<   r.   r=   r*   r>   r*   r?   r.   r@   r*   rA   r*   rI   rr   rB   rC   r   r   r8   r.   ))r   
__future__r   r   	itertoolsr   typingr   r   r   r   _widthr
   r   r   	hyperlinkr   r   	sgr_stater   r   r   r   r   text_sizingr   r   escape_sequencesr   r   r   Enumr   r(   r;   rS   rq   r   r   r   rL   r$   r%   r&   <module>r      sU   0 0 " " " " " "        : : : : : : : : : : : :       $ $ $ $ $ $ 1 1 1 1 1 1 1 10 0 0 0 0 0 0 0 0 0 0 0 0 0
 6 5 5 5 5 5 5 5> > > > > > > > > >
    ty       z   "   ? ? ? ?D4 4 4 4nh+ h+ h+ h+VR R R RjcX cX cX cXV :A!%H H H H H H H Hr%   