}BFjI dZddlZddlZddlZddlZddlZddlZddlmZddlm Z ddl m Z m Z m Z mZmZmZmZmZddlmZmZmZmZddl mZGdd eZGd d eeZdd(e ed)ed*edee efd+Z(d,e ed*ed-ed.ede eeff d/Z)ed0Z*d1e e*d2ed3e*de*fd4Z+ d?d7e ed8ed9ed:edef d;Z,dS)@z~ Utilities for working with strings and text. Inheritance diagram: .. inheritance-diagram:: IPython.utils.text :parts: 3 N) Formatter)Path)ListDictTupleOptionalcastAnyUnionTypeVar)SequenceMappingCallableIterator)SelfceZdZUdZeeed<eed<eeed<deefdZe exZ Z defdZ e e xZ ZdefdZe exZZdeefd Ze exZZd S) LSStringa`String derivative with a special access attributes. These are normal strings, but with the special attributes: .l (or .list) : value as list (split on newlines). .n (or .nlstr): original value (the string itself). .s (or .spstr): value as whitespace-separated string. .p (or .paths): list of path objects (requires path.py package) Any values which require transformations are computed only once and cached. Such strings are very useful to efficiently interact with the shell, which typically only understands whitespace-separated options for commands._LSString__list_LSString__spstr_LSString__pathsreturnct |jS#t$r$|d|_|jcYSwxYwN )rAttributeErrorsplitselfs @C:\PYTHON\_runtimes\venv\Lib\site-packages\IPython/utils/text.pyget_listzLSString.get_list6sK ;    **T**DK;      +77cv |jS#t$r%|dd|_|jcYSwxYw)Nr )rrreplacers r get_spstrzLSString.get_spstr?sM <    <<S11DL<    s  ,88c|SNrs r get_nlstrzLSString.get_nlstrH c |jS#t$r.d|dD|_|jcYSwxYw)Ncjg|]0}tj|!t|1Sr(ospathexistsr.0ps r z&LSString.get_paths..Qs2SSSPQARARSDGGSSSr+r)rrrrs r get_pathszLSString.get_pathsMsY <    SSTZZ-=-=SSSDL<    s 5AAN)__name__ __module__ __qualname____doc__rstr__annotations__rr propertyllistr%sspstrrr)nnlstrr6r4pathsr(r+rrr"s M M I LLL $Z$s)x!!!A 3    ###A4###A 4:    ###Ar+rc eZdZUdZeed<eed<eeed<defdZ e e xZ Z defdZ e e xZZdefdZe exZZdeefd Ze exZZ dd eeeegejed zffd edeedefdZdeedeeefdZ ddeeededefdZ d S)SListaList derivative with a special access attributes. These are normal lists, but with the special attributes: * .l (or .list) : value as list (the list itself). * .n (or .nlstr): value as a string, joined on newlines. * .s (or .spstr): value as a string, joined on spaces. * .p (or .paths): list of path objects (requires path.py package) Any values which require transformations are computed only once and cached. _SList__spstr _SList__nlstr _SList__pathsrc|Sr'r(rs rr zSList.get_listtr*r+ct |jS#t$r$d||_|jcYSwxYw)Nr#)rGrjoinrs rr%zSList.get_spstrysI <    88D>>DL<    r!ct |jS#t$r$d||_|jcYSwxYwr)rHrrLrs rr)zSList.get_nlstrsI <    99T??DL<    r!cb |jS#t$rd|D|_|jcYSwxYw)Ncjg|]0}tj|!t|1Sr(r.r2s rr5z#SList.get_paths..s1GGGRW^^A5F5FGDGGGGGr+)rIrrs rr6zSList.get_pathssM <    GGTGGGDL<    s  "..FNpatternprunefieldcdtdtffd ttrfdn|s%t|fd|DSt|fd|DS)aReturn all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. If field is specified, the match must occur in the specified whitespace-separated field. Examples:: a.grep( lambda x: x.startswith('C') ) a.grep('Cha.*log', prune=1) a.grep('chm', field=-1) r@rcl|S|} |}|S#t$rYdSwxYw)N)r IndexError)r@partstgtrRs r match_targetz SList.grep..match_targetsO}GGIIE El    rr s % 33cDtj|tjSr')research IGNORECASE)xrPs rzSList.grep..sbiBMBBr+c<g|]}||Sr(r(r3elrYpreds rr5zSList.grep..s2KKKbDDb9I9I4J4JKrKKKr+c<g|]}||Sr(r(ras rr5zSList.grep..s2OOOb\\"=M=M8N8NOrOOOr+)r; isinstancetype)rrPrQrRrYrcs ` `@@rgrepz SList.greps* C C       gs # # BBBBDDD Q4::KKKKKDKKKLL L4::OOOOODOOOPP Pr+fieldsc8t|dkr d|DSt}d|DD]_}g}|D].} |||#t$rY+wxYw|r(|d|`|S)a{Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. Example data (in var a, created by 'a = !ls -l'):: -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']`` * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']`` (note the joining by space). * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']`` IndexErrors are ignored. Without args, fields() just split()'s the strings. rc6g|]}|Sr(r)r3rbs rr5z SList.fields..s ...2BHHJJ...r+c6g|]}|Sr(rk)r3fs rr5z SList.fields..s +++17799+++r+r#)lenrFappendrVrL)rrhresrb linepartsfds rrhz SList.fieldss& v;;!  ..... .gg++d+++ 0 0BI  $$RV,,,,!D 0 388I../// sA A,+A,numscfd|D}n d|D}|rxtt|D][}dd||dD} t|}n#t$rd}YnwxYw|||d<\|t |d|DS)zsort by specified fields (see fields()) Example:: a.sort(1, nums = True) Sorts a by second field, in numerical order (so that 21 > 3) NcZg|]'}t|g|g(Sr()rFrh)r3linerRs rr5zSList.sort..s4IIIDE4&MM((//$7IIIr+cg|]}||gSr(r()r3rvs rr5zSList.sort..s222TD4=222r+rUc:g|]}||Sr()isdigit)r3chs rr5zSList.sort..s%!I!I!IBJJLL!I"!I!I!Ir+rcg|] }|d S)r()r3ts rr5zSList.sort..s---A1Q4---r+)rangernrLint ValueErrorsortrf)rrRrsdsuinumstrrBs ` rrz SList.sorts  IIIIDIIICC22T222C  3s88__  !I!Is1vay!I!I!IJJF AA!AAAAq   tDzz-----...s+A;; B  B )FN)NF)!r7r8r9r:r;r<rrrr r=r>r?r%r@rAr)rBrCr6r4rDr rr r[Matchboolrrrgrhrr(r+rrFrFcs  LLL LLL $Z$x!!!A 3    ###A 3    ###A 4:    ###A # &Q&QsHcUBHSMD,@%@AAB&Q&Q} &Q  &Q&Q&Q&QP"d3i"DcO""""L&*//S "//  //////r+rFFinstrnspacesntabsflattenrc>d|zd|zz}|r tjdtj}ntjdtj}tj|||}|t j|zr|dt| S|S)aIndent a string a given number of spaces or tabstops. indent(str, nspaces=4, ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented. flatten : bool (default: False) Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased. Returns ------- str : string indented by ntabs and nspaces.  r#z^\s*^N)r[compile MULTILINEsubendswithr/lineseprn)rrrrindpatoutstrs rindentrs. ,w &C-j",//jr|,, VCe $ $F rz#~&&jCyj!! r+argc6t|tr|gS|S)aAlways return a list of strings, given a string or list of strings as input. Examples -------- :: In [7]: list_strings('A single string') Out[7]: ['A single string'] In [8]: list_strings(['A single string in a list']) Out[8]: ['A single string in a list'] In [9]: list_strings(['A','list','of','strings']) Out[9]: ['A', 'list', 'of', 'strings'] )rer;)rs r list_stringsr%s"$#su  r+rUN*txtwidthmarkc|s ||zd|S|t|z dz t|zdz}|dkrd}||z}|d|d|S)aReturn the input string centered in a 'marquee'. Examples -------- :: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' In [18]: marquee('A test',40,' ') Out[18]: ' A test ' Nrr#rn)rrrnmarkmarkss rmarqueer=sp" $U FUF## 3s88^A D )1 ,E qyy% JEsss55 ))r+strngcptjdtj}|d|}|S)zTFormat a string for screen printing. This removes some latex-type format codes.z\\$rU)r[rrr)rpar_res r format_screenrVs/ Zr| , ,F JJr% E Lr+textc.|drtj|S|dd}t |dkrtj|S|\}}tj|}d||gS)zEquivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. rr|) startswithtextwrapdedentrrnrL)rsplitsfirstrests rrr`s t%t$$$ZZQ  F 6{{at$$$KE4 ?4 D 99eT] # ##r+c|}dt|D]F}tt|dkrn#|d}|tjvs|dkrdz Fdfd|D}|S)aNStrip leading email quotation characters ('>'). Removes any combination of leading '>' interspersed with whitespace that appears *identically* in all lines of the input text. Parameters ---------- text : str Examples -------- Simple uses:: In [2]: strip_email_quotes('> > text') Out[2]: 'text' In [3]: strip_email_quotes('> > text\n> > more') Out[3]: 'text\nmore' Note how only the common prefix that appears in all lines is stripped:: In [4]: strip_email_quotes('> > text\n> > more\n> more...') Out[4]: '> text\n> more\nmore...' So if any line has no quote marks ('>'), then none are stripped from any of them :: In [5]: strip_email_quotes('> > text\n> > more\nlast different') Out[5]: '> > text\n> > more\nlast different' rr|>rc$g|] }|d Sr'r()r3ln strip_lens rr5z&strip_email_quotes..s!555bn555r+) splitlinesziprnsetstring whitespacerL)rlines characters prefix_charrs @rstrip_email_quotesr{s@ OO  EI5k   s:  ! # # E m &+ + +{c/A/A NII  995555u555 6 6D Kr+c :eZdZdZdedededeeeffdZdS) EvalFormattera+A String Formatter that allows evaluation of simple expressions. Note that this version interprets a `:` as specifying a format string (as per standard string formatting), so if slicing is required, you must explicitly create a slice. Note that on Python 3.14+ this version interprets `[]` as indexing operator so you need to use generators instead of list comprehensions, for example: `list(i for i in range(10))`. This is to be used in templating cases, such as the parallel batch script templates, where simple arithmetic on arguments is useful. Examples -------- :: In [1]: f = EvalFormatter() In [2]: f.format('{n//4}', n=8) Out[2]: '2' In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello") Out[3]: 'll' nameargskwargsrc,t|||}||fSr')eval)rrrrvs r get_fieldzEvalFormatter.get_fields vv & &$wr+N)r7r8r9r:r;r rrr(r+rrrsV2cceCHor+rcFeZdZdZdedeedeeefdefdZdS)FullEvalFormatteraiA String Formatter that allows evaluation of simple expressions. Any time a format key is not found in the kwargs, it will be tried as an expression in the kwargs namespace. Note that this version allows slicing using [1:2], so you cannot specify a format string. Use :class:`EvalFormatter` to permit format strings. Examples -------- :: In [1]: f = FullEvalFormatter() In [2]: f.format('{n//4}', n=8) Out[2]: '2' In [3]: f.format('{list(range(5))[2:4]}') Out[3]: '[2, 3]' In [4]: f.format('{3*2}') Out[4]: '6' format_stringrrrcg}||D]\}}}}|r|||u|rd||g}t|t |} || |} ||| dd|S)N:rU)parserorLrdict convert_field format_field) rrrrresult literal_text field_name format_spec conversionobjs rvformatzFullEvalFormatter.vformatsAE B B  : : =L*k: , l+++%E!$:{*C!D!DJ:tF||44((j99 d//R88999wwvr+N) r7r8r9r:r;r r rrr(r+rrrs_0   (0  ?FsCx?P        r+rc neZdZdZejdZdedee e e e e ffdZ defdZ dS)DollarFormatteraFormatter allowing Itpl style $foo replacement, for names and attribute access only. Standard {foo} replacement also works, and allows full evaluation of its arguments. Examples -------- :: In [1]: f = DollarFormatter() In [2]: f.format('{n//4}', n=8) Out[2]: '2' In [3]: f.format('23 * 76 is $result', result=23*76) Out[3]: '23 * 76 is 1748' In [4]: f.format('$a or {b}', a=1, b=2) Out[4]: '1 or 2' z,(.*?)\$(\$?[\w\.]+)(?=([^']*'[^']*')*[^']*$) fmt_stringrc#\Ktj||D]\}}}}d}d}|j|D]Z}|dd\} } | dr || | zz }n || z| ddfVd}|}[|||dz|||fVdS)NrrUr|r$)rr#_dollar_pattern_ignore_single_quotefinditergrouprend) rr literal_txtrrr continue_fromrmnew_txt new_fields rrzDollarFormatter.parse#s@I *A A  [ [ >>>C ! ]^^44j+zZ Z Z Z Z# [ [r+cdS)Nzr(rs r__repr__zDollarFormatter.__repr__7s""r+N) r7r8r9r:r[rrr;rrr rrr(r+rrr s&+5"*7++'[[sCc7I1J(K[[[[(########r+rr>max_rows row_firstc#BK|rit|zt|zdkz}t|D].}fdt|t|DV/dStdt|D]}|||zVdS)z5Yield successive max_rows-sized column chunks from l.rc g|] }| Sr(r()r3jr>s rr5z_col_chunks..Fs999A1Q4999r+N)rnr~)r>rrncolsrs` r _col_chunksr?s&Q8#A(9A(=>u : :A9999q#a&&%!8!8999 9 9 9 9 : :q#a&&(++ & &AAq8|$% % % % % & &r+rlistseparator_size displaywidthc 6tdt|dzD]b}tttt |||}t |}t|}|||dz zz|krnc||dz r ||z |dz znd||dS)z4Calculate optimal info to columnize a list of stringr|r) num_columnsoptimal_separator_widthr column_widths)r~rnr?mapmaxrsum)rrrrr col_widths sumlengthrs r _find_optimalrLs!SZZ!^,,#c;uh #J#JKKLL  OO J ~3 3| C C E D UZ]^U^'f y(@eai'P'Pef '  r+Tmylistrdefaultc<|t|kr|S||S)z2return list item number, or default if don't existr)rrrs r_get_or_defaultr`s"CKKayr+ and , list_last_sepsepwrap_item_withct|dkrdSrfd|D}t|dkr|dS|d|ddD||dS)a Return a string with a natural enumeration of items >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c and d' >>> get_text_list(['a', 'b', 'c'], ' or ') 'a, b or c' >>> get_text_list(['a', 'b', 'c'], ', ') 'a, b, c' >>> get_text_list(['a', 'b'], ' or ') 'a or b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' >>> get_text_list(['a', 'b'], wrap_item_with="`") '`a` and `b`' >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ") 'a + b + c = d' rrUc g|] }| Sr(r()r3itemrs rr5z!get_text_list..s6   ,^TT>>B   r+r|c3K|]}|VdSr'r()r3rs r z get_text_list..s"''q''''''r+N)rnrL)rrrrs `r get_text_listrhs. 5zzQr         5zzQQx ''E#2#J''''''%)) r+)rrF)rUrr)F)rrrU)-r:r/r[rsysrwarningsrpathlibrtypingrrrrr r r r collections.abcr rrrrr;rr?rFrrrrrrrrrrrrrrrrr(r+rrs%                     BAAAAAAAAAAA2$2$2$2$2$s2$2$2$B\/\/\/\/\/DI\/\/\/~  #   $ SV    FeCcN+S 0***#*#*****2$$$$$$6/S/S////dID99999 999x-#-#-#-#-#'-#-#-#j49 & & Cy & &,0 & d3i & & & & 9!%7:JM #s(^" GCLLDGaAWY   9  # 47 PS       r+