
    gfB                         d Z ddlZddlZddlZddlZddlmZ ddlmZ dZ G d de	      Z
 G d d	ej                        Zej                  j                   e_          G d
 dej                        Zd Zd Zy)z&Module providing 'sequence awareness'.    N)wcwidth)CAPABILITIES_CAUSE_MOVEMENT)SequenceSequenceTextWrapper
iter_parsemeasure_lengthc                   j    e Zd ZdZd Zd Zed        Zed        Zed        Z	d Z
e	 	 	 d
d       Zy	)Termcapz7Terminal capability of given variable name and pattern.c                 <    || _         || _        || _        d| _        y)z
        Class initializer.

        :arg str name: name describing capability.
        :arg str pattern: regular expression string.
        :arg str attribute: :class:`~.Terminal` attribute used to build
            this terminal capability.
        N)namepattern	attribute_re_compiled)selfr   r   r   s       i/var/dept/share/cheung/public_html/OutSchool/python/env/lib/python3.12/site-packages/blessed/sequences.py__init__zTermcap.__init__   s!     	"     c                 &    dj                  |       S )Nz&<Termcap {self.name}:{self.pattern!r}>r   formatr   s    r   __repr__zTermcap.__repr__#   s    7>>D>IIr   c                 &    dj                  |       S )z;Regular expression pattern for capability with named group.z(?P<{self.name}>{self.pattern})r   r   r   s    r   named_patternzTermcap.named_pattern'   s     177T7BBr   c                 z    | j                   $t        j                  | j                        | _         | j                   S )z3Compiled regular expression pattern for capability.)r   recompiler   r   s    r   re_compiledzTermcap.re_compiled-   s1     $ "

4<< 8D   r   c                 &    | j                   t        v S )z*Whether capability causes cursor movement.)r   r   r   s    r   	will_movezTermcap.will_move4   s     yy777r   c                     ddddddj                  | j                        }||S dddj                  | j                        }|8t        | j                  j	                  |      j                  d            }||z  S y)aA  
        Horizontal carriage adjusted by capability, may be negative.

        :rtype: int
        :arg str text: for capabilities *parm_left_cursor*,
            *parm_right_cursor*, provide the matching sequence
            text, its interpreted distance is returned.

        :returns: 0 except for matching '
              )cursor_left	backspacecursor_righttab	ascii_tab)parm_left_cursorparm_right_cursorr   )getr   intr   matchgroup)r   textvalueunits       r   horizontal_distancezTermcap.horizontal_distance9   s     
 #dii. 	 L !#!"
 #dii. 	 ((..t4::1=>E%<r   c	                    d|rd|rd|dn|}|dk(  r | |t        j                  |      |      S t        j                   ||f|z         }	|sKt        |dz
  |dz         D ]6  }
t        |
      |	v s|	j	                  t        |
            } | |||      c S  |rt        j
                  dfd|	      }nt        j
                  dfd	|	      } | |||      S )
ak  
        Class factory builder for given capability definition.

        :arg str name: Variable name given for this pattern.
        :arg str capability: A unicode string representing a terminal
            capability to build for. When ``nparams`` is non-zero, it
            must be a callable unicode string (such as the result from
            ``getattr(term, 'bold')``.
        :arg str attribute: The terminfo(5) capability name by which this
            pattern is known.
        :arg int nparams: number of positional arguments for callable.
        :arg int numeric: Value to substitute into capability to when generating pattern
        :arg bool match_grouped: If the numeric pattern should be
            grouped, ``(\d+)`` when ``True``, ``\d+`` default.
        :arg bool match_any: When keyword argument ``nparams`` is given,
            *any* numeric found in output is suitable for building as
            pattern ``(\d+)``.  Otherwise, only the first matching value of
            range *(numeric - 1)* through *(numeric + 1)* will be replaced by
            pattern ``(\d+)`` in builder.
        :arg bool match_optional: When ``True``, building of numeric patterns
            containing ``(\d+)`` will be built as optional, ``(\d+)?``.
        :rtype: blessed.sequences.Termcap
        :returns: Terminal capability instance for given capability definition
        z\d+z(\d+)z(\d+)?c   r   r#      c                     S N x_numeric_regexs    r   <lambda>zTermcap.build.<locals>.<lambda>   s     r   c                     S r8   r9   r:   s    r   r=   zTermcap.build.<locals>.<lambda>   s    ~ r   )r   escaperangestrreplacesub)clsr   
capabilityr   nparamsnumericmatch_grouped	match_anymatch_optional_outpnumr   r<   s               @r   buildzTermcap.buildY   s    8  %N&N"W a<tRYYz2I>> 		*wj7&:;<Wq['A+6 9s8u$#mmCHnEGtWi889
 ffX'?GGffV%=uEG4),,r   N)r   r5   FFF)__name__
__module____qualname____doc__r   r   propertyr   r   r    r3   classmethodrM   r9   r   r   r
   r
      sq    A!J C C
 ! ! 8 8@ 899>"2- 2-r   r
   c                   "    e Zd ZdZd Zd Zd Zy)r   zDocstring overridden.c                 T    || _         t        j                  j                  | |fi | y)ze
        Class initializer.

        This class supports the :meth:`~.Terminal.wrap` method.
        N)termtextwrapTextWrapperr   )r   widthrV   kwargss       r   r   zSequenceTextWrapper.__init__   s&     	%%dE<V<r   c                    g }| j                   dk  st        | j                   t              s8t        dj	                  | j                   t        | j                                     | j                  }t        | d       xs | j                  }|j                          |r2g }d}|r| j                  n| j                  }| j                   t        |      z
  }|r%t        |d   |      j                         dk(  r|r|d= |rMt        |d   |      j                         }	||	z   |kD  rn'|j!                  |j#                                ||	z  }|rM|r4t        |d   |      j                         |kD  r| j%                  ||||       |r%|r#t        |d   |      j                         dk(  r|d= |r#|j!                  |dj'                  |      z          |r2|S )a4  
        Sequence-aware variant of :meth:`textwrap.TextWrapper._wrap_chunks`.

        :raises ValueError: ``self.width`` is not a positive integer
        :rtype: list
        :returns: text chunks adjusted for width

        This simply ensures that word boundaries are not broken mid-sequence, as standard python
        textwrap would incorrectly determine the length of a string containing sequences, and may
        also break consider sequences part of a "word" that may be broken by hyphen (``-``), where
        this implementation corrects both.
        r   z0invalid width {0!r}({1!r}) (must be integer > 0)drop_whitespacer"    )rY   
isinstancer-   
ValueErrorr   typerV   hasattrr\   reversesubsequent_indentinitial_indentlenr   striplengthappendpop_handle_long_wordjoin)
r   chunkslinesrV   r\   cur_linecur_lenindentrY   	chunk_lens
             r   _wrap_chunksz SequenceTextWrapper._wrap_chunks   s    ::?*TZZ"=B

D$457 7 yy%d,= ( ( @+/+?+? 	HG/4T++$:M:MFJJV,EVBZ.446"<2J$VBZ6==?	Y&.

-9$  (6":t4;;=E&&vx%H(2,!=!C!C!E!KRLVchhx&889) * r   c                 h   |dk  rdn||z
  }| j                   rx| j                  }|d   }dx}}	t        ||      D ]7  \  }
}|	t        |
      z  }	t	        |d|	 |      j                         |kD  r n|	}9 |j                  |d|        ||d |d<   y|s |j                  |j                                yy)a  
        Sequence-aware :meth:`textwrap.TextWrapper._handle_long_word`.

        This simply ensures that word boundaries are not broken mid-sequence, as standard python
        textwrap would incorrectly determine the length of a string containing sequences, and may
        also break consider sequences part of a "word" that may be broken by hyphen (``-``), where
        this implementation corrects both.
        r#   r"   r   N)break_long_wordsrV   r   re   r   rg   rh   ri   )r   reversed_chunksrn   ro   rY   
space_leftrV   chunkidxnxtr0   _s               r   rj   z%SequenceTextWrapper._handle_long_word   s      !)Q
   99D#B'EMC#%dE2 as4y E$3K.557*D	
 OOE$3K("'+OB
 OOO//12 r   N)rN   rO   rP   rQ   r   rr   rj   r9   r   r   r   r      s    =,\3r   r   c                   `    e Zd ZdZd ZddZddZddZd Zd Z	dd	Z
dd
ZddZd ZddZy)r   a  
    A "sequence-aware" version of the base :class:`str` class.

    This unicode-derived class understands the effect of escape sequences
    of printable length, allowing a properly implemented :meth:`rjust`,
    :meth:`ljust`, :meth:`center`, and :meth:`length`.
    c                 T    t         j                  j                  | |      }||_        |S )z
        Class constructor.

        :arg str sequence_text: A string that may contain sequences.
        :arg blessed.Terminal term: :class:`~.Terminal` instance.
        )six	text_type__new___term)rD   sequence_textrV   news       r   r   zSequence.__new__   s&     mm##C7	
r   c                     |t        t        dt        |j                         | j	                         z
              t        t        |            z        z  }dj                  | |f      S )aq  
        Return string containing sequences, left-adjusted.

        :arg int width: Total width given to left-adjust ``text``.  If
            unspecified, the width of the attached terminal is used (default).
        :arg str fillchar: String for padding right-of ``text``.
        :returns: String of ``text``, left-aligned by ``width``.
        :rtype: str
                r]   r-   maxfloat	__index__rg   re   rk   )r   rY   fillchar	rightsides       r   ljustzSequence.ljust	  sZ     seEOO-=>?5XCWW Y Y	xxy)**r   c                     |t        t        dt        |j                         | j	                         z
              t        t        |            z        z  }dj                  || f      S )as  
        Return string containing sequences, right-adjusted.

        :arg int width: Total width given to right-adjust ``text``.  If
            unspecified, the width of the attached terminal is used (default).
        :arg str fillchar: String for padding left-of ``text``.
        :returns: String of ``text``, right-aligned by ``width``.
        :rtype: str
        r   r]   r   )r   rY   r   leftsides       r   rjustzSequence.rjust  sZ     ceEOO-=>?5XCWWY Yxx4())r   c           	         t        dt        |j                               | j                         z
        dz  }|t	        t        dt        j                  |            t        t        |            z        z  }|t	        t        dt        j                  |            t        t        |            z        z  }dj                  || |f      S )al  
        Return string containing sequences, centered.

        :arg int width: Total width given to center ``text``.  If
            unspecified, the width of the attached terminal is used (default).
        :arg str fillchar: String for padding left and right-of ``text``.
        :returns: String of ``text``, centered by ``width``.
        :rtype: str
        r   r6   r]   )
r   r   r   rg   r-   mathfloorre   ceilrk   )r   rY   r   splitr   r   s         r   centerzSequence.center%  s     Cu01DKKMABQFcdjj'(E#h-,@@B Bsdii&'5X+?? A A	xx4344r   c                    d}d}|j                         }t        | j                  | j                               }|D ]+  \  }}|s|t	        t        |      d      z  }||kD  r n||z  }- |dj                  d |D              z   S )a  
        Truncate a string in a sequence-aware manner.

        Any printable characters beyond ``width`` are removed, while all
        sequences remain in place. Horizontal Sequences are first expanded
        by :meth:`padd`.

        :arg int width: The printable width to truncate the string to.
        :rtype: str
        :returns: String truncated to at most ``width`` printable characters.
        r]   r   c              3   ,   K   | ]  \  }}|s	|  y wr8   r9   ).0r0   caps      r   	<genexpr>z$Sequence.truncate.<locals>.<genexpr>Q  s     HsCHs   
)r   r   r   paddr   r   rk   )r   rY   outputcurrent_widthtarget_width
parsed_seqr0   r   s           r   truncatezSequence.truncate6  s     (

DIIK8
 $ 	ID#WT]A!66 </dNF	 HjHHHHr   c                 F    t        d | j                  d      D              S )u  
        Return the printable length of string containing sequences.

        Strings containing ``term.left`` or ``\b`` will cause "overstrike",
        but a length less than 0 is not ever returned. So ``_\b+`` is a
        length of 1 (displays as ``+``), but ``\b`` alone is simply a
        length of 0.

        Some characters may consume more than one cell, mainly those CJK
        Unified Ideographs (Chinese, Japanese, Korean) defined by Unicode
        as half or full-width characters.

        For example:

            >>> from blessed import Terminal
            >>> from blessed.sequences import Sequence
            >>> term = Terminal()
            >>> msg = term.clear + term.red(u'コンニチハ')
            >>> Sequence(msg, term).length()
            10

        .. note:: Although accounted for, strings containing sequences such
            as ``term.clear`` will not give accurate returns, it is not
            considered lengthy (a length of 0).
        c              3   F   K   | ]  }t        t        |      d         yw)r   N)r   r   )r   w_chars     r   r   z"Sequence.length.<locals>.<genexpr>n  s     Ov3wv*Os   !Trf   )sumr   r   s    r   rg   zSequence.lengthS  s     6 O9NOOOr   Nc                 @    | j                         j                  |      S )a	  
        Return string of sequences, leading and trailing whitespace removed.

        :arg str chars: Remove characters in chars instead of whitespace.
        :rtype: str
        :returns: string of sequences with leading and trailing whitespace removed.
        )
strip_seqsrf   r   charss     r   rf   zSequence.stripp  s      &&u--r   c                 @    | j                         j                  |      S )z
        Return string of all sequences and leading whitespace removed.

        :arg str chars: Remove characters in chars instead of whitespace.
        :rtype: str
        :returns: string of sequences with leading removed.
        )r   lstripr   s     r   r   zSequence.lstripz        ''..r   c                 @    | j                         j                  |      S )z
        Return string of all sequences and trailing whitespace removed.

        :arg str chars: Remove characters in chars instead of whitespace.
        :rtype: str
        :returns: string of sequences with trailing removed.
        )r   rstripr   s     r   r   zSequence.rstrip  r   r   c                 &    | j                  d      S )z
        Return ``text`` stripped of only its terminal sequences.

        :rtype: str
        :returns: Text with terminal sequences removed
        Tr   )r   r   s    r   r   zSequence.strip_seqs  s     yyty$$r   c                     d}t        | j                  |       D ]?  \  }}|s||z  }|j                  |      }|dkD  r	|d|z  z  }-|dk  r|d| }8|r;||z  }A |S )z
        Return non-destructive horizontal movement as destructive spacing.

        :arg bool strip: Strip terminal sequences
        :rtype: str
        :returns: Text adjusted for horizontal movement
        r]   r    N)r   r   r3   )r   rf   outpr0   r   r1   s         r   r   zSequence.padd  s     #DJJ5 	ID#++D1Eqye#FU|	 r   )r   r8   )F)rN   rO   rP   rQ   r   r   r   r   r   rg   rf   r   r   r   r   r9   r   r   r   r      s@    
+*5"I:P:.//%r   r   c              #      K   | j                   j                  |      D ]>  }|j                  }|j                  |      }|dk(  r|df ,|| j                  |   f @ yw)z
    Generator yields (text, capability) for characters of ``text``.

    value for ``capability`` may be ``None``, where ``text`` is
    :class:`str` of length 1.  Otherwise, ``text`` is a full
    matching sequence of given capability.
    MISMATCHN)_caps_compiled_anyfinditer	lastgroupr/   caps)rV   r0   r.   r   r1   s        r   r   r     sd      ((11$7 )D!:$-4(()s   AA c                 p    	 t        t        ||             \  } }|rt        |       S 	 y# t        $ r Y yw xY w)zk
    .. deprecated:: 1.12.0.

    :rtype: int
    :returns: Length of the first sequence in the string
    r   )nextr   re   StopIteration)r0   rV   rE   s      r   r   r     sH    
4 67jt9    s   $) 	55)rQ   r   r   rW   r}   r   blessed._capabilitiesr   __all__objectr
   rX   r   r~   r   r   r   r9   r   r   <module>r      s{    , 	     >
Mz-f z-zY3(.. Y3D '22::  xs}} xv)"r   