test_functions.vim 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917
  1. " Tests for various functions.
  2. source shared.vim
  3. source check.vim
  4. source term_util.vim
  5. source screendump.vim
  6. source vim9.vim
  7. " Must be done first, since the alternate buffer must be unset.
  8. func Test_00_bufexists()
  9. call assert_equal(0, bufexists('does_not_exist'))
  10. call assert_equal(1, bufexists(bufnr('%')))
  11. call assert_equal(0, bufexists(0))
  12. new Xfoo
  13. let bn = bufnr('%')
  14. call assert_equal(1, bufexists(bn))
  15. call assert_equal(1, bufexists('Xfoo'))
  16. call assert_equal(1, bufexists(getcwd() . '/Xfoo'))
  17. call assert_equal(1, bufexists(0))
  18. bw
  19. call assert_equal(0, bufexists(bn))
  20. call assert_equal(0, bufexists('Xfoo'))
  21. endfunc
  22. func Test_has()
  23. throw 'Skipped: Nvim has removed some features'
  24. call assert_equal(1, has('eval'))
  25. call assert_equal(1, has('eval', 1))
  26. if has('unix')
  27. call assert_equal(1, or(has('ttyin'), 1))
  28. call assert_equal(0, and(has('ttyout'), 0))
  29. call assert_equal(1, has('multi_byte_encoding'))
  30. call assert_equal(0, has(':tearoff'))
  31. endif
  32. call assert_equal(1, has('vcon', 1))
  33. call assert_equal(1, has('mouse_gpm_enabled', 1))
  34. call assert_equal(has('gui_win32') && has('menu'), has(':tearoff'))
  35. call assert_equal(0, has('nonexistent'))
  36. call assert_equal(0, has('nonexistent', 1))
  37. " Will we ever have patch 9999?
  38. let ver = 'patch-' .. v:version / 100 .. '.' .. v:version % 100 .. '.9999'
  39. call assert_equal(0, has(ver))
  40. endfunc
  41. func Test_empty()
  42. call assert_equal(1, empty(''))
  43. call assert_equal(0, empty('a'))
  44. call assert_equal(1, empty(0))
  45. call assert_equal(1, empty(-0))
  46. call assert_equal(0, empty(1))
  47. call assert_equal(0, empty(-1))
  48. if has('float')
  49. call assert_equal(1, empty(0.0))
  50. call assert_equal(1, empty(-0.0))
  51. call assert_equal(0, empty(1.0))
  52. call assert_equal(0, empty(-1.0))
  53. call assert_equal(0, empty(1.0/0.0))
  54. call assert_equal(0, empty(0.0/0.0))
  55. endif
  56. call assert_equal(1, empty([]))
  57. call assert_equal(0, empty(['a']))
  58. call assert_equal(1, empty({}))
  59. call assert_equal(0, empty({'a':1}))
  60. call assert_equal(1, empty(v:null))
  61. " call assert_equal(1, empty(v:none))
  62. call assert_equal(1, empty(v:false))
  63. call assert_equal(0, empty(v:true))
  64. if has('channel')
  65. call assert_equal(1, empty(test_null_channel()))
  66. endif
  67. if has('job')
  68. call assert_equal(1, empty(test_null_job()))
  69. endif
  70. call assert_equal(0, empty(function('Test_empty')))
  71. call assert_equal(0, empty(function('Test_empty', [0])))
  72. endfunc
  73. func Test_err_teapot()
  74. throw 'Skipped: Nvim does not have err_teapot()'
  75. call assert_fails('call err_teapot()', "E418: I'm a teapot")
  76. call assert_fails('call err_teapot(0)', "E418: I'm a teapot")
  77. call assert_fails('call err_teapot(v:false)', "E418: I'm a teapot")
  78. call assert_fails('call err_teapot("1")', "E503: Coffee is currently not available")
  79. call assert_fails('call err_teapot(v:true)', "E503: Coffee is currently not available")
  80. let expr = 1
  81. call assert_fails('call err_teapot(expr)', "E503: Coffee is currently not available")
  82. endfunc
  83. func Test_islocked()
  84. call assert_fails('call islocked(99)', 'E475:')
  85. call assert_fails('call islocked("s: x")', 'E488:')
  86. endfunc
  87. func Test_len()
  88. call assert_equal(1, len(0))
  89. call assert_equal(2, len(12))
  90. call assert_equal(0, len(''))
  91. call assert_equal(2, len('ab'))
  92. call assert_equal(0, len([]))
  93. call assert_equal(0, len(v:_null_list))
  94. call assert_equal(2, len([2, 1]))
  95. call assert_equal(0, len({}))
  96. call assert_equal(0, len(v:_null_dict))
  97. call assert_equal(2, len({'a': 1, 'b': 2}))
  98. " call assert_fails('call len(v:none)', 'E701:')
  99. call assert_fails('call len({-> 0})', 'E701:')
  100. endfunc
  101. func Test_max()
  102. call assert_equal(0, max([]))
  103. call assert_equal(2, max([2]))
  104. call assert_equal(2, max([1, 2]))
  105. call assert_equal(2, max([1, 2, v:null]))
  106. call assert_equal(0, max({}))
  107. call assert_equal(2, max({'a':1, 'b':2}))
  108. call assert_fails('call max(1)', 'E712:')
  109. " call assert_fails('call max(v:none)', 'E712:')
  110. " check we only get one error
  111. call assert_fails('call max([#{}, [1]])', ['E728:', 'E728:'])
  112. call assert_fails('call max(#{a: {}, b: [1]})', ['E728:', 'E728:'])
  113. endfunc
  114. func Test_min()
  115. call assert_equal(0, min([]))
  116. call assert_equal(2, min([2]))
  117. call assert_equal(1, min([1, 2]))
  118. call assert_equal(0, min([1, 2, v:null]))
  119. call assert_equal(0, min({}))
  120. call assert_equal(1, min({'a':1, 'b':2}))
  121. call assert_fails('call min(1)', 'E712:')
  122. " call assert_fails('call min(v:none)', 'E712:')
  123. call assert_fails('call min([1, {}])', 'E728:')
  124. " check we only get one error
  125. call assert_fails('call min([[1], #{}])', ['E745:', 'E745:'])
  126. call assert_fails('call min(#{a: [1], b: #{}})', ['E745:', 'E745:'])
  127. endfunc
  128. func Test_strwidth()
  129. for aw in ['single', 'double']
  130. exe 'set ambiwidth=' . aw
  131. call assert_equal(0, strwidth(''))
  132. call assert_equal(1, strwidth("\t"))
  133. call assert_equal(3, strwidth('Vim'))
  134. call assert_equal(4, strwidth(1234))
  135. call assert_equal(5, strwidth(-1234))
  136. call assert_equal(2, strwidth('😉'))
  137. call assert_equal(17, strwidth('Eĥoŝanĝo ĉiuĵaŭde'))
  138. call assert_equal((aw == 'single') ? 6 : 7, strwidth('Straße'))
  139. call assert_fails('call strwidth({->0})', 'E729:')
  140. call assert_fails('call strwidth([])', 'E730:')
  141. call assert_fails('call strwidth({})', 'E731:')
  142. endfor
  143. if has('float')
  144. call assert_equal(3, strwidth(1.2))
  145. call CheckDefExecAndScriptFailure(['echo strwidth(1.2)'], 'E806:')
  146. endif
  147. set ambiwidth&
  148. endfunc
  149. func Test_str2nr()
  150. call assert_equal(0, str2nr(''))
  151. call assert_equal(1, str2nr('1'))
  152. call assert_equal(1, str2nr(' 1 '))
  153. call assert_equal(1, str2nr('+1'))
  154. call assert_equal(1, str2nr('+ 1'))
  155. call assert_equal(1, str2nr(' + 1 '))
  156. call assert_equal(-1, str2nr('-1'))
  157. call assert_equal(-1, str2nr('- 1'))
  158. call assert_equal(-1, str2nr(' - 1 '))
  159. call assert_equal(123456789, str2nr('123456789'))
  160. call assert_equal(-123456789, str2nr('-123456789'))
  161. call assert_equal(5, str2nr('101', 2))
  162. call assert_equal(5, '0b101'->str2nr(2))
  163. call assert_equal(5, str2nr('0B101', 2))
  164. call assert_equal(-5, str2nr('-101', 2))
  165. call assert_equal(-5, str2nr('-0b101', 2))
  166. call assert_equal(-5, str2nr('-0B101', 2))
  167. call assert_equal(65, str2nr('101', 8))
  168. call assert_equal(65, str2nr('0101', 8))
  169. call assert_equal(-65, str2nr('-101', 8))
  170. call assert_equal(-65, str2nr('-0101', 8))
  171. call assert_equal(65, str2nr('0o101', 8))
  172. call assert_equal(65, str2nr('0O0101', 8))
  173. call assert_equal(-65, str2nr('-0O101', 8))
  174. call assert_equal(-65, str2nr('-0o0101', 8))
  175. call assert_equal(11259375, str2nr('abcdef', 16))
  176. call assert_equal(11259375, str2nr('ABCDEF', 16))
  177. call assert_equal(-11259375, str2nr('-ABCDEF', 16))
  178. call assert_equal(11259375, str2nr('0xabcdef', 16))
  179. call assert_equal(11259375, str2nr('0Xabcdef', 16))
  180. call assert_equal(11259375, str2nr('0XABCDEF', 16))
  181. call assert_equal(-11259375, str2nr('-0xABCDEF', 16))
  182. call assert_equal(1, str2nr("1'000'000", 10, 0))
  183. call assert_equal(256, str2nr("1'0000'0000", 2, 1))
  184. call assert_equal(262144, str2nr("1'000'000", 8, 1))
  185. call assert_equal(1000000, str2nr("1'000'000", 10, 1))
  186. call assert_equal(1000, str2nr("1'000''000", 10, 1))
  187. call assert_equal(65536, str2nr("1'00'00", 16, 1))
  188. call assert_equal(0, str2nr('0x10'))
  189. call assert_equal(0, str2nr('0b10'))
  190. call assert_equal(0, str2nr('0o10'))
  191. call assert_equal(1, str2nr('12', 2))
  192. call assert_equal(1, str2nr('18', 8))
  193. call assert_equal(1, str2nr('1g', 16))
  194. call assert_equal(0, str2nr(v:null))
  195. " call assert_equal(0, str2nr(v:none))
  196. call assert_fails('call str2nr([])', 'E730:')
  197. call assert_fails('call str2nr({->2})', 'E729:')
  198. if has('float')
  199. call assert_equal(1, str2nr(1.2))
  200. call CheckDefExecFailure(['echo str2nr(1.2)'], 'E1013:')
  201. call CheckScriptFailure(['vim9script', 'echo str2nr(1.2)'], 'E806:')
  202. endif
  203. call assert_fails('call str2nr(10, [])', 'E745:')
  204. endfunc
  205. func Test_strftime()
  206. CheckFunction strftime
  207. " Format of strftime() depends on system. We assume
  208. " that basic formats tested here are available and
  209. " identical on all systems which support strftime().
  210. "
  211. " The 2nd parameter of strftime() is a local time, so the output day
  212. " of strftime() can be 17 or 18, depending on timezone.
  213. call assert_match('^2017-01-1[78]$', strftime('%Y-%m-%d', 1484695512))
  214. "
  215. call assert_match('^\d\d\d\d-\(0\d\|1[012]\)-\([012]\d\|3[01]\) \([01]\d\|2[0-3]\):[0-5]\d:\([0-5]\d\|60\)$', '%Y-%m-%d %H:%M:%S'->strftime())
  216. call assert_fails('call strftime([])', 'E730:')
  217. call assert_fails('call strftime("%Y", [])', 'E745:')
  218. " Check that the time changes after we change the timezone
  219. " Save previous timezone value, if any
  220. if exists('$TZ')
  221. let tz = $TZ
  222. endif
  223. " Force different time zones, save the current hour (24-hour clock) for each
  224. let $TZ = 'GMT+1' | let one = strftime('%H')
  225. let $TZ = 'GMT+2' | let two = strftime('%H')
  226. " Those hours should be two bytes long, and should not be the same; if they
  227. " are, a tzset(3) call may have failed somewhere
  228. call assert_equal(strlen(one), 2)
  229. call assert_equal(strlen(two), 2)
  230. " TODO: this fails on MS-Windows
  231. if has('unix')
  232. call assert_notequal(one, two)
  233. endif
  234. " If we cached a timezone value, put it back, otherwise clear it
  235. if exists('tz')
  236. let $TZ = tz
  237. else
  238. unlet $TZ
  239. endif
  240. endfunc
  241. func Test_strptime()
  242. CheckFunction strptime
  243. CheckNotBSD
  244. CheckNotMSWindows
  245. if exists('$TZ')
  246. let tz = $TZ
  247. endif
  248. let $TZ = 'UTC'
  249. call assert_equal(1484653763, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
  250. " Force DST and check that it's considered
  251. let $TZ = 'WINTER0SUMMER,J1,J365'
  252. call assert_equal(1484653763 - 3600, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23'))
  253. call assert_fails('call strptime()', 'E119:')
  254. call assert_fails('call strptime("xxx")', 'E119:')
  255. " This fails on BSD 14 and returns
  256. " -2209078800 instead of 0
  257. call assert_equal(0, strptime("%Y", ''))
  258. call assert_equal(0, strptime("%Y", "xxx"))
  259. if exists('tz')
  260. let $TZ = tz
  261. else
  262. unlet $TZ
  263. endif
  264. endfunc
  265. func Test_resolve_unix()
  266. if !has('unix')
  267. return
  268. endif
  269. " Xlink1 -> Xlink2
  270. " Xlink2 -> Xlink3
  271. silent !ln -s -f Xlink2 Xlink1
  272. silent !ln -s -f Xlink3 Xlink2
  273. call assert_equal('Xlink3', resolve('Xlink1'))
  274. call assert_equal('./Xlink3', resolve('./Xlink1'))
  275. call assert_equal('Xlink3/', resolve('Xlink2/'))
  276. " FIXME: these tests result in things like "Xlink2/" instead of "Xlink3/"?!
  277. "call assert_equal('Xlink3/', resolve('Xlink1/'))
  278. "call assert_equal('./Xlink3/', resolve('./Xlink1/'))
  279. "call assert_equal(getcwd() . '/Xlink3/', resolve(getcwd() . '/Xlink1/'))
  280. call assert_equal(getcwd() . '/Xlink3', resolve(getcwd() . '/Xlink1'))
  281. " Test resolve() with a symlink cycle.
  282. " Xlink1 -> Xlink2
  283. " Xlink2 -> Xlink3
  284. " Xlink3 -> Xlink1
  285. silent !ln -s -f Xlink1 Xlink3
  286. call assert_fails('call resolve("Xlink1")', 'E655:')
  287. call assert_fails('call resolve("./Xlink1")', 'E655:')
  288. call assert_fails('call resolve("Xlink2")', 'E655:')
  289. call assert_fails('call resolve("Xlink3")', 'E655:')
  290. call delete('Xlink1')
  291. call delete('Xlink2')
  292. call delete('Xlink3')
  293. silent !ln -s -f Xdir//Xfile Xlink
  294. call assert_equal('Xdir/Xfile', resolve('Xlink'))
  295. call delete('Xlink')
  296. silent !ln -s -f Xlink2/ Xlink1
  297. call assert_equal('Xlink2', 'Xlink1'->resolve())
  298. call assert_equal('Xlink2/', resolve('Xlink1/'))
  299. call delete('Xlink1')
  300. silent !ln -s -f ./Xlink2 Xlink1
  301. call assert_equal('Xlink2', resolve('Xlink1'))
  302. call assert_equal('./Xlink2', resolve('./Xlink1'))
  303. call delete('Xlink1')
  304. call assert_equal('/', resolve('/'))
  305. endfunc
  306. func s:normalize_fname(fname)
  307. let ret = substitute(a:fname, '\', '/', 'g')
  308. let ret = substitute(ret, '//', '/', 'g')
  309. return ret->tolower()
  310. endfunc
  311. func Test_simplify()
  312. call assert_equal('', simplify(''))
  313. call assert_equal('/', simplify('/'))
  314. call assert_equal('/', simplify('/.'))
  315. call assert_equal('/', simplify('/..'))
  316. call assert_equal('/...', simplify('/...'))
  317. call assert_equal('//path', simplify('//path'))
  318. if has('unix')
  319. call assert_equal('/path', simplify('///path'))
  320. call assert_equal('/path', simplify('////path'))
  321. endif
  322. call assert_equal('./dir/file', './dir/file'->simplify())
  323. call assert_equal('./dir/file', simplify('.///dir//file'))
  324. call assert_equal('./dir/file', simplify('./dir/./file'))
  325. call assert_equal('./file', simplify('./dir/../file'))
  326. call assert_equal('../dir/file', simplify('dir/../../dir/file'))
  327. call assert_equal('./file', simplify('dir/.././file'))
  328. call assert_equal('../dir', simplify('./../dir'))
  329. call assert_equal('..', simplify('../testdir/..'))
  330. call mkdir('Xdir')
  331. call assert_equal('.', simplify('Xdir/../.'))
  332. call delete('Xdir', 'd')
  333. call assert_fails('call simplify({->0})', 'E729:')
  334. call assert_fails('call simplify([])', 'E730:')
  335. call assert_fails('call simplify({})', 'E731:')
  336. if has('float')
  337. call assert_equal('1.2', simplify(1.2))
  338. call CheckDefExecAndScriptFailure(['echo simplify(1.2)'], 'E806:')
  339. endif
  340. endfunc
  341. func Test_pathshorten()
  342. call assert_equal('', pathshorten(''))
  343. call assert_equal('foo', pathshorten('foo'))
  344. call assert_equal('/foo', '/foo'->pathshorten())
  345. call assert_equal('f/', pathshorten('foo/'))
  346. call assert_equal('f/bar', pathshorten('foo/bar'))
  347. call assert_equal('f/b/foobar', 'foo/bar/foobar'->pathshorten())
  348. call assert_equal('/f/b/foobar', pathshorten('/foo/bar/foobar'))
  349. call assert_equal('.f/bar', pathshorten('.foo/bar'))
  350. call assert_equal('~f/bar', pathshorten('~foo/bar'))
  351. call assert_equal('~.f/bar', pathshorten('~.foo/bar'))
  352. call assert_equal('.~f/bar', pathshorten('.~foo/bar'))
  353. call assert_equal('~/f/bar', pathshorten('~/foo/bar'))
  354. call assert_fails('call pathshorten([])', 'E730:')
  355. " test pathshorten with optional variable to set preferred size of shortening
  356. call assert_equal('', pathshorten('', 2))
  357. call assert_equal('foo', pathshorten('foo', 2))
  358. call assert_equal('/foo', pathshorten('/foo', 2))
  359. call assert_equal('fo/', pathshorten('foo/', 2))
  360. call assert_equal('fo/bar', pathshorten('foo/bar', 2))
  361. call assert_equal('fo/ba/foobar', pathshorten('foo/bar/foobar', 2))
  362. call assert_equal('/fo/ba/foobar', pathshorten('/foo/bar/foobar', 2))
  363. call assert_equal('.fo/bar', pathshorten('.foo/bar', 2))
  364. call assert_equal('~fo/bar', pathshorten('~foo/bar', 2))
  365. call assert_equal('~.fo/bar', pathshorten('~.foo/bar', 2))
  366. call assert_equal('.~fo/bar', pathshorten('.~foo/bar', 2))
  367. call assert_equal('~/fo/bar', pathshorten('~/foo/bar', 2))
  368. call assert_fails('call pathshorten([],2)', 'E730:')
  369. call assert_notequal('~/fo/bar', pathshorten('~/foo/bar', 3))
  370. call assert_equal('~/foo/bar', pathshorten('~/foo/bar', 3))
  371. call assert_equal('~/f/bar', pathshorten('~/foo/bar', 0))
  372. endfunc
  373. func Test_strpart()
  374. call assert_equal('de', strpart('abcdefg', 3, 2))
  375. call assert_equal('ab', strpart('abcdefg', -2, 4))
  376. call assert_equal('abcdefg', 'abcdefg'->strpart(-2))
  377. call assert_equal('fg', strpart('abcdefg', 5, 4))
  378. call assert_equal('defg', strpart('abcdefg', 3))
  379. call assert_equal('', strpart('abcdefg', 10))
  380. call assert_fails("let s=strpart('abcdef', [])", 'E745:')
  381. call assert_equal('lép', strpart('éléphant', 2, 4))
  382. call assert_equal('léphant', strpart('éléphant', 2))
  383. call assert_equal('é', strpart('éléphant', 0, 1, 1))
  384. call assert_equal('ép', strpart('éléphant', 3, 2, v:true))
  385. call assert_equal('ó', strpart('cómposed', 1, 1, 1))
  386. endfunc
  387. func Test_tolower()
  388. call assert_equal("", tolower(""))
  389. " Test with all printable ASCII characters.
  390. call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
  391. \ tolower(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
  392. " Test with a few uppercase diacritics.
  393. call assert_equal("aàáâãäåāăąǎǟǡả", tolower("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
  394. call assert_equal("bḃḇ", tolower("BḂḆ"))
  395. call assert_equal("cçćĉċč", tolower("CÇĆĈĊČ"))
  396. call assert_equal("dďđḋḏḑ", tolower("DĎĐḊḎḐ"))
  397. call assert_equal("eèéêëēĕėęěẻẽ", tolower("EÈÉÊËĒĔĖĘĚẺẼ"))
  398. call assert_equal("fḟ ", tolower("FḞ "))
  399. call assert_equal("gĝğġģǥǧǵḡ", tolower("GĜĞĠĢǤǦǴḠ"))
  400. call assert_equal("hĥħḣḧḩ", tolower("HĤĦḢḦḨ"))
  401. call assert_equal("iìíîïĩīĭįiǐỉ", tolower("IÌÍÎÏĨĪĬĮİǏỈ"))
  402. call assert_equal("jĵ", tolower("JĴ"))
  403. call assert_equal("kķǩḱḵ", tolower("KĶǨḰḴ"))
  404. call assert_equal("lĺļľŀłḻ", tolower("LĹĻĽĿŁḺ"))
  405. call assert_equal("mḿṁ", tolower("MḾṀ"))
  406. call assert_equal("nñńņňṅṉ", tolower("NÑŃŅŇṄṈ"))
  407. call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
  408. call assert_equal("pṕṗ", tolower("PṔṖ"))
  409. call assert_equal("q", tolower("Q"))
  410. call assert_equal("rŕŗřṙṟ", tolower("RŔŖŘṘṞ"))
  411. call assert_equal("sśŝşšṡ", tolower("SŚŜŞŠṠ"))
  412. call assert_equal("tţťŧṫṯ", tolower("TŢŤŦṪṮ"))
  413. call assert_equal("uùúûüũūŭůűųưǔủ", tolower("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
  414. call assert_equal("vṽ", tolower("VṼ"))
  415. call assert_equal("wŵẁẃẅẇ", tolower("WŴẀẂẄẆ"))
  416. call assert_equal("xẋẍ", tolower("XẊẌ"))
  417. call assert_equal("yýŷÿẏỳỷỹ", tolower("YÝŶŸẎỲỶỸ"))
  418. call assert_equal("zźżžƶẑẕ", tolower("ZŹŻŽƵẐẔ"))
  419. " Test with a few lowercase diacritics, which should remain unchanged.
  420. call assert_equal("aàáâãäåāăąǎǟǡả", tolower("aàáâãäåāăąǎǟǡả"))
  421. call assert_equal("bḃḇ", tolower("bḃḇ"))
  422. call assert_equal("cçćĉċč", tolower("cçćĉċč"))
  423. call assert_equal("dďđḋḏḑ", tolower("dďđḋḏḑ"))
  424. call assert_equal("eèéêëēĕėęěẻẽ", tolower("eèéêëēĕėęěẻẽ"))
  425. call assert_equal("fḟ", tolower("fḟ"))
  426. call assert_equal("gĝğġģǥǧǵḡ", tolower("gĝğġģǥǧǵḡ"))
  427. call assert_equal("hĥħḣḧḩẖ", tolower("hĥħḣḧḩẖ"))
  428. call assert_equal("iìíîïĩīĭįǐỉ", tolower("iìíîïĩīĭįǐỉ"))
  429. call assert_equal("jĵǰ", tolower("jĵǰ"))
  430. call assert_equal("kķǩḱḵ", tolower("kķǩḱḵ"))
  431. call assert_equal("lĺļľŀłḻ", tolower("lĺļľŀłḻ"))
  432. call assert_equal("mḿṁ ", tolower("mḿṁ "))
  433. call assert_equal("nñńņňʼnṅṉ", tolower("nñńņňʼnṅṉ"))
  434. call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("oòóôõöøōŏőơǒǫǭỏ"))
  435. call assert_equal("pṕṗ", tolower("pṕṗ"))
  436. call assert_equal("q", tolower("q"))
  437. call assert_equal("rŕŗřṙṟ", tolower("rŕŗřṙṟ"))
  438. call assert_equal("sśŝşšṡ", tolower("sśŝşšṡ"))
  439. call assert_equal("tţťŧṫṯẗ", tolower("tţťŧṫṯẗ"))
  440. call assert_equal("uùúûüũūŭůűųưǔủ", tolower("uùúûüũūŭůűųưǔủ"))
  441. call assert_equal("vṽ", tolower("vṽ"))
  442. call assert_equal("wŵẁẃẅẇẘ", tolower("wŵẁẃẅẇẘ"))
  443. call assert_equal("ẋẍ", tolower("ẋẍ"))
  444. call assert_equal("yýÿŷẏẙỳỷỹ", tolower("yýÿŷẏẙỳỷỹ"))
  445. call assert_equal("zźżžƶẑẕ", tolower("zźżžƶẑẕ"))
  446. " According to https://twitter.com/jifa/status/625776454479970304
  447. " Ⱥ (U+023A) and Ⱦ (U+023E) are the *only* code points to increase
  448. " in length (2 to 3 bytes) when lowercased. So let's test them.
  449. call assert_equal("ⱥ ⱦ", tolower("Ⱥ Ⱦ"))
  450. " This call to tolower with invalid utf8 sequence used to cause access to
  451. " invalid memory.
  452. call tolower("\xC0\x80\xC0")
  453. call tolower("123\xC0\x80\xC0")
  454. " Test in latin1 encoding
  455. let save_enc = &encoding
  456. " set encoding=latin1
  457. call assert_equal("abc", tolower("ABC"))
  458. let &encoding = save_enc
  459. endfunc
  460. func Test_toupper()
  461. call assert_equal("", toupper(""))
  462. " Test with all printable ASCII characters.
  463. call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~',
  464. \ toupper(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'))
  465. " Test with a few lowercase diacritics.
  466. call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", "aàáâãäåāăąǎǟǡả"->toupper())
  467. call assert_equal("BḂḆ", toupper("bḃḇ"))
  468. call assert_equal("CÇĆĈĊČ", toupper("cçćĉċč"))
  469. call assert_equal("DĎĐḊḎḐ", toupper("dďđḋḏḑ"))
  470. call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("eèéêëēĕėęěẻẽ"))
  471. call assert_equal("FḞ", toupper("fḟ"))
  472. call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("gĝğġģǥǧǵḡ"))
  473. call assert_equal("HĤĦḢḦḨẖ", toupper("hĥħḣḧḩẖ"))
  474. call assert_equal("IÌÍÎÏĨĪĬĮǏỈ", toupper("iìíîïĩīĭįǐỉ"))
  475. call assert_equal("JĴǰ", toupper("jĵǰ"))
  476. call assert_equal("KĶǨḰḴ", toupper("kķǩḱḵ"))
  477. call assert_equal("LĹĻĽĿŁḺ", toupper("lĺļľŀłḻ"))
  478. call assert_equal("MḾṀ ", toupper("mḿṁ "))
  479. call assert_equal("NÑŃŅŇʼnṄṈ", toupper("nñńņňʼnṅṉ"))
  480. call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("oòóôõöøōŏőơǒǫǭỏ"))
  481. call assert_equal("PṔṖ", toupper("pṕṗ"))
  482. call assert_equal("Q", toupper("q"))
  483. call assert_equal("RŔŖŘṘṞ", toupper("rŕŗřṙṟ"))
  484. call assert_equal("SŚŜŞŠṠ", toupper("sśŝşšṡ"))
  485. call assert_equal("TŢŤŦṪṮẗ", toupper("tţťŧṫṯẗ"))
  486. call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("uùúûüũūŭůűųưǔủ"))
  487. call assert_equal("VṼ", toupper("vṽ"))
  488. call assert_equal("WŴẀẂẄẆẘ", toupper("wŵẁẃẅẇẘ"))
  489. call assert_equal("ẊẌ", toupper("ẋẍ"))
  490. call assert_equal("YÝŸŶẎẙỲỶỸ", toupper("yýÿŷẏẙỳỷỹ"))
  491. call assert_equal("ZŹŻŽƵẐẔ", toupper("zźżžƶẑẕ"))
  492. " Test that uppercase diacritics, which should remain unchanged.
  493. call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", toupper("AÀÁÂÃÄÅĀĂĄǍǞǠẢ"))
  494. call assert_equal("BḂḆ", toupper("BḂḆ"))
  495. call assert_equal("CÇĆĈĊČ", toupper("CÇĆĈĊČ"))
  496. call assert_equal("DĎĐḊḎḐ", toupper("DĎĐḊḎḐ"))
  497. call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("EÈÉÊËĒĔĖĘĚẺẼ"))
  498. call assert_equal("FḞ ", toupper("FḞ "))
  499. call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("GĜĞĠĢǤǦǴḠ"))
  500. call assert_equal("HĤĦḢḦḨ", toupper("HĤĦḢḦḨ"))
  501. call assert_equal("IÌÍÎÏĨĪĬĮİǏỈ", toupper("IÌÍÎÏĨĪĬĮİǏỈ"))
  502. call assert_equal("JĴ", toupper("JĴ"))
  503. call assert_equal("KĶǨḰḴ", toupper("KĶǨḰḴ"))
  504. call assert_equal("LĹĻĽĿŁḺ", toupper("LĹĻĽĿŁḺ"))
  505. call assert_equal("MḾṀ", toupper("MḾṀ"))
  506. call assert_equal("NÑŃŅŇṄṈ", toupper("NÑŃŅŇṄṈ"))
  507. call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ"))
  508. call assert_equal("PṔṖ", toupper("PṔṖ"))
  509. call assert_equal("Q", toupper("Q"))
  510. call assert_equal("RŔŖŘṘṞ", toupper("RŔŖŘṘṞ"))
  511. call assert_equal("SŚŜŞŠṠ", toupper("SŚŜŞŠṠ"))
  512. call assert_equal("TŢŤŦṪṮ", toupper("TŢŤŦṪṮ"))
  513. call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("UÙÚÛÜŨŪŬŮŰŲƯǓỦ"))
  514. call assert_equal("VṼ", toupper("VṼ"))
  515. call assert_equal("WŴẀẂẄẆ", toupper("WŴẀẂẄẆ"))
  516. call assert_equal("XẊẌ", toupper("XẊẌ"))
  517. call assert_equal("YÝŶŸẎỲỶỸ", toupper("YÝŶŸẎỲỶỸ"))
  518. call assert_equal("ZŹŻŽƵẐẔ", toupper("ZŹŻŽƵẐẔ"))
  519. call assert_equal("Ⱥ Ⱦ", toupper("ⱥ ⱦ"))
  520. " This call to toupper with invalid utf8 sequence used to cause access to
  521. " invalid memory.
  522. call toupper("\xC0\x80\xC0")
  523. call toupper("123\xC0\x80\xC0")
  524. " Test in latin1 encoding
  525. let save_enc = &encoding
  526. " set encoding=latin1
  527. call assert_equal("ABC", toupper("abc"))
  528. let &encoding = save_enc
  529. endfunc
  530. func Test_tr()
  531. call assert_equal('foo', tr('bar', 'bar', 'foo'))
  532. call assert_equal('zxy', 'cab'->tr('abc', 'xyz'))
  533. call assert_fails("let s=tr([], 'abc', 'def')", 'E730:')
  534. call assert_fails("let s=tr('abc', [], 'def')", 'E730:')
  535. call assert_fails("let s=tr('abc', 'abc', [])", 'E730:')
  536. call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
  537. " set encoding=latin1
  538. call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:')
  539. call assert_equal('hEllO', tr('hello', 'eo', 'EO'))
  540. call assert_equal('hello', tr('hello', 'xy', 'ab'))
  541. call assert_fails('call tr("abc", "123", "₁₂")', 'E475:')
  542. set encoding=utf8
  543. endfunc
  544. " Tests for the mode() function
  545. let current_modes = ''
  546. func Save_mode()
  547. let g:current_modes = mode(0) . '-' . mode(1)
  548. return ''
  549. endfunc
  550. " Test for the mode() function
  551. func Test_mode()
  552. new
  553. call append(0, ["Blue Ball Black", "Brown Band Bowl", ""])
  554. " Only complete from the current buffer.
  555. set complete=.
  556. noremap! <F2> <C-R>=Save_mode()<CR>
  557. xnoremap <F2> <Cmd>call Save_mode()<CR>
  558. normal! 3G
  559. exe "normal i\<F2>\<Esc>"
  560. call assert_equal('i-i', g:current_modes)
  561. " i_CTRL-P: Multiple matches
  562. exe "normal i\<C-G>uBa\<C-P>\<F2>\<Esc>u"
  563. call assert_equal('i-ic', g:current_modes)
  564. " i_CTRL-P: Single match
  565. exe "normal iBro\<C-P>\<F2>\<Esc>u"
  566. call assert_equal('i-ic', g:current_modes)
  567. " i_CTRL-X
  568. exe "normal iBa\<C-X>\<F2>\<Esc>u"
  569. call assert_equal('i-ix', g:current_modes)
  570. " i_CTRL-X CTRL-P: Multiple matches
  571. exe "normal iBa\<C-X>\<C-P>\<F2>\<Esc>u"
  572. call assert_equal('i-ic', g:current_modes)
  573. " i_CTRL-X CTRL-P: Single match
  574. exe "normal iBro\<C-X>\<C-P>\<F2>\<Esc>u"
  575. call assert_equal('i-ic', g:current_modes)
  576. " i_CTRL-X CTRL-P + CTRL-P: Single match
  577. exe "normal iBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
  578. call assert_equal('i-ic', g:current_modes)
  579. " i_CTRL-X CTRL-L: Multiple matches
  580. exe "normal i\<C-X>\<C-L>\<F2>\<Esc>u"
  581. call assert_equal('i-ic', g:current_modes)
  582. " i_CTRL-X CTRL-L: Single match
  583. exe "normal iBlu\<C-X>\<C-L>\<F2>\<Esc>u"
  584. call assert_equal('i-ic', g:current_modes)
  585. " i_CTRL-P: No match
  586. exe "normal iCom\<C-P>\<F2>\<Esc>u"
  587. call assert_equal('i-ic', g:current_modes)
  588. " i_CTRL-X CTRL-P: No match
  589. exe "normal iCom\<C-X>\<C-P>\<F2>\<Esc>u"
  590. call assert_equal('i-ic', g:current_modes)
  591. " i_CTRL-X CTRL-L: No match
  592. exe "normal iabc\<C-X>\<C-L>\<F2>\<Esc>u"
  593. call assert_equal('i-ic', g:current_modes)
  594. exe "normal R\<F2>\<Esc>"
  595. call assert_equal('R-R', g:current_modes)
  596. " R_CTRL-P: Multiple matches
  597. exe "normal RBa\<C-P>\<F2>\<Esc>u"
  598. call assert_equal('R-Rc', g:current_modes)
  599. " R_CTRL-P: Single match
  600. exe "normal RBro\<C-P>\<F2>\<Esc>u"
  601. call assert_equal('R-Rc', g:current_modes)
  602. " R_CTRL-X
  603. exe "normal RBa\<C-X>\<F2>\<Esc>u"
  604. call assert_equal('R-Rx', g:current_modes)
  605. " R_CTRL-X CTRL-P: Multiple matches
  606. exe "normal RBa\<C-X>\<C-P>\<F2>\<Esc>u"
  607. call assert_equal('R-Rc', g:current_modes)
  608. " R_CTRL-X CTRL-P: Single match
  609. exe "normal RBro\<C-X>\<C-P>\<F2>\<Esc>u"
  610. call assert_equal('R-Rc', g:current_modes)
  611. " R_CTRL-X CTRL-P + CTRL-P: Single match
  612. exe "normal RBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
  613. call assert_equal('R-Rc', g:current_modes)
  614. " R_CTRL-X CTRL-L: Multiple matches
  615. exe "normal R\<C-X>\<C-L>\<F2>\<Esc>u"
  616. call assert_equal('R-Rc', g:current_modes)
  617. " R_CTRL-X CTRL-L: Single match
  618. exe "normal RBlu\<C-X>\<C-L>\<F2>\<Esc>u"
  619. call assert_equal('R-Rc', g:current_modes)
  620. " R_CTRL-P: No match
  621. exe "normal RCom\<C-P>\<F2>\<Esc>u"
  622. call assert_equal('R-Rc', g:current_modes)
  623. " R_CTRL-X CTRL-P: No match
  624. exe "normal RCom\<C-X>\<C-P>\<F2>\<Esc>u"
  625. call assert_equal('R-Rc', g:current_modes)
  626. " R_CTRL-X CTRL-L: No match
  627. exe "normal Rabc\<C-X>\<C-L>\<F2>\<Esc>u"
  628. call assert_equal('R-Rc', g:current_modes)
  629. exe "normal gR\<F2>\<Esc>"
  630. call assert_equal('R-Rv', g:current_modes)
  631. " gR_CTRL-P: Multiple matches
  632. exe "normal gRBa\<C-P>\<F2>\<Esc>u"
  633. call assert_equal('R-Rvc', g:current_modes)
  634. " gR_CTRL-P: Single match
  635. exe "normal gRBro\<C-P>\<F2>\<Esc>u"
  636. call assert_equal('R-Rvc', g:current_modes)
  637. " gR_CTRL-X
  638. exe "normal gRBa\<C-X>\<F2>\<Esc>u"
  639. call assert_equal('R-Rvx', g:current_modes)
  640. " gR_CTRL-X CTRL-P: Multiple matches
  641. exe "normal gRBa\<C-X>\<C-P>\<F2>\<Esc>u"
  642. call assert_equal('R-Rvc', g:current_modes)
  643. " gR_CTRL-X CTRL-P: Single match
  644. exe "normal gRBro\<C-X>\<C-P>\<F2>\<Esc>u"
  645. call assert_equal('R-Rvc', g:current_modes)
  646. " gR_CTRL-X CTRL-P + CTRL-P: Single match
  647. exe "normal gRBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u"
  648. call assert_equal('R-Rvc', g:current_modes)
  649. " gR_CTRL-X CTRL-L: Multiple matches
  650. exe "normal gR\<C-X>\<C-L>\<F2>\<Esc>u"
  651. call assert_equal('R-Rvc', g:current_modes)
  652. " gR_CTRL-X CTRL-L: Single match
  653. exe "normal gRBlu\<C-X>\<C-L>\<F2>\<Esc>u"
  654. call assert_equal('R-Rvc', g:current_modes)
  655. " gR_CTRL-P: No match
  656. exe "normal gRCom\<C-P>\<F2>\<Esc>u"
  657. call assert_equal('R-Rvc', g:current_modes)
  658. " gR_CTRL-X CTRL-P: No match
  659. exe "normal gRCom\<C-X>\<C-P>\<F2>\<Esc>u"
  660. call assert_equal('R-Rvc', g:current_modes)
  661. " gR_CTRL-X CTRL-L: No match
  662. exe "normal gRabc\<C-X>\<C-L>\<F2>\<Esc>u"
  663. call assert_equal('R-Rvc', g:current_modes)
  664. call assert_equal('n', 0->mode())
  665. call assert_equal('n', 1->mode())
  666. " i_CTRL-O
  667. exe "normal i\<C-O>:call Save_mode()\<Cr>\<Esc>"
  668. call assert_equal("n-niI", g:current_modes)
  669. " R_CTRL-O
  670. exe "normal R\<C-O>:call Save_mode()\<Cr>\<Esc>"
  671. call assert_equal("n-niR", g:current_modes)
  672. " gR_CTRL-O
  673. exe "normal gR\<C-O>:call Save_mode()\<Cr>\<Esc>"
  674. call assert_equal("n-niV", g:current_modes)
  675. " How to test operator-pending mode?
  676. call feedkeys("v", 'xt')
  677. call assert_equal('v', mode())
  678. call assert_equal('v', mode(1))
  679. call feedkeys("\<Esc>V", 'xt')
  680. call assert_equal('V', mode())
  681. call assert_equal('V', mode(1))
  682. call feedkeys("\<Esc>\<C-V>", 'xt')
  683. call assert_equal("\<C-V>", mode())
  684. call assert_equal("\<C-V>", mode(1))
  685. call feedkeys("\<Esc>", 'xt')
  686. call feedkeys("gh", 'xt')
  687. call assert_equal('s', mode())
  688. call assert_equal('s', mode(1))
  689. call feedkeys("\<Esc>gH", 'xt')
  690. call assert_equal('S', mode())
  691. call assert_equal('S', mode(1))
  692. call feedkeys("\<Esc>g\<C-H>", 'xt')
  693. call assert_equal("\<C-S>", mode())
  694. call assert_equal("\<C-S>", mode(1))
  695. call feedkeys("\<Esc>", 'xt')
  696. " v_CTRL-O
  697. exe "normal gh\<C-O>\<F2>\<Esc>"
  698. call assert_equal("v-vs", g:current_modes)
  699. exe "normal gH\<C-O>\<F2>\<Esc>"
  700. call assert_equal("V-Vs", g:current_modes)
  701. exe "normal g\<C-H>\<C-O>\<F2>\<Esc>"
  702. call assert_equal("\<C-V>-\<C-V>s", g:current_modes)
  703. call feedkeys(":\<F2>\<CR>", 'xt')
  704. call assert_equal('c-c', g:current_modes)
  705. call feedkeys(":\<Insert>\<F2>\<CR>", 'xt')
  706. call assert_equal("c-cr", g:current_modes)
  707. call feedkeys("gQ\<F2>vi\<CR>", 'xt')
  708. call assert_equal('c-cv', g:current_modes)
  709. call feedkeys("gQ\<Insert>\<F2>vi\<CR>", 'xt')
  710. call assert_equal("c-cvr", g:current_modes)
  711. " Commandline mode in Visual mode should return "c-c", never "v-v".
  712. call feedkeys("v\<Cmd>call input('')\<CR>\<F2>\<CR>\<Esc>", 'xt')
  713. call assert_equal("c-c", g:current_modes)
  714. " Executing commands in Vim Ex mode should return "cv", never "cvr",
  715. " as Cmdline editing has already ended.
  716. call feedkeys("gQcall Save_mode()\<CR>vi\<CR>", 'xt')
  717. call assert_equal('c-cv', g:current_modes)
  718. call feedkeys("gQ\<Insert>call Save_mode()\<CR>vi\<CR>", 'xt')
  719. call assert_equal('c-cv', g:current_modes)
  720. " call feedkeys("Qcall Save_mode()\<CR>vi\<CR>", 'xt')
  721. " call assert_equal('c-ce', g:current_modes)
  722. " Test mode in operatorfunc (it used to be Operator-pending).
  723. set operatorfunc=OperatorFunc
  724. function OperatorFunc(_)
  725. call Save_mode()
  726. endfunction
  727. execute "normal! g@l\<Esc>"
  728. call assert_equal('n-n', g:current_modes)
  729. execute "normal! i\<C-o>g@l\<Esc>"
  730. call assert_equal('n-niI', g:current_modes)
  731. execute "normal! R\<C-o>g@l\<Esc>"
  732. call assert_equal('n-niR', g:current_modes)
  733. execute "normal! gR\<C-o>g@l\<Esc>"
  734. call assert_equal('n-niV', g:current_modes)
  735. " Test statusline updates for overstrike mode
  736. if CanRunVimInTerminal()
  737. let buf = RunVimInTerminal('', {'rows': 12})
  738. call term_sendkeys(buf, ":set laststatus=2 statusline=%!mode(1)\<CR>")
  739. call term_sendkeys(buf, ":")
  740. call TermWait(buf)
  741. call VerifyScreenDump(buf, 'Test_mode_1', {})
  742. call term_sendkeys(buf, "\<Insert>")
  743. call TermWait(buf)
  744. call VerifyScreenDump(buf, 'Test_mode_2', {})
  745. call StopVimInTerminal(buf)
  746. endif
  747. if has('terminal')
  748. term
  749. call feedkeys("\<C-W>N", 'xt')
  750. call assert_equal('n', mode())
  751. call assert_equal('nt', mode(1))
  752. call feedkeys("aexit\<CR>", 'xt')
  753. endif
  754. bwipe!
  755. unmap! <F2>
  756. xunmap <F2>
  757. set complete&
  758. set operatorfunc&
  759. delfunction OperatorFunc
  760. endfunc
  761. " Test for append()
  762. func Test_append()
  763. enew!
  764. split
  765. call assert_equal(0, append(1, []))
  766. call assert_equal(0, append(1, v:_null_list))
  767. call assert_equal(0, append(0, ["foo"]))
  768. call assert_equal(0, append(1, []))
  769. call assert_equal(0, append(1, v:_null_list))
  770. call assert_equal(0, append(8, []))
  771. call assert_equal(0, append(9, v:_null_list))
  772. call assert_equal(['foo', ''], getline(1, '$'))
  773. split
  774. only
  775. undo
  776. undo
  777. " Using $ instead of '$' must give an error
  778. call assert_fails("call append($, 'foobar')", 'E116:')
  779. call assert_fails("call append({}, '')", ['E728:', 'E728:'])
  780. endfunc
  781. " Test for setline()
  782. func Test_setline()
  783. new
  784. call setline(0, ["foo"])
  785. call setline(0, [])
  786. call setline(0, v:_null_list)
  787. call setline(1, ["bar"])
  788. call setline(1, [])
  789. call setline(1, v:_null_list)
  790. call setline(2, [])
  791. call setline(2, v:_null_list)
  792. call setline(3, [])
  793. call setline(3, v:_null_list)
  794. call setline(2, ["baz"])
  795. call assert_equal(['bar', 'baz'], getline(1, '$'))
  796. close!
  797. endfunc
  798. func Test_getbufvar()
  799. let bnr = bufnr('%')
  800. let b:var_num = '1234'
  801. let def_num = '5678'
  802. call assert_equal('1234', getbufvar(bnr, 'var_num'))
  803. call assert_equal('1234', getbufvar(bnr, 'var_num', def_num))
  804. let bd = getbufvar(bnr, '')
  805. call assert_equal('1234', bd['var_num'])
  806. call assert_true(exists("bd['changedtick']"))
  807. call assert_equal(2, len(bd))
  808. let bd2 = getbufvar(bnr, '', def_num)
  809. call assert_equal(bd, bd2)
  810. unlet b:var_num
  811. call assert_equal(def_num, getbufvar(bnr, 'var_num', def_num))
  812. call assert_equal('', getbufvar(bnr, 'var_num'))
  813. let bd = getbufvar(bnr, '')
  814. call assert_equal(1, len(bd))
  815. let bd = getbufvar(bnr, '',def_num)
  816. call assert_equal(1, len(bd))
  817. call assert_equal('', getbufvar(9999, ''))
  818. call assert_equal(def_num, getbufvar(9999, '', def_num))
  819. unlet def_num
  820. call assert_equal(0, getbufvar(bnr, '&autoindent'))
  821. call assert_equal(0, getbufvar(bnr, '&autoindent', 1))
  822. " Set and get a buffer-local variable
  823. call setbufvar(bnr, 'bufvar_test', ['one', 'two'])
  824. call assert_equal(['one', 'two'], getbufvar(bnr, 'bufvar_test'))
  825. " Open new window with forced option values
  826. set fileformats=unix,dos
  827. new ++ff=dos ++bin ++enc=iso-8859-2
  828. call assert_equal('dos', getbufvar(bufnr('%'), '&fileformat'))
  829. call assert_equal(1, getbufvar(bufnr('%'), '&bin'))
  830. call assert_equal('iso-8859-2', getbufvar(bufnr('%'), '&fenc'))
  831. close
  832. " Get the b: dict.
  833. let b:testvar = 'one'
  834. new
  835. let b:testvar = 'two'
  836. let thebuf = bufnr()
  837. wincmd w
  838. call assert_equal('two', getbufvar(thebuf, 'testvar'))
  839. call assert_equal('two', getbufvar(thebuf, '').testvar)
  840. bwipe!
  841. set fileformats&
  842. endfunc
  843. func Test_last_buffer_nr()
  844. call assert_equal(bufnr('$'), last_buffer_nr())
  845. endfunc
  846. func Test_stridx()
  847. call assert_equal(-1, stridx('', 'l'))
  848. call assert_equal(0, stridx('', ''))
  849. call assert_equal(0, 'hello'->stridx(''))
  850. call assert_equal(-1, stridx('hello', 'L'))
  851. call assert_equal(2, stridx('hello', 'l', -1))
  852. call assert_equal(2, stridx('hello', 'l', 0))
  853. call assert_equal(2, 'hello'->stridx('l', 1))
  854. call assert_equal(3, stridx('hello', 'l', 3))
  855. call assert_equal(-1, stridx('hello', 'l', 4))
  856. call assert_equal(-1, stridx('hello', 'l', 10))
  857. call assert_equal(2, stridx('hello', 'll'))
  858. call assert_equal(-1, stridx('hello', 'hello world'))
  859. call assert_fails("let n=stridx('hello', [])", 'E730:')
  860. call assert_fails("let n=stridx([], 'l')", 'E730:')
  861. endfunc
  862. func Test_strridx()
  863. call assert_equal(-1, strridx('', 'l'))
  864. call assert_equal(0, strridx('', ''))
  865. call assert_equal(5, strridx('hello', ''))
  866. call assert_equal(-1, strridx('hello', 'L'))
  867. call assert_equal(3, 'hello'->strridx('l'))
  868. call assert_equal(3, strridx('hello', 'l', 10))
  869. call assert_equal(3, strridx('hello', 'l', 3))
  870. call assert_equal(2, strridx('hello', 'l', 2))
  871. call assert_equal(-1, strridx('hello', 'l', 1))
  872. call assert_equal(-1, strridx('hello', 'l', 0))
  873. call assert_equal(-1, strridx('hello', 'l', -1))
  874. call assert_equal(2, strridx('hello', 'll'))
  875. call assert_equal(-1, strridx('hello', 'hello world'))
  876. call assert_fails("let n=strridx('hello', [])", 'E730:')
  877. call assert_fails("let n=strridx([], 'l')", 'E730:')
  878. endfunc
  879. func Test_match_func()
  880. call assert_equal(4, match('testing', 'ing'))
  881. call assert_equal(4, 'testing'->match('ing', 2))
  882. call assert_equal(-1, match('testing', 'ing', 5))
  883. call assert_equal(-1, match('testing', 'ing', 8))
  884. call assert_equal(1, match(['vim', 'testing', 'execute'], 'ing'))
  885. call assert_equal(-1, match(['vim', 'testing', 'execute'], 'img'))
  886. call assert_fails("let x=match('vim', [])", 'E730:')
  887. call assert_equal(3, match(['a', 'b', 'c', 'a'], 'a', 1))
  888. call assert_equal(-1, match(['a', 'b', 'c', 'a'], 'a', 5))
  889. call assert_equal(4, match('testing', 'ing', -1))
  890. call assert_fails("let x=match('testing', 'ing', 0, [])", 'E745:')
  891. call assert_equal(-1, match(v:_null_list, 2))
  892. call assert_equal(-1, match('abc', '\\%('))
  893. endfunc
  894. func Test_matchend()
  895. call assert_equal(7, matchend('testing', 'ing'))
  896. call assert_equal(7, 'testing'->matchend('ing', 2))
  897. call assert_equal(-1, matchend('testing', 'ing', 5))
  898. call assert_equal(-1, matchend('testing', 'ing', 8))
  899. call assert_equal(match(['vim', 'testing', 'execute'], 'ing'), matchend(['vim', 'testing', 'execute'], 'ing'))
  900. call assert_equal(match(['vim', 'testing', 'execute'], 'img'), matchend(['vim', 'testing', 'execute'], 'img'))
  901. endfunc
  902. func Test_matchlist()
  903. call assert_equal(['acd', 'a', '', 'c', 'd', '', '', '', '', ''], matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)'))
  904. call assert_equal(['d', '', '', '', 'd', '', '', '', '', ''], 'acd'->matchlist('\(a\)\?\(b\)\?\(c\)\?\(.*\)', 2))
  905. call assert_equal([], matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 4))
  906. endfunc
  907. func Test_matchstr()
  908. call assert_equal('ing', matchstr('testing', 'ing'))
  909. call assert_equal('ing', 'testing'->matchstr('ing', 2))
  910. call assert_equal('', matchstr('testing', 'ing', 5))
  911. call assert_equal('', matchstr('testing', 'ing', 8))
  912. call assert_equal('testing', matchstr(['vim', 'testing', 'execute'], 'ing'))
  913. call assert_equal('', matchstr(['vim', 'testing', 'execute'], 'img'))
  914. endfunc
  915. func Test_matchstrpos()
  916. call assert_equal(['ing', 4, 7], matchstrpos('testing', 'ing'))
  917. call assert_equal(['ing', 4, 7], 'testing'->matchstrpos('ing', 2))
  918. call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 5))
  919. call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 8))
  920. call assert_equal(['ing', 1, 4, 7], matchstrpos(['vim', 'testing', 'execute'], 'ing'))
  921. call assert_equal(['', -1, -1, -1], matchstrpos(['vim', 'testing', 'execute'], 'img'))
  922. call assert_equal(['', -1, -1], matchstrpos(v:_null_list, '\a'))
  923. endfunc
  924. " Test for matchstrlist()
  925. func Test_matchstrlist()
  926. let lines =<< trim END
  927. #" Basic match
  928. call assert_equal([{'idx': 0, 'byteidx': 1, 'text': 'bout'},
  929. \ {'idx': 1, 'byteidx': 1, 'text': 'bove'}],
  930. \ matchstrlist(['about', 'above'], 'bo.*'))
  931. #" no match
  932. call assert_equal([], matchstrlist(['about', 'above'], 'xy.*'))
  933. #" empty string
  934. call assert_equal([], matchstrlist([''], '.'))
  935. #" empty pattern
  936. call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}], matchstrlist(['abc'], ''))
  937. #" method call
  938. call assert_equal([{'idx': 0, 'byteidx': 2, 'text': 'it'}], ['editor']->matchstrlist('ed\zsit\zeor'))
  939. #" single character matches
  940. call assert_equal([{'idx': 0, 'byteidx': 5, 'text': 'r'}],
  941. \ ['editor']->matchstrlist('r'))
  942. call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'a'}], ['a']->matchstrlist('a'))
  943. call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}],
  944. \ matchstrlist(['foobar'], '\zs'))
  945. #" string with tabs
  946. call assert_equal([{'idx': 0, 'byteidx': 1, 'text': 'foo'}],
  947. \ matchstrlist(["\tfoobar"], 'foo'))
  948. #" string with multibyte characters
  949. call assert_equal([{'idx': 0, 'byteidx': 2, 'text': '😊😊'}],
  950. \ matchstrlist(["\t\t😊😊"], '\k\+'))
  951. #" null string
  952. call assert_equal([], matchstrlist(v:_null_list, 'abc'))
  953. call assert_equal([], matchstrlist([v:_null_string], 'abc'))
  954. call assert_equal([{'idx': 0, 'byteidx': 0, 'text': ''}],
  955. \ matchstrlist(['abc'], v:_null_string))
  956. #" sub matches
  957. call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}], matchstrlist(['acd'], '\(a\)\?\(b\)\?\(c\)\?\(.*\)', {'submatches': v:true}))
  958. #" null dict argument
  959. call assert_equal([{'idx': 0, 'byteidx': 0, 'text': 'vim'}],
  960. \ matchstrlist(['vim'], '\w\+', v:_null_dict))
  961. #" Error cases
  962. call assert_fails("echo matchstrlist('abc', 'a')", 'E1211: List required for argument 1')
  963. call assert_fails("echo matchstrlist(['abc'], {})", 'E1174: String required for argument 2')
  964. call assert_fails("echo matchstrlist(['abc'], '.', [])", 'E1206: Dictionary required for argument 3')
  965. call assert_fails("echo matchstrlist(['abc'], 'a', {'submatches': []})", 'E475: Invalid value for argument submatches')
  966. call assert_fails("echo matchstrlist(['abc'], '\\@=')", 'E866: (NFA regexp) Misplaced @')
  967. END
  968. call CheckLegacyAndVim9Success(lines)
  969. let lines =<< trim END
  970. vim9script
  971. # non string items
  972. matchstrlist([0z10, {'a': 'x'}], 'x')
  973. END
  974. call CheckSourceSuccess(lines)
  975. let lines =<< trim END
  976. vim9script
  977. def Foo()
  978. # non string items
  979. assert_equal([], matchstrlist([0z10, {'a': 'x'}], 'x'))
  980. enddef
  981. Foo()
  982. END
  983. call CheckSourceFailure(lines, 'E1013: Argument 1: type mismatch, expected list<string> but got list<any>', 2)
  984. endfunc
  985. " Test for matchbufline()
  986. func Test_matchbufline()
  987. let lines =<< trim END
  988. #" Basic match
  989. new
  990. call setline(1, ['about', 'above', 'below'])
  991. VAR bnr = bufnr()
  992. wincmd w
  993. call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'bout'},
  994. \ {'lnum': 2, 'byteidx': 1, 'text': 'bove'}],
  995. \ matchbufline(bnr, 'bo.*', 1, '$'))
  996. #" multiple matches in a line
  997. call setbufline(bnr, 1, ['about about', 'above above', 'below'])
  998. call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'bout'},
  999. \ {'lnum': 1, 'byteidx': 7, 'text': 'bout'},
  1000. \ {'lnum': 2, 'byteidx': 1, 'text': 'bove'},
  1001. \ {'lnum': 2, 'byteidx': 7, 'text': 'bove'}],
  1002. \ matchbufline(bnr, 'bo\k\+', 1, '$'))
  1003. #" no match
  1004. call assert_equal([], matchbufline(bnr, 'xy.*', 1, '$'))
  1005. #" match on a particular line
  1006. call assert_equal([{'lnum': 2, 'byteidx': 7, 'text': 'bove'}],
  1007. \ matchbufline(bnr, 'bo\k\+$', 2, 2))
  1008. #" match on a particular line
  1009. call assert_equal([], matchbufline(bnr, 'bo.*', 3, 3))
  1010. #" empty string
  1011. call deletebufline(bnr, 1, '$')
  1012. call assert_equal([], matchbufline(bnr, '.', 1, '$'))
  1013. #" empty pattern
  1014. call setbufline(bnr, 1, 'abc')
  1015. call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
  1016. \ matchbufline(bnr, '', 1, '$'))
  1017. #" method call
  1018. call setbufline(bnr, 1, 'editor')
  1019. call assert_equal([{'lnum': 1, 'byteidx': 2, 'text': 'it'}],
  1020. \ bnr->matchbufline('ed\zsit\zeor', 1, 1))
  1021. #" single character matches
  1022. call assert_equal([{'lnum': 1, 'byteidx': 5, 'text': 'r'}],
  1023. \ matchbufline(bnr, 'r', 1, '$'))
  1024. call setbufline(bnr, 1, 'a')
  1025. call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'a'}],
  1026. \ matchbufline(bnr, 'a', 1, '$'))
  1027. #" zero-width match
  1028. call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
  1029. \ matchbufline(bnr, '\zs', 1, '$'))
  1030. #" string with tabs
  1031. call setbufline(bnr, 1, "\tfoobar")
  1032. call assert_equal([{'lnum': 1, 'byteidx': 1, 'text': 'foo'}],
  1033. \ matchbufline(bnr, 'foo', 1, '$'))
  1034. #" string with multibyte characters
  1035. call setbufline(bnr, 1, "\t\t😊😊")
  1036. call assert_equal([{'lnum': 1, 'byteidx': 2, 'text': '😊😊'}],
  1037. \ matchbufline(bnr, '\k\+', 1, '$'))
  1038. #" empty buffer
  1039. call deletebufline(bnr, 1, '$')
  1040. call assert_equal([], matchbufline(bnr, 'abc', 1, '$'))
  1041. #" Non existing buffer
  1042. call setbufline(bnr, 1, 'abc')
  1043. call assert_fails("echo matchbufline(5000, 'abc', 1, 1)", 'E158: Invalid buffer name: 5000')
  1044. #" null string
  1045. call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': ''}],
  1046. \ matchbufline(bnr, v:_null_string, 1, 1))
  1047. #" invalid starting line number
  1048. call assert_equal([], matchbufline(bnr, 'abc', 100, 100))
  1049. #" ending line number greater than the last line
  1050. call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'abc'}],
  1051. \ matchbufline(bnr, 'abc', 1, 100))
  1052. #" ending line number greater than the starting line number
  1053. call setbufline(bnr, 1, ['one', 'two'])
  1054. call assert_fails($"echo matchbufline({bnr}, 'abc', 2, 1)", 'E475: Invalid value for argument end_lnum')
  1055. #" sub matches
  1056. call deletebufline(bnr, 1, '$')
  1057. call setbufline(bnr, 1, 'acd')
  1058. call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'acd', 'submatches': ['a', '', 'c', 'd', '', '', '', '', '']}],
  1059. \ matchbufline(bnr, '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 1, '$', {'submatches': v:true}))
  1060. #" null dict argument
  1061. call assert_equal([{'lnum': 1, 'byteidx': 0, 'text': 'acd'}],
  1062. \ matchbufline(bnr, '\w\+', '$', '$', v:_null_dict))
  1063. #" Error cases
  1064. call assert_fails("echo matchbufline([1], 'abc', 1, 1)", 'E1220: String or Number required for argument 1')
  1065. call assert_fails("echo matchbufline(1, {}, 1, 1)", 'E1174: String required for argument 2')
  1066. call assert_fails("echo matchbufline(1, 'abc', {}, 1)", 'E1220: String or Number required for argument 3')
  1067. call assert_fails("echo matchbufline(1, 'abc', 1, {})", 'E1220: String or Number required for argument 4')
  1068. call assert_fails($"echo matchbufline({bnr}, 'abc', -1, '$')", 'E475: Invalid value for argument lnum')
  1069. call assert_fails($"echo matchbufline({bnr}, 'abc', 1, -1)", 'E475: Invalid value for argument end_lnum')
  1070. call assert_fails($"echo matchbufline({bnr}, '\\@=', 1, 1)", 'E866: (NFA regexp) Misplaced @')
  1071. call assert_fails($"echo matchbufline({bnr}, 'abc', 1, 1, {{'submatches': []}})", 'E475: Invalid value for argument submatches')
  1072. :%bdelete!
  1073. call assert_fails($"echo matchbufline({bnr}, 'abc', 1, '$'))", 'E681: Buffer is not loaded')
  1074. END
  1075. call CheckLegacyAndVim9Success(lines)
  1076. call assert_fails($"echo matchbufline('', 'abc', 'abc', 1)", 'E475: Invalid value for argument lnum')
  1077. call assert_fails($"echo matchbufline('', 'abc', 1, 'abc')", 'E475: Invalid value for argument end_lnum')
  1078. let lines =<< trim END
  1079. vim9script
  1080. def Foo()
  1081. echo matchbufline('', 'abc', 'abc', 1)
  1082. enddef
  1083. Foo()
  1084. END
  1085. call CheckSourceFailure(lines, 'E1030: Using a String as a Number: "abc"', 1)
  1086. let lines =<< trim END
  1087. vim9script
  1088. def Foo()
  1089. echo matchbufline('', 'abc', 1, 'abc')
  1090. enddef
  1091. Foo()
  1092. END
  1093. call CheckSourceFailure(lines, 'E1030: Using a String as a Number: "abc"', 1)
  1094. endfunc
  1095. func Test_nextnonblank_prevnonblank()
  1096. new
  1097. insert
  1098. This
  1099. is
  1100. a
  1101. Test
  1102. .
  1103. call assert_equal(0, nextnonblank(-1))
  1104. call assert_equal(0, nextnonblank(0))
  1105. call assert_equal(1, nextnonblank(1))
  1106. call assert_equal(4, 2->nextnonblank())
  1107. call assert_equal(4, nextnonblank(3))
  1108. call assert_equal(4, nextnonblank(4))
  1109. call assert_equal(6, nextnonblank(5))
  1110. call assert_equal(6, nextnonblank(6))
  1111. call assert_equal(7, nextnonblank(7))
  1112. call assert_equal(0, 8->nextnonblank())
  1113. call assert_equal(0, prevnonblank(-1))
  1114. call assert_equal(0, prevnonblank(0))
  1115. call assert_equal(1, 1->prevnonblank())
  1116. call assert_equal(1, prevnonblank(2))
  1117. call assert_equal(1, prevnonblank(3))
  1118. call assert_equal(4, prevnonblank(4))
  1119. call assert_equal(4, 5->prevnonblank())
  1120. call assert_equal(6, prevnonblank(6))
  1121. call assert_equal(7, prevnonblank(7))
  1122. call assert_equal(0, prevnonblank(8))
  1123. bw!
  1124. endfunc
  1125. func Test_byte2line_line2byte()
  1126. new
  1127. set endofline
  1128. call setline(1, ['a', 'bc', 'd'])
  1129. set fileformat=unix
  1130. call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
  1131. \ map(range(-1, 8), 'byte2line(v:val)'))
  1132. call assert_equal([-1, -1, 1, 3, 6, 8, -1],
  1133. \ map(range(-1, 5), 'line2byte(v:val)'))
  1134. set fileformat=mac
  1135. call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1],
  1136. \ map(range(-1, 8), 'v:val->byte2line()'))
  1137. call assert_equal([-1, -1, 1, 3, 6, 8, -1],
  1138. \ map(range(-1, 5), 'v:val->line2byte()'))
  1139. set fileformat=dos
  1140. call assert_equal([-1, -1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, -1],
  1141. \ map(range(-1, 11), 'byte2line(v:val)'))
  1142. call assert_equal([-1, -1, 1, 4, 8, 11, -1],
  1143. \ map(range(-1, 5), 'line2byte(v:val)'))
  1144. bw!
  1145. set noendofline nofixendofline
  1146. normal a-
  1147. for ff in ["unix", "mac", "dos"]
  1148. let &fileformat = ff
  1149. call assert_equal(1, line2byte(1))
  1150. call assert_equal(2, line2byte(2)) " line2byte(line("$") + 1) is the buffer size plus one (as per :help line2byte).
  1151. endfor
  1152. set endofline& fixendofline& fileformat&
  1153. bw!
  1154. endfunc
  1155. " Test for byteidx() using a character index
  1156. func Test_byteidx()
  1157. let a = '.é.' " one char of two bytes
  1158. call assert_equal(0, byteidx(a, 0))
  1159. call assert_equal(1, byteidx(a, 1))
  1160. call assert_equal(3, byteidx(a, 2))
  1161. call assert_equal(4, byteidx(a, 3))
  1162. call assert_equal(-1, byteidx(a, 4))
  1163. let b = '.é.' " normal e with composing char
  1164. call assert_equal(0, b->byteidx(0))
  1165. call assert_equal(1, b->byteidx(1))
  1166. call assert_equal(4, b->byteidx(2))
  1167. call assert_equal(5, b->byteidx(3))
  1168. call assert_equal(-1, b->byteidx(4))
  1169. " string with multiple composing characters
  1170. let str = '-ą́-ą́'
  1171. call assert_equal(0, byteidx(str, 0))
  1172. call assert_equal(1, byteidx(str, 1))
  1173. call assert_equal(6, byteidx(str, 2))
  1174. call assert_equal(7, byteidx(str, 3))
  1175. call assert_equal(12, byteidx(str, 4))
  1176. call assert_equal(-1, byteidx(str, 5))
  1177. " empty string
  1178. call assert_equal(0, byteidx('', 0))
  1179. call assert_equal(-1, byteidx('', 1))
  1180. " error cases
  1181. call assert_fails("call byteidx([], 0)", 'E730:')
  1182. call assert_fails("call byteidx('abc', [])", 'E745:')
  1183. call assert_fails("call byteidx('abc', 0, {})", ['E728:', 'E728:'])
  1184. call assert_fails("call byteidx('abc', 0, -1)", ['E1023:', 'E1023:'])
  1185. endfunc
  1186. " Test for byteidxcomp() using a character index
  1187. func Test_byteidxcomp()
  1188. let a = '.é.' " one char of two bytes
  1189. call assert_equal(0, byteidxcomp(a, 0))
  1190. call assert_equal(1, byteidxcomp(a, 1))
  1191. call assert_equal(3, byteidxcomp(a, 2))
  1192. call assert_equal(4, byteidxcomp(a, 3))
  1193. call assert_equal(-1, byteidxcomp(a, 4))
  1194. let b = '.é.' " normal e with composing char
  1195. call assert_equal(0, b->byteidxcomp(0))
  1196. call assert_equal(1, b->byteidxcomp(1))
  1197. call assert_equal(2, b->byteidxcomp(2))
  1198. call assert_equal(4, b->byteidxcomp(3))
  1199. call assert_equal(5, b->byteidxcomp(4))
  1200. call assert_equal(-1, b->byteidxcomp(5))
  1201. " string with multiple composing characters
  1202. let str = '-ą́-ą́'
  1203. call assert_equal(0, byteidxcomp(str, 0))
  1204. call assert_equal(1, byteidxcomp(str, 1))
  1205. call assert_equal(2, byteidxcomp(str, 2))
  1206. call assert_equal(4, byteidxcomp(str, 3))
  1207. call assert_equal(6, byteidxcomp(str, 4))
  1208. call assert_equal(7, byteidxcomp(str, 5))
  1209. call assert_equal(8, byteidxcomp(str, 6))
  1210. call assert_equal(10, byteidxcomp(str, 7))
  1211. call assert_equal(12, byteidxcomp(str, 8))
  1212. call assert_equal(-1, byteidxcomp(str, 9))
  1213. " empty string
  1214. call assert_equal(0, byteidxcomp('', 0))
  1215. call assert_equal(-1, byteidxcomp('', 1))
  1216. " error cases
  1217. call assert_fails("call byteidxcomp([], 0)", 'E730:')
  1218. call assert_fails("call byteidxcomp('abc', [])", 'E745:')
  1219. call assert_fails("call byteidxcomp('abc', 0, {})", ['E728:', 'E728:'])
  1220. call assert_fails("call byteidxcomp('abc', 0, -1)", ['E1023:', 'E1023:'])
  1221. endfunc
  1222. " Test for byteidx() using a UTF-16 index
  1223. func Test_byteidx_from_utf16_index()
  1224. " string with single byte characters
  1225. let str = "abc"
  1226. for i in range(3)
  1227. call assert_equal(i, byteidx(str, i, v:true))
  1228. endfor
  1229. call assert_equal(3, byteidx(str, 3, v:true))
  1230. call assert_equal(-1, byteidx(str, 4, v:true))
  1231. " string with two byte characters
  1232. let str = "a©©b"
  1233. call assert_equal(0, byteidx(str, 0, v:true))
  1234. call assert_equal(1, byteidx(str, 1, v:true))
  1235. call assert_equal(3, byteidx(str, 2, v:true))
  1236. call assert_equal(5, byteidx(str, 3, v:true))
  1237. call assert_equal(6, byteidx(str, 4, v:true))
  1238. call assert_equal(-1, byteidx(str, 5, v:true))
  1239. " string with two byte characters
  1240. let str = "a😊😊b"
  1241. call assert_equal(0, byteidx(str, 0, v:true))
  1242. call assert_equal(1, byteidx(str, 1, v:true))
  1243. call assert_equal(1, byteidx(str, 2, v:true))
  1244. call assert_equal(5, byteidx(str, 3, v:true))
  1245. call assert_equal(5, byteidx(str, 4, v:true))
  1246. call assert_equal(9, byteidx(str, 5, v:true))
  1247. call assert_equal(10, byteidx(str, 6, v:true))
  1248. call assert_equal(-1, byteidx(str, 7, v:true))
  1249. " string with composing characters
  1250. let str = '-á-b́'
  1251. call assert_equal(0, byteidx(str, 0, v:true))
  1252. call assert_equal(1, byteidx(str, 1, v:true))
  1253. call assert_equal(4, byteidx(str, 2, v:true))
  1254. call assert_equal(5, byteidx(str, 3, v:true))
  1255. call assert_equal(8, byteidx(str, 4, v:true))
  1256. call assert_equal(-1, byteidx(str, 5, v:true))
  1257. " string with multiple composing characters
  1258. let str = '-ą́-ą́'
  1259. call assert_equal(0, byteidx(str, 0, v:true))
  1260. call assert_equal(1, byteidx(str, 1, v:true))
  1261. call assert_equal(6, byteidx(str, 2, v:true))
  1262. call assert_equal(7, byteidx(str, 3, v:true))
  1263. call assert_equal(12, byteidx(str, 4, v:true))
  1264. call assert_equal(-1, byteidx(str, 5, v:true))
  1265. " empty string
  1266. call assert_equal(0, byteidx('', 0, v:true))
  1267. call assert_equal(-1, byteidx('', 1, v:true))
  1268. " error cases
  1269. call assert_fails('call byteidx(str, 0, [])', 'E745:')
  1270. endfunc
  1271. " Test for byteidxcomp() using a UTF-16 index
  1272. func Test_byteidxcomp_from_utf16_index()
  1273. " string with single byte characters
  1274. let str = "abc"
  1275. for i in range(3)
  1276. call assert_equal(i, byteidxcomp(str, i, v:true))
  1277. endfor
  1278. call assert_equal(3, byteidxcomp(str, 3, v:true))
  1279. call assert_equal(-1, byteidxcomp(str, 4, v:true))
  1280. " string with two byte characters
  1281. let str = "a©©b"
  1282. call assert_equal(0, byteidxcomp(str, 0, v:true))
  1283. call assert_equal(1, byteidxcomp(str, 1, v:true))
  1284. call assert_equal(3, byteidxcomp(str, 2, v:true))
  1285. call assert_equal(5, byteidxcomp(str, 3, v:true))
  1286. call assert_equal(6, byteidxcomp(str, 4, v:true))
  1287. call assert_equal(-1, byteidxcomp(str, 5, v:true))
  1288. " string with two byte characters
  1289. let str = "a😊😊b"
  1290. call assert_equal(0, byteidxcomp(str, 0, v:true))
  1291. call assert_equal(1, byteidxcomp(str, 1, v:true))
  1292. call assert_equal(1, byteidxcomp(str, 2, v:true))
  1293. call assert_equal(5, byteidxcomp(str, 3, v:true))
  1294. call assert_equal(5, byteidxcomp(str, 4, v:true))
  1295. call assert_equal(9, byteidxcomp(str, 5, v:true))
  1296. call assert_equal(10, byteidxcomp(str, 6, v:true))
  1297. call assert_equal(-1, byteidxcomp(str, 7, v:true))
  1298. " string with composing characters
  1299. let str = '-á-b́'
  1300. call assert_equal(0, byteidxcomp(str, 0, v:true))
  1301. call assert_equal(1, byteidxcomp(str, 1, v:true))
  1302. call assert_equal(2, byteidxcomp(str, 2, v:true))
  1303. call assert_equal(4, byteidxcomp(str, 3, v:true))
  1304. call assert_equal(5, byteidxcomp(str, 4, v:true))
  1305. call assert_equal(6, byteidxcomp(str, 5, v:true))
  1306. call assert_equal(8, byteidxcomp(str, 6, v:true))
  1307. call assert_equal(-1, byteidxcomp(str, 7, v:true))
  1308. call assert_fails('call byteidxcomp(str, 0, [])', 'E745:')
  1309. " string with multiple composing characters
  1310. let str = '-ą́-ą́'
  1311. call assert_equal(0, byteidxcomp(str, 0, v:true))
  1312. call assert_equal(1, byteidxcomp(str, 1, v:true))
  1313. call assert_equal(2, byteidxcomp(str, 2, v:true))
  1314. call assert_equal(4, byteidxcomp(str, 3, v:true))
  1315. call assert_equal(6, byteidxcomp(str, 4, v:true))
  1316. call assert_equal(7, byteidxcomp(str, 5, v:true))
  1317. call assert_equal(8, byteidxcomp(str, 6, v:true))
  1318. call assert_equal(10, byteidxcomp(str, 7, v:true))
  1319. call assert_equal(12, byteidxcomp(str, 8, v:true))
  1320. call assert_equal(-1, byteidxcomp(str, 9, v:true))
  1321. " empty string
  1322. call assert_equal(0, byteidxcomp('', 0, v:true))
  1323. call assert_equal(-1, byteidxcomp('', 1, v:true))
  1324. " error cases
  1325. call assert_fails('call byteidxcomp(str, 0, [])', 'E745:')
  1326. endfunc
  1327. " Test for charidx() using a byte index
  1328. func Test_charidx()
  1329. let a = 'xáb́y'
  1330. call assert_equal(0, charidx(a, 0))
  1331. call assert_equal(1, charidx(a, 3))
  1332. call assert_equal(2, charidx(a, 4))
  1333. call assert_equal(3, charidx(a, 7))
  1334. call assert_equal(4, charidx(a, 8))
  1335. call assert_equal(-1, charidx(a, 9))
  1336. call assert_equal(-1, charidx(a, -1))
  1337. " count composing characters
  1338. call assert_equal(0, a->charidx(0, 1))
  1339. call assert_equal(2, a->charidx(2, 1))
  1340. call assert_equal(3, a->charidx(4, 1))
  1341. call assert_equal(5, a->charidx(7, 1))
  1342. call assert_equal(6, a->charidx(8, 1))
  1343. call assert_equal(-1, a->charidx(9, 1))
  1344. " empty string
  1345. call assert_equal(0, charidx('', 0))
  1346. call assert_equal(-1, charidx('', 1))
  1347. call assert_equal(0, charidx('', 0, 1))
  1348. call assert_equal(-1, charidx('', 1, 1))
  1349. " error cases
  1350. call assert_equal(0, charidx(v:_null_string, 0))
  1351. call assert_equal(-1, charidx(v:_null_string, 1))
  1352. call assert_fails('let x = charidx([], 1)', 'E1174:')
  1353. call assert_fails('let x = charidx("abc", [])', 'E1210:')
  1354. call assert_fails('let x = charidx("abc", 1, [])', 'E1212:')
  1355. call assert_fails('let x = charidx("abc", 1, -1)', 'E1212:')
  1356. call assert_fails('let x = charidx("abc", 1, 2)', 'E1212:')
  1357. endfunc
  1358. " Test for charidx() using a UTF-16 index
  1359. func Test_charidx_from_utf16_index()
  1360. " string with single byte characters
  1361. let str = "abc"
  1362. for i in range(4)
  1363. call assert_equal(i, charidx(str, i, v:false, v:true))
  1364. endfor
  1365. call assert_equal(-1, charidx(str, 4, v:false, v:true))
  1366. " string with two byte characters
  1367. let str = "a©©b"
  1368. call assert_equal(0, charidx(str, 0, v:false, v:true))
  1369. call assert_equal(1, charidx(str, 1, v:false, v:true))
  1370. call assert_equal(2, charidx(str, 2, v:false, v:true))
  1371. call assert_equal(3, charidx(str, 3, v:false, v:true))
  1372. call assert_equal(4, charidx(str, 4, v:false, v:true))
  1373. call assert_equal(-1, charidx(str, 5, v:false, v:true))
  1374. " string with four byte characters
  1375. let str = "a😊😊b"
  1376. call assert_equal(0, charidx(str, 0, v:false, v:true))
  1377. call assert_equal(1, charidx(str, 1, v:false, v:true))
  1378. call assert_equal(1, charidx(str, 2, v:false, v:true))
  1379. call assert_equal(2, charidx(str, 3, v:false, v:true))
  1380. call assert_equal(2, charidx(str, 4, v:false, v:true))
  1381. call assert_equal(3, charidx(str, 5, v:false, v:true))
  1382. call assert_equal(4, charidx(str, 6, v:false, v:true))
  1383. call assert_equal(-1, charidx(str, 7, v:false, v:true))
  1384. " string with composing characters
  1385. let str = '-á-b́'
  1386. for i in str->strcharlen()->range()
  1387. call assert_equal(i, charidx(str, i, v:false, v:true))
  1388. endfor
  1389. call assert_equal(4, charidx(str, 4, v:false, v:true))
  1390. call assert_equal(-1, charidx(str, 5, v:false, v:true))
  1391. for i in str->strchars()->range()
  1392. call assert_equal(i, charidx(str, i, v:true, v:true))
  1393. endfor
  1394. call assert_equal(6, charidx(str, 6, v:true, v:true))
  1395. call assert_equal(-1, charidx(str, 7, v:true, v:true))
  1396. " string with multiple composing characters
  1397. let str = '-ą́-ą́'
  1398. for i in str->strcharlen()->range()
  1399. call assert_equal(i, charidx(str, i, v:false, v:true))
  1400. endfor
  1401. call assert_equal(4, charidx(str, 4, v:false, v:true))
  1402. call assert_equal(-1, charidx(str, 5, v:false, v:true))
  1403. for i in str->strchars()->range()
  1404. call assert_equal(i, charidx(str, i, v:true, v:true))
  1405. endfor
  1406. call assert_equal(8, charidx(str, 8, v:true, v:true))
  1407. call assert_equal(-1, charidx(str, 9, v:true, v:true))
  1408. " empty string
  1409. call assert_equal(0, charidx('', 0, v:false, v:true))
  1410. call assert_equal(-1, charidx('', 1, v:false, v:true))
  1411. call assert_equal(0, charidx('', 0, v:true, v:true))
  1412. call assert_equal(-1, charidx('', 1, v:true, v:true))
  1413. " error cases
  1414. call assert_equal(0, charidx('', 0, v:false, v:true))
  1415. call assert_equal(-1, charidx('', 1, v:false, v:true))
  1416. call assert_equal(0, charidx('', 0, v:true, v:true))
  1417. call assert_equal(-1, charidx('', 1, v:true, v:true))
  1418. call assert_equal(0, charidx(v:_null_string, 0, v:false, v:true))
  1419. call assert_equal(-1, charidx(v:_null_string, 1, v:false, v:true))
  1420. call assert_fails('let x = charidx("abc", 1, v:false, [])', 'E1212:')
  1421. call assert_fails('let x = charidx("abc", 1, v:true, [])', 'E1212:')
  1422. endfunc
  1423. " Test for utf16idx() using a byte index
  1424. func Test_utf16idx_from_byteidx()
  1425. " UTF-16 index of a string with single byte characters
  1426. let str = "abc"
  1427. for i in range(4)
  1428. call assert_equal(i, utf16idx(str, i))
  1429. endfor
  1430. call assert_equal(-1, utf16idx(str, 4))
  1431. " UTF-16 index of a string with two byte characters
  1432. let str = 'a©©b'
  1433. call assert_equal(0, str->utf16idx(0))
  1434. call assert_equal(1, str->utf16idx(1))
  1435. call assert_equal(1, str->utf16idx(2))
  1436. call assert_equal(2, str->utf16idx(3))
  1437. call assert_equal(2, str->utf16idx(4))
  1438. call assert_equal(3, str->utf16idx(5))
  1439. call assert_equal(4, str->utf16idx(6))
  1440. call assert_equal(-1, str->utf16idx(7))
  1441. " UTF-16 index of a string with four byte characters
  1442. let str = 'a😊😊b'
  1443. call assert_equal(0, utf16idx(str, 0))
  1444. call assert_equal(1, utf16idx(str, 1))
  1445. call assert_equal(1, utf16idx(str, 2))
  1446. call assert_equal(1, utf16idx(str, 3))
  1447. call assert_equal(1, utf16idx(str, 4))
  1448. call assert_equal(3, utf16idx(str, 5))
  1449. call assert_equal(3, utf16idx(str, 6))
  1450. call assert_equal(3, utf16idx(str, 7))
  1451. call assert_equal(3, utf16idx(str, 8))
  1452. call assert_equal(5, utf16idx(str, 9))
  1453. call assert_equal(6, utf16idx(str, 10))
  1454. call assert_equal(-1, utf16idx(str, 11))
  1455. " UTF-16 index of a string with composing characters
  1456. let str = '-á-b́'
  1457. call assert_equal(0, utf16idx(str, 0))
  1458. call assert_equal(1, utf16idx(str, 1))
  1459. call assert_equal(1, utf16idx(str, 2))
  1460. call assert_equal(1, utf16idx(str, 3))
  1461. call assert_equal(2, utf16idx(str, 4))
  1462. call assert_equal(3, utf16idx(str, 5))
  1463. call assert_equal(3, utf16idx(str, 6))
  1464. call assert_equal(3, utf16idx(str, 7))
  1465. call assert_equal(4, utf16idx(str, 8))
  1466. call assert_equal(-1, utf16idx(str, 9))
  1467. call assert_equal(0, utf16idx(str, 0, v:true))
  1468. call assert_equal(1, utf16idx(str, 1, v:true))
  1469. call assert_equal(2, utf16idx(str, 2, v:true))
  1470. call assert_equal(2, utf16idx(str, 3, v:true))
  1471. call assert_equal(3, utf16idx(str, 4, v:true))
  1472. call assert_equal(4, utf16idx(str, 5, v:true))
  1473. call assert_equal(5, utf16idx(str, 6, v:true))
  1474. call assert_equal(5, utf16idx(str, 7, v:true))
  1475. call assert_equal(6, utf16idx(str, 8, v:true))
  1476. call assert_equal(-1, utf16idx(str, 9, v:true))
  1477. " string with multiple composing characters
  1478. let str = '-ą́-ą́'
  1479. call assert_equal(0, utf16idx(str, 0))
  1480. call assert_equal(1, utf16idx(str, 1))
  1481. call assert_equal(1, utf16idx(str, 2))
  1482. call assert_equal(1, utf16idx(str, 3))
  1483. call assert_equal(1, utf16idx(str, 4))
  1484. call assert_equal(1, utf16idx(str, 5))
  1485. call assert_equal(2, utf16idx(str, 6))
  1486. call assert_equal(3, utf16idx(str, 7))
  1487. call assert_equal(3, utf16idx(str, 8))
  1488. call assert_equal(3, utf16idx(str, 9))
  1489. call assert_equal(3, utf16idx(str, 10))
  1490. call assert_equal(3, utf16idx(str, 11))
  1491. call assert_equal(4, utf16idx(str, 12))
  1492. call assert_equal(-1, utf16idx(str, 13))
  1493. call assert_equal(0, utf16idx(str, 0, v:true))
  1494. call assert_equal(1, utf16idx(str, 1, v:true))
  1495. call assert_equal(2, utf16idx(str, 2, v:true))
  1496. call assert_equal(2, utf16idx(str, 3, v:true))
  1497. call assert_equal(3, utf16idx(str, 4, v:true))
  1498. call assert_equal(3, utf16idx(str, 5, v:true))
  1499. call assert_equal(4, utf16idx(str, 6, v:true))
  1500. call assert_equal(5, utf16idx(str, 7, v:true))
  1501. call assert_equal(6, utf16idx(str, 8, v:true))
  1502. call assert_equal(6, utf16idx(str, 9, v:true))
  1503. call assert_equal(7, utf16idx(str, 10, v:true))
  1504. call assert_equal(7, utf16idx(str, 11, v:true))
  1505. call assert_equal(8, utf16idx(str, 12, v:true))
  1506. call assert_equal(-1, utf16idx(str, 13, v:true))
  1507. " empty string
  1508. call assert_equal(0, utf16idx('', 0))
  1509. call assert_equal(-1, utf16idx('', 1))
  1510. call assert_equal(0, utf16idx('', 0, v:true))
  1511. call assert_equal(-1, utf16idx('', 1, v:true))
  1512. " error cases
  1513. call assert_equal(0, utf16idx("", 0))
  1514. call assert_equal(-1, utf16idx("", 1))
  1515. call assert_equal(-1, utf16idx("abc", -1))
  1516. call assert_equal(0, utf16idx(v:_null_string, 0))
  1517. call assert_equal(-1, utf16idx(v:_null_string, 1))
  1518. call assert_fails('let l = utf16idx([], 0)', 'E1174:')
  1519. call assert_fails('let l = utf16idx("ab", [])', 'E1210:')
  1520. call assert_fails('let l = utf16idx("ab", 0, [])', 'E1212:')
  1521. endfunc
  1522. " Test for utf16idx() using a character index
  1523. func Test_utf16idx_from_charidx()
  1524. let str = "abc"
  1525. for i in str->strcharlen()->range()
  1526. call assert_equal(i, utf16idx(str, i, v:false, v:true))
  1527. endfor
  1528. call assert_equal(3, utf16idx(str, 3, v:false, v:true))
  1529. call assert_equal(-1, utf16idx(str, 4, v:false, v:true))
  1530. " UTF-16 index of a string with two byte characters
  1531. let str = "a©©b"
  1532. for i in str->strcharlen()->range()
  1533. call assert_equal(i, utf16idx(str, i, v:false, v:true))
  1534. endfor
  1535. call assert_equal(4, utf16idx(str, 4, v:false, v:true))
  1536. call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
  1537. " UTF-16 index of a string with four byte characters
  1538. let str = "a😊😊b"
  1539. call assert_equal(0, utf16idx(str, 0, v:false, v:true))
  1540. call assert_equal(1, utf16idx(str, 1, v:false, v:true))
  1541. call assert_equal(3, utf16idx(str, 2, v:false, v:true))
  1542. call assert_equal(5, utf16idx(str, 3, v:false, v:true))
  1543. call assert_equal(6, utf16idx(str, 4, v:false, v:true))
  1544. call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
  1545. " UTF-16 index of a string with composing characters
  1546. let str = '-á-b́'
  1547. for i in str->strcharlen()->range()
  1548. call assert_equal(i, utf16idx(str, i, v:false, v:true))
  1549. endfor
  1550. call assert_equal(4, utf16idx(str, 4, v:false, v:true))
  1551. call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
  1552. for i in str->strchars()->range()
  1553. call assert_equal(i, utf16idx(str, i, v:true, v:true))
  1554. endfor
  1555. call assert_equal(6, utf16idx(str, 6, v:true, v:true))
  1556. call assert_equal(-1, utf16idx(str, 7, v:true, v:true))
  1557. " string with multiple composing characters
  1558. let str = '-ą́-ą́'
  1559. for i in str->strcharlen()->range()
  1560. call assert_equal(i, utf16idx(str, i, v:false, v:true))
  1561. endfor
  1562. call assert_equal(4, utf16idx(str, 4, v:false, v:true))
  1563. call assert_equal(-1, utf16idx(str, 5, v:false, v:true))
  1564. for i in str->strchars()->range()
  1565. call assert_equal(i, utf16idx(str, i, v:true, v:true))
  1566. endfor
  1567. call assert_equal(8, utf16idx(str, 8, v:true, v:true))
  1568. call assert_equal(-1, utf16idx(str, 9, v:true, v:true))
  1569. " empty string
  1570. call assert_equal(0, utf16idx('', 0, v:false, v:true))
  1571. call assert_equal(-1, utf16idx('', 1, v:false, v:true))
  1572. call assert_equal(0, utf16idx('', 0, v:true, v:true))
  1573. call assert_equal(-1, utf16idx('', 1, v:true, v:true))
  1574. " error cases
  1575. call assert_equal(0, utf16idx(v:_null_string, 0, v:true, v:true))
  1576. call assert_equal(-1, utf16idx(v:_null_string, 1, v:true, v:true))
  1577. call assert_fails('let l = utf16idx("ab", 0, v:false, [])', 'E1212:')
  1578. endfunc
  1579. " Test for strutf16len()
  1580. func Test_strutf16len()
  1581. call assert_equal(3, strutf16len('abc'))
  1582. call assert_equal(3, 'abc'->strutf16len(v:true))
  1583. call assert_equal(4, strutf16len('a©©b'))
  1584. call assert_equal(4, strutf16len('a©©b', v:true))
  1585. call assert_equal(6, strutf16len('a😊😊b'))
  1586. call assert_equal(6, strutf16len('a😊😊b', v:true))
  1587. call assert_equal(4, strutf16len('-á-b́'))
  1588. call assert_equal(6, strutf16len('-á-b́', v:true))
  1589. call assert_equal(4, strutf16len('-ą́-ą́'))
  1590. call assert_equal(8, strutf16len('-ą́-ą́', v:true))
  1591. call assert_equal(0, strutf16len(''))
  1592. " error cases
  1593. call assert_fails('let l = strutf16len([])', 'E1174:')
  1594. call assert_fails('let l = strutf16len("a", [])', 'E1212:')
  1595. call assert_equal(0, strutf16len(v:_null_string))
  1596. endfunc
  1597. func Test_count()
  1598. let l = ['a', 'a', 'A', 'b']
  1599. call assert_equal(2, count(l, 'a'))
  1600. call assert_equal(1, count(l, 'A'))
  1601. call assert_equal(1, count(l, 'b'))
  1602. call assert_equal(0, count(l, 'B'))
  1603. call assert_equal(2, count(l, 'a', 0))
  1604. call assert_equal(1, count(l, 'A', 0))
  1605. call assert_equal(1, count(l, 'b', 0))
  1606. call assert_equal(0, count(l, 'B', 0))
  1607. call assert_equal(3, count(l, 'a', 1))
  1608. call assert_equal(3, count(l, 'A', 1))
  1609. call assert_equal(1, count(l, 'b', 1))
  1610. call assert_equal(1, count(l, 'B', 1))
  1611. call assert_equal(0, count(l, 'c', 1))
  1612. call assert_equal(1, count(l, 'a', 0, 1))
  1613. call assert_equal(2, count(l, 'a', 1, 1))
  1614. call assert_fails('call count(l, "a", 0, 10)', 'E684:')
  1615. call assert_fails('call count(l, "a", [])', 'E745:')
  1616. let d = {1: 'a', 2: 'a', 3: 'A', 4: 'b'}
  1617. call assert_equal(2, count(d, 'a'))
  1618. call assert_equal(1, count(d, 'A'))
  1619. call assert_equal(1, count(d, 'b'))
  1620. call assert_equal(0, count(d, 'B'))
  1621. call assert_equal(2, count(d, 'a', 0))
  1622. call assert_equal(1, count(d, 'A', 0))
  1623. call assert_equal(1, count(d, 'b', 0))
  1624. call assert_equal(0, count(d, 'B', 0))
  1625. call assert_equal(3, count(d, 'a', 1))
  1626. call assert_equal(3, count(d, 'A', 1))
  1627. call assert_equal(1, count(d, 'b', 1))
  1628. call assert_equal(1, count(d, 'B', 1))
  1629. call assert_equal(0, count(d, 'c', 1))
  1630. call assert_fails('call count(d, "a", 0, 1)', 'E474:')
  1631. call assert_equal(0, count("foo", "bar"))
  1632. call assert_equal(1, count("foo", "oo"))
  1633. call assert_equal(2, count("foo", "o"))
  1634. call assert_equal(0, count("foo", "O"))
  1635. call assert_equal(2, count("foo", "O", 1))
  1636. call assert_equal(2, count("fooooo", "oo"))
  1637. call assert_equal(0, count("foo", ""))
  1638. call assert_fails('call count(0, 0)', 'E706:')
  1639. call assert_fails('call count("", "", {})', ['E728:', 'E728:'])
  1640. endfunc
  1641. func Test_changenr()
  1642. new Xchangenr
  1643. call assert_equal(0, changenr())
  1644. norm ifoo
  1645. call assert_equal(1, changenr())
  1646. set undolevels=10
  1647. norm Sbar
  1648. call assert_equal(2, changenr())
  1649. undo
  1650. call assert_equal(1, changenr())
  1651. redo
  1652. call assert_equal(2, changenr())
  1653. bw!
  1654. set undolevels&
  1655. endfunc
  1656. func Test_filewritable()
  1657. new Xfilewritable
  1658. write!
  1659. call assert_equal(1, filewritable('Xfilewritable'))
  1660. call assert_notequal(0, setfperm('Xfilewritable', 'r--r-----'))
  1661. call assert_equal(0, filewritable('Xfilewritable'))
  1662. call assert_notequal(0, setfperm('Xfilewritable', 'rw-r-----'))
  1663. call assert_equal(1, 'Xfilewritable'->filewritable())
  1664. call assert_equal(0, filewritable('doesnotexist'))
  1665. call mkdir('Xdir')
  1666. call assert_equal(2, filewritable('Xdir'))
  1667. call delete('Xdir', 'd')
  1668. call delete('Xfilewritable')
  1669. bw!
  1670. endfunc
  1671. func Test_Executable()
  1672. if has('win32')
  1673. call assert_equal(1, executable('notepad'))
  1674. call assert_equal(1, 'notepad.exe'->executable())
  1675. call assert_equal(0, executable('notepad.exe.exe'))
  1676. call assert_equal(0, executable('shell32.dll'))
  1677. call assert_equal(0, executable('win.ini'))
  1678. elseif has('unix')
  1679. call assert_equal(1, 'cat'->executable())
  1680. call assert_equal(0, executable('nodogshere'))
  1681. " get "cat" path and remove the leading /
  1682. let catcmd = exepath('cat')[1:]
  1683. new
  1684. " check that the relative path works in /
  1685. lcd /
  1686. call assert_equal(1, executable(catcmd))
  1687. let result = catcmd->exepath()
  1688. " when using chroot looking for sbin/cat can return bin/cat, that is OK
  1689. if catcmd =~ '\<sbin\>' && result =~ '\<bin\>'
  1690. call assert_equal('/' .. substitute(catcmd, '\<sbin\>', 'bin', ''), result)
  1691. else
  1692. " /bin/cat and /usr/bin/cat may be hard linked, we could get either
  1693. let result = substitute(result, '/usr/bin/cat', '/bin/cat', '')
  1694. let catcmd = substitute(catcmd, 'usr/bin/cat', 'bin/cat', '')
  1695. call assert_equal('/' .. catcmd, result)
  1696. endif
  1697. bwipe
  1698. else
  1699. throw 'Skipped: does not work on this platform'
  1700. endif
  1701. endfunc
  1702. func Test_executable_longname()
  1703. if !has('win32')
  1704. return
  1705. endif
  1706. let fname = 'X' . repeat('あ', 200) . '.bat'
  1707. call writefile([], fname)
  1708. call assert_equal(1, executable(fname))
  1709. call delete(fname)
  1710. endfunc
  1711. func Test_hostname()
  1712. let hostname_vim = hostname()
  1713. if has('unix')
  1714. let hostname_system = systemlist('uname -n')[0]
  1715. call assert_equal(hostname_vim, hostname_system)
  1716. endif
  1717. endfunc
  1718. func Test_getpid()
  1719. " getpid() always returns the same value within a vim instance.
  1720. call assert_equal(getpid(), getpid())
  1721. if has('unix')
  1722. call assert_equal(systemlist('echo $PPID')[0], string(getpid()))
  1723. endif
  1724. endfunc
  1725. func Test_hlexists()
  1726. call assert_equal(0, hlexists('does_not_exist'))
  1727. " call assert_equal(0, 'Number'->hlexists())
  1728. call assert_equal(0, highlight_exists('does_not_exist'))
  1729. " call assert_equal(0, highlight_exists('Number'))
  1730. syntax on
  1731. call assert_equal(0, hlexists('does_not_exist'))
  1732. " call assert_equal(1, hlexists('Number'))
  1733. call assert_equal(0, highlight_exists('does_not_exist'))
  1734. " call assert_equal(1, highlight_exists('Number'))
  1735. syntax off
  1736. endfunc
  1737. " Test for the col() function
  1738. func Test_col()
  1739. new
  1740. call setline(1, 'abcdef')
  1741. norm gg4|mx6|mY2|
  1742. call assert_equal(2, col('.'))
  1743. call assert_equal(7, col('$'))
  1744. call assert_equal(2, col('v'))
  1745. call assert_equal(4, col("'x"))
  1746. call assert_equal(6, col("'Y"))
  1747. call assert_equal(2, [1, 2]->col())
  1748. call assert_equal(7, col([1, '$']))
  1749. call assert_equal(0, col(''))
  1750. call assert_equal(0, col('x'))
  1751. call assert_equal(0, col([2, '$']))
  1752. call assert_equal(0, col([1, 100]))
  1753. call assert_equal(0, col([1]))
  1754. call assert_equal(0, col(v:_null_list))
  1755. call assert_fails('let c = col({})', 'E1222:')
  1756. call assert_fails('let c = col(".", [])', 'E1210:')
  1757. " test for getting the visual start column
  1758. func T()
  1759. let g:Vcol = col('v')
  1760. return ''
  1761. endfunc
  1762. let g:Vcol = 0
  1763. xmap <expr> <F2> T()
  1764. exe "normal gg3|ve\<F2>"
  1765. call assert_equal(3, g:Vcol)
  1766. xunmap <F2>
  1767. delfunc T
  1768. " Test for the visual line start and end marks '< and '>
  1769. call setline(1, ['one', 'one two', 'one two three'])
  1770. "normal! ggVG
  1771. call feedkeys("ggVG\<Esc>", 'xt')
  1772. call assert_equal(1, col("'<"))
  1773. call assert_equal(14, col("'>"))
  1774. " Delete the last line of the visually selected region
  1775. $d
  1776. call assert_notequal(14, col("'>"))
  1777. " Test with 'virtualedit'
  1778. set virtualedit=all
  1779. call cursor(1, 10)
  1780. call assert_equal(4, col('.'))
  1781. set virtualedit&
  1782. " Test for getting the column number in another window
  1783. let winid = win_getid()
  1784. new
  1785. call win_execute(winid, 'normal 1G$')
  1786. call assert_equal(3, col('.', winid))
  1787. call win_execute(winid, 'normal 2G')
  1788. call assert_equal(8, col('$', winid))
  1789. call assert_equal(0, col('.', 5001))
  1790. bw!
  1791. endfunc
  1792. " Test for input()
  1793. func Test_input_func()
  1794. " Test for prompt with multiple lines
  1795. redir => v
  1796. call feedkeys(":let c = input(\"A\\nB\\nC\\n? \")\<CR>B\<CR>", 'xt')
  1797. redir END
  1798. call assert_equal("B", c)
  1799. call assert_equal(['A', 'B', 'C'], split(v, "\n"))
  1800. " Test for default value
  1801. call feedkeys(":let c = input('color? ', 'red')\<CR>\<CR>", 'xt')
  1802. call assert_equal('red', c)
  1803. " Test for completion at the input prompt
  1804. func! Tcomplete(arglead, cmdline, pos)
  1805. return "item1\nitem2\nitem3"
  1806. endfunc
  1807. call feedkeys(":let c = input('Q? ', '', 'custom,Tcomplete')\<CR>"
  1808. \ .. "\<C-A>\<CR>", 'xt')
  1809. delfunc Tcomplete
  1810. call assert_equal('item1 item2 item3', c)
  1811. " Test for using special characters as default input
  1812. call feedkeys(":let c = input('name? ', \"x\\<BS>y\")\<CR>\<CR>", 'xt')
  1813. call assert_equal('y', c)
  1814. " Test for using text with composing characters as default input
  1815. call feedkeys(":let c = input('name? ', \"ã̳\")\<CR>\<CR>", 'xt')
  1816. call assert_equal('ã̳', c)
  1817. " Test for using <CR> as default input
  1818. call feedkeys(":let c = input('name? ', \"\\<CR>\")\<CR>x\<CR>", 'xt')
  1819. call assert_equal(' x', c)
  1820. call assert_fails("call input('F:', '', 'invalid')", 'E180:')
  1821. call assert_fails("call input('F:', '', [])", 'E730:')
  1822. endfunc
  1823. " Test for the inputdialog() function
  1824. func Test_inputdialog()
  1825. set timeout timeoutlen=10
  1826. if has('gui_running')
  1827. call assert_fails('let v=inputdialog([], "xx")', 'E730:')
  1828. call assert_fails('let v=inputdialog("Q", [])', 'E730:')
  1829. else
  1830. call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<CR>", 'xt')
  1831. call assert_equal('xx', v)
  1832. call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<Esc>", 'xt')
  1833. call assert_equal('yy', v)
  1834. endif
  1835. set timeout& timeoutlen&
  1836. endfunc
  1837. " Test for inputlist()
  1838. func Test_inputlist()
  1839. call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<cr>", 'tx')
  1840. call assert_equal(1, c)
  1841. call feedkeys(":let c = ['Select color:', '1. red', '2. green', '3. blue']->inputlist()\<cr>2\<cr>", 'tx')
  1842. call assert_equal(2, c)
  1843. call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>3\<cr>", 'tx')
  1844. call assert_equal(3, c)
  1845. " CR to cancel
  1846. call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<cr>", 'tx')
  1847. call assert_equal(0, c)
  1848. " Esc to cancel
  1849. call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<Esc>", 'tx')
  1850. call assert_equal(0, c)
  1851. " q to cancel
  1852. call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>q", 'tx')
  1853. call assert_equal(0, c)
  1854. " Cancel after inputting a number
  1855. call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>5q", 'tx')
  1856. call assert_equal(0, c)
  1857. " Use backspace to delete characters in the prompt
  1858. call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<BS>3\<BS>2\<cr>", 'tx')
  1859. call assert_equal(2, c)
  1860. " Use mouse to make a selection
  1861. call Ntest_setmouse(&lines - 3, 2)
  1862. call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
  1863. call assert_equal(1, c)
  1864. " Mouse click outside of the list
  1865. call Ntest_setmouse(&lines - 6, 2)
  1866. call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx')
  1867. call assert_equal(-2, c)
  1868. call assert_fails('call inputlist("")', 'E686:')
  1869. " Nvim accepts null list as empty list
  1870. " call assert_fails('call inputlist(v:_null_list)', 'E686:')
  1871. endfunc
  1872. func Test_range_inputlist()
  1873. " flush out any garbage left in the buffer
  1874. while getchar(0)
  1875. endwhile
  1876. call feedkeys(":let result = inputlist(range(10))\<CR>1\<CR>", 'x')
  1877. call assert_equal(1, result)
  1878. call feedkeys(":let result = inputlist(range(3, 10))\<CR>1\<CR>", 'x')
  1879. call assert_equal(1, result)
  1880. unlet result
  1881. endfunc
  1882. func Test_balloon_show()
  1883. CheckFeature balloon_eval
  1884. " This won't do anything but must not crash either.
  1885. call balloon_show('hi!')
  1886. if !has('gui_running')
  1887. call balloon_show(range(3))
  1888. call balloon_show([])
  1889. endif
  1890. endfunc
  1891. func Test_setbufvar_options()
  1892. " This tests that aucmd_prepbuf() and aucmd_restbuf() properly restore the
  1893. " window layout and cursor position.
  1894. call assert_equal(1, winnr('$'))
  1895. split dummy_preview
  1896. resize 2
  1897. set winfixheight winfixwidth
  1898. let prev_id = win_getid()
  1899. wincmd j
  1900. let wh = winheight(0)
  1901. let dummy_buf = bufnr('dummy_buf1', v:true)
  1902. call setbufvar(dummy_buf, '&buftype', 'nofile')
  1903. execute 'belowright vertical split #' . dummy_buf
  1904. call assert_equal(wh, winheight(0))
  1905. let dum1_id = win_getid()
  1906. call setline(1, 'foo')
  1907. normal! V$
  1908. call assert_equal(4, col('.'))
  1909. call setbufvar('dummy_preview', '&buftype', 'nofile')
  1910. call assert_equal(4, col('.'))
  1911. wincmd h
  1912. let wh = winheight(0)
  1913. call setline(1, 'foo')
  1914. normal! V$
  1915. call assert_equal(4, col('.'))
  1916. let dummy_buf = bufnr('dummy_buf2', v:true)
  1917. eval 'nofile'->setbufvar(dummy_buf, '&buftype')
  1918. call assert_equal(4, col('.'))
  1919. execute 'belowright vertical split #' . dummy_buf
  1920. call assert_equal(wh, winheight(0))
  1921. bwipe!
  1922. call win_gotoid(prev_id)
  1923. bwipe!
  1924. call win_gotoid(dum1_id)
  1925. bwipe!
  1926. endfunc
  1927. func Test_setbufvar_keep_window_title()
  1928. CheckRunVimInTerminal
  1929. if !has('title') || empty(&t_ts)
  1930. throw "Skipped: can't get/set title"
  1931. endif
  1932. let lines =<< trim END
  1933. set title
  1934. edit Xa.txt
  1935. let g:buf = bufadd('Xb.txt')
  1936. inoremap <F2> <C-R>=setbufvar(g:buf, '&autoindent', 1) ?? ''<CR>
  1937. END
  1938. call writefile(lines, 'Xsetbufvar')
  1939. let buf = RunVimInTerminal('-S Xsetbufvar', {})
  1940. call WaitForAssert({-> assert_match('Xa.txt', term_gettitle(buf))}, 1000)
  1941. call term_sendkeys(buf, "i\<F2>")
  1942. call TermWait(buf)
  1943. call term_sendkeys(buf, "\<Esc>")
  1944. call TermWait(buf)
  1945. call assert_match('Xa.txt', term_gettitle(buf))
  1946. call StopVimInTerminal(buf)
  1947. call delete('Xsetbufvar')
  1948. endfunc
  1949. func Test_redo_in_nested_functions()
  1950. nnoremap g. :set opfunc=Operator<CR>g@
  1951. function Operator( type, ... )
  1952. let @x = 'XXX'
  1953. execute 'normal! g`[' . (a:type ==# 'line' ? 'V' : 'v') . 'g`]' . '"xp'
  1954. endfunction
  1955. function! Apply()
  1956. 5,6normal! .
  1957. endfunction
  1958. new
  1959. call setline(1, repeat(['some "quoted" text', 'more "quoted" text'], 3))
  1960. 1normal g.i"
  1961. call assert_equal('some "XXX" text', getline(1))
  1962. 3,4normal .
  1963. call assert_equal('some "XXX" text', getline(3))
  1964. call assert_equal('more "XXX" text', getline(4))
  1965. call Apply()
  1966. call assert_equal('some "XXX" text', getline(5))
  1967. call assert_equal('more "XXX" text', getline(6))
  1968. bwipe!
  1969. nunmap g.
  1970. delfunc Operator
  1971. delfunc Apply
  1972. endfunc
  1973. func Test_trim()
  1974. call assert_equal("Testing", trim(" \t\r\r\x0BTesting \t\n\r\n\t\x0B\x0B"))
  1975. call assert_equal("Testing", " \t \r\r\n\n\x0BTesting \t\n\r\n\t\x0B\x0B"->trim())
  1976. call assert_equal("RESERVE", trim("xyz \twwRESERVEzyww \t\t", " wxyz\t"))
  1977. call assert_equal("wRE \tSERVEzyww", trim("wRE \tSERVEzyww"))
  1978. call assert_equal("abcd\t xxxx tail", trim(" \tabcd\t xxxx tail"))
  1979. call assert_equal("\tabcd\t xxxx tail", trim(" \tabcd\t xxxx tail", " "))
  1980. call assert_equal(" \tabcd\t xxxx tail", trim(" \tabcd\t xxxx tail", "abx"))
  1981. call assert_equal("RESERVE", trim("你RESERVE好", "你好"))
  1982. call assert_equal("您R E SER V E早", trim("你好您R E SER V E早好你你", "你好"))
  1983. call assert_equal("你好您R E SER V E早好你你", trim(" \n\r\r 你好您R E SER V E早好你你 \t \x0B", ))
  1984. call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" 你好您R E SER V E早好你你 \t \x0B", " 你好"))
  1985. call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" tteesstttt你好您R E SER V E早好你你 \t \x0B ttestt", " 你好tes"))
  1986. call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" tteesstttt你好您R E SER V E早好你你 \t \x0B ttestt", " 你你你好好好tttsses"))
  1987. call assert_equal("留下", trim("这些些不要这些留下这些", "这些不要"))
  1988. call assert_equal("", trim("", ""))
  1989. call assert_equal("a", trim("a", ""))
  1990. call assert_equal("", trim("", "a"))
  1991. call assert_equal("vim", trim(" vim ", " ", 0))
  1992. call assert_equal("vim ", trim(" vim ", " ", 1))
  1993. call assert_equal(" vim", trim(" vim ", " ", 2))
  1994. call assert_fails('eval trim(" vim ", " ", [])', 'E745:')
  1995. call assert_fails('eval trim(" vim ", " ", -1)', 'E475:')
  1996. call assert_fails('eval trim(" vim ", " ", 3)', 'E475:')
  1997. call assert_fails('eval trim(" vim ", 0)', 'E1174:')
  1998. let chars = join(map(range(1, 0x20) + [0xa0], {n -> n->nr2char()}), '')
  1999. call assert_equal("x", trim(chars . "x" . chars))
  2000. call assert_equal("x", trim(chars . "x" . chars, '', 0))
  2001. call assert_equal("x" . chars, trim(chars . "x" . chars, '', 1))
  2002. call assert_equal(chars . "x", trim(chars . "x" . chars, '', 2))
  2003. call assert_fails('let c=trim([])', 'E730:')
  2004. endfunc
  2005. " Test for reg_recording() and reg_executing()
  2006. func Test_reg_executing_and_recording()
  2007. let s:reg_stat = ''
  2008. func s:save_reg_stat()
  2009. let s:reg_stat = reg_recording() . ':' . reg_executing()
  2010. return ''
  2011. endfunc
  2012. new
  2013. call s:save_reg_stat()
  2014. call assert_equal(':', s:reg_stat)
  2015. call feedkeys("qa\"=s:save_reg_stat()\<CR>pq", 'xt')
  2016. call assert_equal('a:', s:reg_stat)
  2017. call feedkeys("@a", 'xt')
  2018. call assert_equal(':a', s:reg_stat)
  2019. call feedkeys("qb@aq", 'xt')
  2020. call assert_equal('b:a', s:reg_stat)
  2021. call feedkeys("q\"\"=s:save_reg_stat()\<CR>pq", 'xt')
  2022. call assert_equal('":', s:reg_stat)
  2023. " :normal command saves and restores reg_executing
  2024. let s:reg_stat = ''
  2025. let @q = ":call TestFunc()\<CR>:call s:save_reg_stat()\<CR>"
  2026. func TestFunc() abort
  2027. normal! ia
  2028. endfunc
  2029. call feedkeys("@q", 'xt')
  2030. call assert_equal(':q', s:reg_stat)
  2031. delfunc TestFunc
  2032. " getchar() command saves and restores reg_executing
  2033. map W :call TestFunc()<CR>
  2034. let @q = "W"
  2035. let g:typed = ''
  2036. let g:regs = []
  2037. func TestFunc() abort
  2038. let g:regs += [reg_executing()]
  2039. let g:typed = getchar(0)
  2040. let g:regs += [reg_executing()]
  2041. endfunc
  2042. call feedkeys("@qy", 'xt')
  2043. call assert_equal(char2nr("y"), g:typed)
  2044. call assert_equal(['q', 'q'], g:regs)
  2045. delfunc TestFunc
  2046. unmap W
  2047. unlet g:typed
  2048. unlet g:regs
  2049. " input() command saves and restores reg_executing
  2050. map W :call TestFunc()<CR>
  2051. let @q = "W"
  2052. let g:typed = ''
  2053. let g:regs = []
  2054. func TestFunc() abort
  2055. let g:regs += [reg_executing()]
  2056. let g:typed = '?'->input()
  2057. let g:regs += [reg_executing()]
  2058. endfunc
  2059. call feedkeys("@qy\<CR>", 'xt')
  2060. call assert_equal("y", g:typed)
  2061. call assert_equal(['q', 'q'], g:regs)
  2062. delfunc TestFunc
  2063. unmap W
  2064. unlet g:typed
  2065. unlet g:regs
  2066. bwipe!
  2067. delfunc s:save_reg_stat
  2068. unlet s:reg_stat
  2069. endfunc
  2070. func Test_inputsecret()
  2071. map W :call TestFunc()<CR>
  2072. let @q = "W"
  2073. let g:typed1 = ''
  2074. let g:typed2 = ''
  2075. let g:regs = []
  2076. func TestFunc() abort
  2077. let g:typed1 = '?'->inputsecret()
  2078. let g:typed2 = inputsecret('password: ')
  2079. endfunc
  2080. call feedkeys("@qsomething\<CR>else\<CR>", 'xt')
  2081. call assert_equal("something", g:typed1)
  2082. call assert_equal("else", g:typed2)
  2083. delfunc TestFunc
  2084. unmap W
  2085. unlet g:typed1
  2086. unlet g:typed2
  2087. endfunc
  2088. func Test_getchar()
  2089. call feedkeys('a', '')
  2090. call assert_equal(char2nr('a'), getchar())
  2091. call assert_equal(0, getchar(0))
  2092. call assert_equal(0, getchar(1))
  2093. call feedkeys('a', '')
  2094. call assert_equal('a', getcharstr())
  2095. call assert_equal('', getcharstr(0))
  2096. call assert_equal('', getcharstr(1))
  2097. call feedkeys("\<M-F2>", '')
  2098. call assert_equal("\<M-F2>", getchar(0))
  2099. call assert_equal(0, getchar(0))
  2100. call feedkeys("\<Tab>", '')
  2101. call assert_equal(char2nr("\<Tab>"), getchar())
  2102. call feedkeys("\<Tab>", '')
  2103. call assert_equal(char2nr("\<Tab>"), getchar(-1))
  2104. call feedkeys("\<Tab>", '')
  2105. call assert_equal(char2nr("\<Tab>"), getchar(-1, {}))
  2106. call feedkeys("\<Tab>", '')
  2107. call assert_equal(char2nr("\<Tab>"), getchar(-1, #{number: v:true}))
  2108. call assert_equal(0, getchar(0))
  2109. call assert_equal(0, getchar(1))
  2110. call assert_equal(0, getchar(0, #{number: v:true}))
  2111. call assert_equal(0, getchar(1, #{number: v:true}))
  2112. call feedkeys("\<Tab>", '')
  2113. call assert_equal("\<Tab>", getcharstr())
  2114. call feedkeys("\<Tab>", '')
  2115. call assert_equal("\<Tab>", getcharstr(-1))
  2116. call feedkeys("\<Tab>", '')
  2117. call assert_equal("\<Tab>", getcharstr(-1, {}))
  2118. call feedkeys("\<Tab>", '')
  2119. call assert_equal("\<Tab>", getchar(-1, #{number: v:false}))
  2120. call assert_equal('', getcharstr(0))
  2121. call assert_equal('', getcharstr(1))
  2122. call assert_equal('', getchar(0, #{number: v:false}))
  2123. call assert_equal('', getchar(1, #{number: v:false}))
  2124. " Nvim: <M-x> is never simplified
  2125. " for key in ["C-I", "C-X", "M-x"]
  2126. for key in ["C-I", "C-X"]
  2127. let lines =<< eval trim END
  2128. call feedkeys("\<*{key}>", '')
  2129. call assert_equal(char2nr("\<{key}>"), getchar())
  2130. call feedkeys("\<*{key}>", '')
  2131. call assert_equal(char2nr("\<{key}>"), getchar(-1))
  2132. call feedkeys("\<*{key}>", '')
  2133. call assert_equal(char2nr("\<{key}>"), getchar(-1, {{}}))
  2134. call feedkeys("\<*{key}>", '')
  2135. call assert_equal(char2nr("\<{key}>"), getchar(-1, {{'number': 1}}))
  2136. call feedkeys("\<*{key}>", '')
  2137. call assert_equal(char2nr("\<{key}>"), getchar(-1, {{'simplify': 1}}))
  2138. call feedkeys("\<*{key}>", '')
  2139. call assert_equal("\<*{key}>", getchar(-1, {{'simplify': v:false}}))
  2140. call assert_equal(0, getchar(0))
  2141. call assert_equal(0, getchar(1))
  2142. END
  2143. call CheckLegacyAndVim9Success(lines)
  2144. let lines =<< eval trim END
  2145. call feedkeys("\<*{key}>", '')
  2146. call assert_equal("\<{key}>", getcharstr())
  2147. call feedkeys("\<*{key}>", '')
  2148. call assert_equal("\<{key}>", getcharstr(-1))
  2149. call feedkeys("\<*{key}>", '')
  2150. call assert_equal("\<{key}>", getcharstr(-1, {{}}))
  2151. call feedkeys("\<*{key}>", '')
  2152. call assert_equal("\<{key}>", getchar(-1, {{'number': 0}}))
  2153. call feedkeys("\<*{key}>", '')
  2154. call assert_equal("\<{key}>", getcharstr(-1, {{'simplify': 1}}))
  2155. call feedkeys("\<*{key}>", '')
  2156. call assert_equal("\<*{key}>", getcharstr(-1, {{'simplify': v:false}}))
  2157. call assert_equal('', getcharstr(0))
  2158. call assert_equal('', getcharstr(1))
  2159. END
  2160. call CheckLegacyAndVim9Success(lines)
  2161. endfor
  2162. call assert_fails('call getchar(1, 1)', 'E1206:')
  2163. call assert_fails('call getcharstr(1, 1)', 'E1206:')
  2164. call assert_fails('call getchar(1, #{cursor: "foo"})', 'E475:')
  2165. call assert_fails('call getcharstr(1, #{cursor: "foo"})', 'E475:')
  2166. call assert_fails('call getchar(1, #{cursor: 0z})', 'E976:')
  2167. call assert_fails('call getcharstr(1, #{cursor: 0z})', 'E976:')
  2168. call assert_fails('call getchar(1, #{simplify: 0z})', 'E974:')
  2169. call assert_fails('call getcharstr(1, #{simplify: 0z})', 'E974:')
  2170. call assert_fails('call getchar(1, #{number: []})', 'E745:')
  2171. call assert_fails('call getchar(1, #{number: {}})', 'E728:')
  2172. call assert_fails('call getcharstr(1, #{number: v:true})', 'E475:')
  2173. call assert_fails('call getcharstr(1, #{number: v:false})', 'E475:')
  2174. call setline(1, 'xxxx')
  2175. call Ntest_setmouse(1, 3)
  2176. let v:mouse_win = 9
  2177. let v:mouse_winid = 9
  2178. let v:mouse_lnum = 9
  2179. let v:mouse_col = 9
  2180. call feedkeys("\<S-LeftMouse>", '')
  2181. call assert_equal("\<S-LeftMouse>", getchar())
  2182. call assert_equal(1, v:mouse_win)
  2183. call assert_equal(win_getid(1), v:mouse_winid)
  2184. call assert_equal(1, v:mouse_lnum)
  2185. call assert_equal(3, v:mouse_col)
  2186. enew!
  2187. endfunc
  2188. func Test_getchar_cursor_position()
  2189. CheckRunVimInTerminal
  2190. let lines =<< trim END
  2191. call setline(1, ['foobar', 'foobar', 'foobar'])
  2192. call cursor(3, 6)
  2193. nnoremap <F1> <Cmd>echo 1234<Bar>call getchar()<CR>
  2194. nnoremap <F2> <Cmd>call getchar()<CR>
  2195. nnoremap <F3> <Cmd>call getchar(-1, {})<CR>
  2196. nnoremap <F4> <Cmd>call getchar(-1, #{cursor: 'msg'})<CR>
  2197. nnoremap <F5> <Cmd>call getchar(-1, #{cursor: 'keep'})<CR>
  2198. nnoremap <F6> <Cmd>call getchar(-1, #{cursor: 'hide'})<CR>
  2199. END
  2200. call writefile(lines, 'XgetcharCursorPos', 'D')
  2201. let buf = RunVimInTerminal('-S XgetcharCursorPos', {'rows': 6})
  2202. call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
  2203. call term_sendkeys(buf, "\<F1>")
  2204. call WaitForAssert({-> assert_equal([6, 5], term_getcursor(buf)[0:1])})
  2205. call assert_true(term_getcursor(buf)[2].visible)
  2206. call term_sendkeys(buf, 'a')
  2207. call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
  2208. call assert_true(term_getcursor(buf)[2].visible)
  2209. for key in ["\<F2>", "\<F3>", "\<F4>"]
  2210. call term_sendkeys(buf, key)
  2211. call WaitForAssert({-> assert_equal([6, 1], term_getcursor(buf)[0:1])})
  2212. call assert_true(term_getcursor(buf)[2].visible)
  2213. call term_sendkeys(buf, 'a')
  2214. call WaitForAssert({-> assert_equal([3, 6], term_getcursor(buf)[0:1])})
  2215. call assert_true(term_getcursor(buf)[2].visible)
  2216. endfor
  2217. call term_sendkeys(buf, "\<F5>")
  2218. call TermWait(buf, 50)
  2219. call assert_equal([3, 6], term_getcursor(buf)[0:1])
  2220. call assert_true(term_getcursor(buf)[2].visible)
  2221. call term_sendkeys(buf, 'a')
  2222. call TermWait(buf, 50)
  2223. call assert_equal([3, 6], term_getcursor(buf)[0:1])
  2224. call assert_true(term_getcursor(buf)[2].visible)
  2225. call term_sendkeys(buf, "\<F6>")
  2226. call WaitForAssert({-> assert_false(term_getcursor(buf)[2].visible)})
  2227. call term_sendkeys(buf, 'a')
  2228. call WaitForAssert({-> assert_true(term_getcursor(buf)[2].visible)})
  2229. call assert_equal([3, 6], term_getcursor(buf)[0:1])
  2230. call StopVimInTerminal(buf)
  2231. endfunc
  2232. func Test_libcall_libcallnr()
  2233. CheckFeature libcall
  2234. if has('win32')
  2235. let libc = 'msvcrt.dll'
  2236. elseif has('mac')
  2237. let libc = 'libSystem.B.dylib'
  2238. elseif executable('ldd')
  2239. let libc = matchstr(split(system('ldd ' . GetVimProg())), '/libc\.so\>')
  2240. endif
  2241. if get(l:, 'libc', '') ==# ''
  2242. " On Unix, libc.so can be in various places.
  2243. if has('linux')
  2244. " There is not documented but regarding the 1st argument of glibc's
  2245. " dlopen an empty string and nullptr are equivalent, so using an empty
  2246. " string for the 1st argument of libcall allows to call functions.
  2247. let libc = ''
  2248. elseif has('sun')
  2249. " Set the path to libc.so according to the architecture.
  2250. let test_bits = system('file ' . GetVimProg())
  2251. let test_arch = system('uname -p')
  2252. if test_bits =~ '64-bit' && test_arch =~ 'sparc'
  2253. let libc = '/usr/lib/sparcv9/libc.so'
  2254. elseif test_bits =~ '64-bit' && test_arch =~ 'i386'
  2255. let libc = '/usr/lib/amd64/libc.so'
  2256. else
  2257. let libc = '/usr/lib/libc.so'
  2258. endif
  2259. else
  2260. " Unfortunately skip this test until a good way is found.
  2261. return
  2262. endif
  2263. endif
  2264. if has('win32')
  2265. call assert_equal($USERPROFILE, 'USERPROFILE'->libcall(libc, 'getenv'))
  2266. else
  2267. call assert_equal($HOME, 'HOME'->libcall(libc, 'getenv'))
  2268. endif
  2269. " If function returns NULL, libcall() should return an empty string.
  2270. call assert_equal('', libcall(libc, 'getenv', 'X_ENV_DOES_NOT_EXIT'))
  2271. " Test libcallnr() with string and integer argument.
  2272. call assert_equal(4, 'abcd'->libcallnr(libc, 'strlen'))
  2273. call assert_equal(char2nr('A'), char2nr('a')->libcallnr(libc, 'toupper'))
  2274. call assert_fails("call libcall(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
  2275. call assert_fails("call libcallnr(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
  2276. call assert_fails("call libcall('Xdoesnotexist_', 'getenv', 'HOME')", ['', 'E364:'])
  2277. call assert_fails("call libcallnr('Xdoesnotexist_', 'strlen', 'abcd')", ['', 'E364:'])
  2278. endfunc
  2279. sandbox function Fsandbox()
  2280. normal ix
  2281. endfunc
  2282. func Test_func_sandbox()
  2283. sandbox let F = {-> 'hello'}
  2284. call assert_equal('hello', F())
  2285. sandbox let F = {-> "normal ix\<Esc>"->execute()}
  2286. call assert_fails('call F()', 'E48:')
  2287. unlet F
  2288. call assert_fails('call Fsandbox()', 'E48:')
  2289. delfunc Fsandbox
  2290. " From a sandbox try to set a predefined variable (which cannot be modified
  2291. " from a sandbox)
  2292. call assert_fails('sandbox let v:lnum = 10', 'E794:')
  2293. endfunc
  2294. func EditAnotherFile()
  2295. let word = expand('<cword>')
  2296. edit Xfuncrange2
  2297. endfunc
  2298. func Test_func_range_with_edit()
  2299. " Define a function that edits another buffer, then call it with a range that
  2300. " is invalid in that buffer.
  2301. call writefile(['just one line'], 'Xfuncrange2')
  2302. new
  2303. eval 10->range()->setline(1)
  2304. write Xfuncrange1
  2305. call assert_fails('5,8call EditAnotherFile()', 'E16:')
  2306. call delete('Xfuncrange1')
  2307. call delete('Xfuncrange2')
  2308. bwipe!
  2309. endfunc
  2310. func Test_func_exists_on_reload()
  2311. call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists')
  2312. call assert_equal(0, exists('*ExistingFunction'))
  2313. source Xfuncexists
  2314. call assert_equal(1, '*ExistingFunction'->exists())
  2315. " Redefining a function when reloading a script is OK.
  2316. source Xfuncexists
  2317. call assert_equal(1, exists('*ExistingFunction'))
  2318. " But redefining in another script is not OK.
  2319. call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists2')
  2320. call assert_fails('source Xfuncexists2', 'E122:')
  2321. delfunc ExistingFunction
  2322. call assert_equal(0, exists('*ExistingFunction'))
  2323. call writefile([
  2324. \ 'func ExistingFunction()', 'echo "yes"', 'endfunc',
  2325. \ 'func ExistingFunction()', 'echo "no"', 'endfunc',
  2326. \ ], 'Xfuncexists')
  2327. call assert_fails('source Xfuncexists', 'E122:')
  2328. call assert_equal(1, exists('*ExistingFunction'))
  2329. call delete('Xfuncexists2')
  2330. call delete('Xfuncexists')
  2331. delfunc ExistingFunction
  2332. endfunc
  2333. " Test confirm({msg} [, {choices} [, {default} [, {type}]]])
  2334. func Test_confirm()
  2335. CheckUnix
  2336. CheckNotGui
  2337. call feedkeys('o', 'L')
  2338. let a = confirm('Press O to proceed')
  2339. call assert_equal(1, a)
  2340. call feedkeys('y', 'L')
  2341. let a = 'Are you sure?'->confirm("&Yes\n&No")
  2342. call assert_equal(1, a)
  2343. call feedkeys('n', 'L')
  2344. let a = confirm('Are you sure?', "&Yes\n&No")
  2345. call assert_equal(2, a)
  2346. " confirm() should return 0 when pressing CTRL-C.
  2347. call feedkeys("\<C-C>", 'L')
  2348. let a = confirm('Are you sure?', "&Yes\n&No")
  2349. call assert_equal(0, a)
  2350. " <Esc> requires another character to avoid it being seen as the start of an
  2351. " escape sequence. Zero should be harmless.
  2352. eval "\<Esc>0"->feedkeys('L')
  2353. let a = confirm('Are you sure?', "&Yes\n&No")
  2354. call assert_equal(0, a)
  2355. " Default choice is returned when pressing <CR>.
  2356. call feedkeys("\<CR>", 'L')
  2357. let a = confirm('Are you sure?', "&Yes\n&No")
  2358. call assert_equal(1, a)
  2359. call feedkeys("\<CR>", 'L')
  2360. let a = confirm('Are you sure?', "&Yes\n&No", 2)
  2361. call assert_equal(2, a)
  2362. call feedkeys("\<CR>", 'L')
  2363. let a = confirm('Are you sure?', "&Yes\n&No", 0)
  2364. call assert_equal(0, a)
  2365. " Test with the {type} 4th argument
  2366. for type in ['Error', 'Question', 'Info', 'Warning', 'Generic']
  2367. call feedkeys('y', 'L')
  2368. let a = confirm('Are you sure?', "&Yes\n&No\n", 1, type)
  2369. call assert_equal(1, a)
  2370. endfor
  2371. call assert_fails('call confirm([])', 'E730:')
  2372. call assert_fails('call confirm("Are you sure?", [])', 'E730:')
  2373. call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", [])', 'E745:')
  2374. call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", 0, [])', 'E730:')
  2375. endfunc
  2376. func Test_platform_name()
  2377. " The system matches at most only one name.
  2378. let names = ['amiga', 'bsd', 'hpux', 'linux', 'mac', 'qnx', 'sun', 'vms', 'win32', 'win32unix']
  2379. call assert_inrange(0, 1, len(filter(copy(names), 'has(v:val)')))
  2380. " Is Unix?
  2381. call assert_equal(has('bsd'), has('bsd') && has('unix'))
  2382. call assert_equal(has('hpux'), has('hpux') && has('unix'))
  2383. call assert_equal(has('hurd'), has('hurd') && has('unix'))
  2384. call assert_equal(has('linux'), has('linux') && has('unix'))
  2385. call assert_equal(has('mac'), has('mac') && has('unix'))
  2386. call assert_equal(has('qnx'), has('qnx') && has('unix'))
  2387. call assert_equal(has('sun'), has('sun') && has('unix'))
  2388. call assert_equal(has('win32'), has('win32') && !has('unix'))
  2389. call assert_equal(has('win32unix'), has('win32unix') && has('unix'))
  2390. if has('unix') && executable('uname')
  2391. let uname = system('uname')
  2392. " GNU userland on BSD kernels (e.g., GNU/kFreeBSD) don't have BSD defined
  2393. call assert_equal(uname =~? '\%(GNU/k\w\+\)\@<!BSD\|DragonFly', has('bsd'))
  2394. call assert_equal(uname =~? 'HP-UX', has('hpux'))
  2395. call assert_equal(uname =~? 'Linux', has('linux'))
  2396. call assert_equal(uname =~? 'Darwin', has('mac'))
  2397. call assert_equal(uname =~? 'QNX', has('qnx'))
  2398. call assert_equal(uname =~? 'SunOS', has('sun'))
  2399. call assert_equal(uname =~? 'CYGWIN\|MSYS', has('win32unix'))
  2400. call assert_equal(uname =~? 'GNU', has('hurd'))
  2401. endif
  2402. endfunc
  2403. func Test_readdir()
  2404. call mkdir('Xdir')
  2405. call writefile([], 'Xdir/foo.txt')
  2406. call writefile([], 'Xdir/bar.txt')
  2407. call mkdir('Xdir/dir')
  2408. " All results
  2409. let files = readdir('Xdir')
  2410. call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
  2411. " Only results containing "f"
  2412. let files = 'Xdir'->readdir({ x -> stridx(x, 'f') !=- 1 })
  2413. call assert_equal(['foo.txt'], sort(files))
  2414. " Only .txt files
  2415. let files = readdir('Xdir', { x -> x =~ '.txt$' })
  2416. call assert_equal(['bar.txt', 'foo.txt'], sort(files))
  2417. " Only .txt files with string
  2418. let files = readdir('Xdir', 'v:val =~ ".txt$"')
  2419. call assert_equal(['bar.txt', 'foo.txt'], sort(files))
  2420. " Limit to 1 result.
  2421. let l = []
  2422. let files = readdir('Xdir', {x -> len(add(l, x)) == 2 ? -1 : 1})
  2423. call assert_equal(1, len(files))
  2424. " Nested readdir() must not crash
  2425. let files = readdir('Xdir', 'readdir("Xdir", "1") != []')
  2426. call sort(files)->assert_equal(['bar.txt', 'dir', 'foo.txt'])
  2427. eval 'Xdir'->delete('rf')
  2428. endfunc
  2429. func Test_delete_rf()
  2430. call mkdir('Xdir')
  2431. call writefile([], 'Xdir/foo.txt')
  2432. call writefile([], 'Xdir/bar.txt')
  2433. call mkdir('Xdir/[a-1]') " issue #696
  2434. call writefile([], 'Xdir/[a-1]/foo.txt')
  2435. call writefile([], 'Xdir/[a-1]/bar.txt')
  2436. call assert_true(filereadable('Xdir/foo.txt'))
  2437. call assert_true('Xdir/[a-1]/foo.txt'->filereadable())
  2438. call assert_equal(0, delete('Xdir', 'rf'))
  2439. call assert_false(filereadable('Xdir/foo.txt'))
  2440. call assert_false(filereadable('Xdir/[a-1]/foo.txt'))
  2441. if has('unix')
  2442. call mkdir('Xdir/Xdir2', 'p')
  2443. silent !chmod 555 Xdir
  2444. call assert_equal(-1, delete('Xdir/Xdir2', 'rf'))
  2445. call assert_equal(-1, delete('Xdir', 'rf'))
  2446. silent !chmod 755 Xdir
  2447. call assert_equal(0, delete('Xdir', 'rf'))
  2448. endif
  2449. endfunc
  2450. func Test_call()
  2451. call assert_equal(3, call('len', [123]))
  2452. call assert_equal(3, 'len'->call([123]))
  2453. call assert_equal(4, call({ x -> len(x) }, ['xxxx']))
  2454. call assert_equal(2, call(function('len'), ['xx']))
  2455. call assert_fails("call call('len', 123)", 'E1211:')
  2456. call assert_equal(0, call('', []))
  2457. call assert_equal(0, call('len', v:_null_list))
  2458. function Mylen() dict
  2459. return len(self.data)
  2460. endfunction
  2461. let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
  2462. eval mydict.len->call([], mydict)->assert_equal(4)
  2463. call assert_fails("call call('Mylen', [], 0)", 'E1206:')
  2464. call assert_fails('call foo', 'E107:')
  2465. " These once caused a crash.
  2466. " Nvim doesn't have null functions
  2467. " call call(test_null_function(), [])
  2468. " Nvim doesn't have null partials
  2469. " call call(test_null_partial(), [])
  2470. " Nvim doesn't have null functions
  2471. " call assert_fails('call test_null_function()()', 'E1192:')
  2472. " Nvim doesn't have null partials
  2473. " call assert_fails('call test_null_partial()()', 'E117:')
  2474. let lines =<< trim END
  2475. let Time = 'localtime'
  2476. call Time()
  2477. END
  2478. call CheckScriptFailure(lines, 'E1085:')
  2479. endfunc
  2480. func Test_char2nr()
  2481. call assert_equal(12354, char2nr('あ', 1))
  2482. call assert_equal(120, 'x'->char2nr())
  2483. " set encoding=latin1
  2484. call assert_equal(120, 'x'->char2nr())
  2485. set encoding=utf-8
  2486. endfunc
  2487. func Test_charclass()
  2488. call assert_equal(0, charclass(' '))
  2489. call assert_equal(1, charclass('.'))
  2490. call assert_equal(2, charclass('x'))
  2491. call assert_equal(3, charclass("\u203c"))
  2492. " this used to crash vim
  2493. call assert_equal(0, "xxx"[-1]->charclass())
  2494. endfunc
  2495. func Test_eventhandler()
  2496. call assert_equal(0, eventhandler())
  2497. endfunc
  2498. func Test_bufadd_bufload()
  2499. call assert_equal(0, bufexists('someName'))
  2500. let buf = bufadd('someName')
  2501. call assert_notequal(0, buf)
  2502. call assert_equal(1, bufexists('someName'))
  2503. call assert_equal(0, getbufvar(buf, '&buflisted'))
  2504. call assert_equal(0, bufloaded(buf))
  2505. call bufload(buf)
  2506. call assert_equal(1, bufloaded(buf))
  2507. call assert_equal([''], getbufline(buf, 1, '$'))
  2508. let curbuf = bufnr('')
  2509. eval ['some', 'text']->writefile('XotherName')
  2510. let buf = 'XotherName'->bufadd()
  2511. call assert_notequal(0, buf)
  2512. eval 'XotherName'->bufexists()->assert_equal(1)
  2513. call assert_equal(0, getbufvar(buf, '&buflisted'))
  2514. call assert_equal(0, bufloaded(buf))
  2515. eval buf->bufload()
  2516. call assert_equal(1, bufloaded(buf))
  2517. call assert_equal(['some', 'text'], getbufline(buf, 1, '$'))
  2518. call assert_equal(curbuf, bufnr(''))
  2519. let buf1 = bufadd('')
  2520. let buf2 = bufadd('')
  2521. call assert_notequal(0, buf1)
  2522. call assert_notequal(0, buf2)
  2523. call assert_notequal(buf1, buf2)
  2524. call assert_equal(1, bufexists(buf1))
  2525. call assert_equal(1, bufexists(buf2))
  2526. call assert_equal(0, bufloaded(buf1))
  2527. exe 'bwipe ' .. buf1
  2528. call assert_equal(0, bufexists(buf1))
  2529. call assert_equal(1, bufexists(buf2))
  2530. exe 'bwipe ' .. buf2
  2531. call assert_equal(0, bufexists(buf2))
  2532. " When 'buftype' is "nofile" then bufload() does not read the file.
  2533. " Other values too.
  2534. for val in [['nofile', 0],
  2535. \ ['nowrite', 1],
  2536. \ ['acwrite', 1],
  2537. \ ['quickfix', 0],
  2538. \ ['help', 1],
  2539. "\ ['terminal', 0],
  2540. \ ['prompt', 0],
  2541. "\ ['popup', 0],
  2542. \ ]
  2543. bwipe! XotherName
  2544. let buf = bufadd('XotherName')
  2545. call setbufvar(buf, '&bt', val[0])
  2546. call bufload(buf)
  2547. call assert_equal(val[1] ? ['some', 'text'] : [''], getbufline(buf, 1, '$'), val[0])
  2548. endfor
  2549. bwipe someName
  2550. bwipe XotherName
  2551. call assert_equal(0, bufexists('someName'))
  2552. call delete('XotherName')
  2553. endfunc
  2554. func Test_state()
  2555. CheckRunVimInTerminal
  2556. let getstate = ":echo 'state: ' .. g:state .. '; mode: ' .. g:mode\<CR>"
  2557. let lines =<< trim END
  2558. call setline(1, ['one', 'two', 'three'])
  2559. map ;; gg
  2560. set complete=.
  2561. func RunTimer()
  2562. call timer_start(10, {id -> execute('let g:state = state()') .. execute('let g:mode = mode()')})
  2563. endfunc
  2564. au Filetype foobar let g:state = state()|let g:mode = mode()
  2565. END
  2566. call writefile(lines, 'XState')
  2567. let buf = RunVimInTerminal('-S XState', #{rows: 6})
  2568. " Using a ":" command Vim is busy, thus "S" is returned
  2569. call term_sendkeys(buf, ":echo 'state: ' .. state() .. '; mode: ' .. mode()\<CR>")
  2570. call WaitForAssert({-> assert_match('state: S; mode: n', term_getline(buf, 6))}, 1000)
  2571. call term_sendkeys(buf, ":\<CR>")
  2572. " Using a timer callback
  2573. call term_sendkeys(buf, ":call RunTimer()\<CR>")
  2574. call TermWait(buf, 25)
  2575. call term_sendkeys(buf, getstate)
  2576. call WaitForAssert({-> assert_match('state: c; mode: n', term_getline(buf, 6))}, 1000)
  2577. " Halfway a mapping
  2578. call term_sendkeys(buf, ":call RunTimer()\<CR>;")
  2579. call TermWait(buf, 25)
  2580. call term_sendkeys(buf, ";")
  2581. call term_sendkeys(buf, getstate)
  2582. call WaitForAssert({-> assert_match('state: mSc; mode: n', term_getline(buf, 6))}, 1000)
  2583. " An operator is pending
  2584. call term_sendkeys(buf, ":call RunTimer()\<CR>y")
  2585. call TermWait(buf, 25)
  2586. call term_sendkeys(buf, "y")
  2587. call term_sendkeys(buf, getstate)
  2588. call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
  2589. " A register was specified
  2590. call term_sendkeys(buf, ":call RunTimer()\<CR>\"r")
  2591. call TermWait(buf, 25)
  2592. call term_sendkeys(buf, "yy")
  2593. call term_sendkeys(buf, getstate)
  2594. call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
  2595. " Insert mode completion (bit slower on Mac)
  2596. call term_sendkeys(buf, ":call RunTimer()\<CR>Got\<C-N>")
  2597. call TermWait(buf, 25)
  2598. call term_sendkeys(buf, "\<Esc>")
  2599. call term_sendkeys(buf, getstate)
  2600. call WaitForAssert({-> assert_match('state: aSc; mode: i', term_getline(buf, 6))}, 1000)
  2601. " Autocommand executing
  2602. call term_sendkeys(buf, ":set filetype=foobar\<CR>")
  2603. call TermWait(buf, 25)
  2604. call term_sendkeys(buf, getstate)
  2605. call WaitForAssert({-> assert_match('state: xS; mode: n', term_getline(buf, 6))}, 1000)
  2606. " Todo: "w" - waiting for ch_evalexpr()
  2607. " messages scrolled
  2608. call term_sendkeys(buf, ":call RunTimer()\<CR>:echo \"one\\ntwo\\nthree\"\<CR>")
  2609. call TermWait(buf, 25)
  2610. call term_sendkeys(buf, "\<CR>")
  2611. call term_sendkeys(buf, getstate)
  2612. call WaitForAssert({-> assert_match('state: Scs; mode: r', term_getline(buf, 6))}, 1000)
  2613. call StopVimInTerminal(buf)
  2614. call delete('XState')
  2615. endfunc
  2616. func Test_range()
  2617. " destructuring
  2618. let [x, y] = range(2)
  2619. call assert_equal([0, 1], [x, y])
  2620. " index
  2621. call assert_equal(4, range(1, 10)[3])
  2622. " add()
  2623. call assert_equal([0, 1, 2, 3], add(range(3), 3))
  2624. call assert_equal([0, 1, 2, [0, 1, 2]], add([0, 1, 2], range(3)))
  2625. call assert_equal([0, 1, 2, [0, 1, 2]], add(range(3), range(3)))
  2626. " append()
  2627. new
  2628. call append('.', range(5))
  2629. call assert_equal(['', '0', '1', '2', '3', '4'], getline(1, '$'))
  2630. bwipe!
  2631. " appendbufline()
  2632. new
  2633. call appendbufline(bufnr(''), '.', range(5))
  2634. call assert_equal(['0', '1', '2', '3', '4', ''], getline(1, '$'))
  2635. bwipe!
  2636. " call()
  2637. func TwoArgs(a, b)
  2638. return [a:a, a:b]
  2639. endfunc
  2640. call assert_equal([0, 1], call('TwoArgs', range(2)))
  2641. " col()
  2642. new
  2643. call setline(1, ['foo', 'bar'])
  2644. call assert_equal(2, col(range(1, 2)))
  2645. bwipe!
  2646. " complete()
  2647. execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>"
  2648. " complete_info()
  2649. execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>\<C-r>=[complete_info(range(5)), ''][1]\<CR>"
  2650. " copy()
  2651. call assert_equal([1, 2, 3], copy(range(1, 3)))
  2652. " count()
  2653. call assert_equal(0, count(range(0), 3))
  2654. call assert_equal(0, count(range(2), 3))
  2655. call assert_equal(1, count(range(5), 3))
  2656. " cursor()
  2657. new
  2658. call setline(1, ['aaa', 'bbb', 'ccc'])
  2659. call cursor(range(1, 2))
  2660. call assert_equal([2, 1], [col('.'), line('.')])
  2661. bwipe!
  2662. " deepcopy()
  2663. call assert_equal([1, 2, 3], deepcopy(range(1, 3)))
  2664. " empty()
  2665. call assert_true(empty(range(0)))
  2666. call assert_false(empty(range(2)))
  2667. " execute()
  2668. new
  2669. call setline(1, ['aaa', 'bbb', 'ccc'])
  2670. call execute(range(3))
  2671. call assert_equal(2, line('.'))
  2672. bwipe!
  2673. " extend()
  2674. call assert_equal([1, 2, 3, 4], extend([1], range(2, 4)))
  2675. call assert_equal([1, 2, 3, 4], extend(range(1, 1), range(2, 4)))
  2676. call assert_equal([1, 2, 3, 4], extend(range(1, 1), [2, 3, 4]))
  2677. " filter()
  2678. call assert_equal([1, 3], filter(range(5), 'v:val % 2'))
  2679. " funcref()
  2680. call assert_equal([0, 1], funcref('TwoArgs', range(2))())
  2681. " function()
  2682. call assert_equal([0, 1], function('TwoArgs', range(2))())
  2683. " garbagecollect()
  2684. let thelist = [1, range(2), 3]
  2685. let otherlist = range(3)
  2686. call test_garbagecollect_now()
  2687. " get()
  2688. call assert_equal(4, get(range(1, 10), 3))
  2689. call assert_equal(-1, get(range(1, 10), 42, -1))
  2690. " index()
  2691. call assert_equal(1, index(range(1, 5), 2))
  2692. call assert_fails("echo index([1, 2], 1, [])", 'E745:')
  2693. " insert()
  2694. call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42))
  2695. call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42, 0))
  2696. call assert_equal([1, 42, 2, 3, 4, 5], insert(range(1, 5), 42, 1))
  2697. call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, 4))
  2698. call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, -1))
  2699. call assert_equal([1, 2, 3, 4, 5, 42], insert(range(1, 5), 42, 5))
  2700. " join()
  2701. call assert_equal('0 1 2 3 4', join(range(5)))
  2702. " json_encode()
  2703. " call assert_equal('[0,1,2,3]', json_encode(range(4)))
  2704. call assert_equal('[0, 1, 2, 3]', json_encode(range(4)))
  2705. " len()
  2706. call assert_equal(0, len(range(0)))
  2707. call assert_equal(2, len(range(2)))
  2708. call assert_equal(5, len(range(0, 12, 3)))
  2709. call assert_equal(4, len(range(3, 0, -1)))
  2710. " list2str()
  2711. call assert_equal('ABC', list2str(range(65, 67)))
  2712. call assert_fails('let s = list2str(5)', 'E474:')
  2713. " lock()
  2714. let thelist = range(5)
  2715. lockvar thelist
  2716. " map()
  2717. call assert_equal([0, 2, 4, 6, 8], map(range(5), 'v:val * 2'))
  2718. " match()
  2719. call assert_equal(3, match(range(5), 3))
  2720. " matchaddpos()
  2721. highlight MyGreenGroup ctermbg=green guibg=green
  2722. call matchaddpos('MyGreenGroup', range(line('.'), line('.')))
  2723. " matchend()
  2724. call assert_equal(4, matchend(range(5), '4'))
  2725. call assert_equal(3, matchend(range(1, 5), '4'))
  2726. call assert_equal(-1, matchend(range(1, 5), '42'))
  2727. " matchstrpos()
  2728. call assert_equal(['4', 4, 0, 1], matchstrpos(range(5), '4'))
  2729. call assert_equal(['4', 3, 0, 1], matchstrpos(range(1, 5), '4'))
  2730. call assert_equal(['', -1, -1, -1], matchstrpos(range(1, 5), '42'))
  2731. " max() reverse()
  2732. call assert_equal(0, max(range(0)))
  2733. call assert_equal(0, max(range(10, 9)))
  2734. call assert_equal(9, max(range(10)))
  2735. call assert_equal(18, max(range(0, 20, 3)))
  2736. call assert_equal(20, max(range(20, 0, -3)))
  2737. call assert_equal(99999, max(range(100000)))
  2738. call assert_equal(99999, max(range(99999, 0, -1)))
  2739. call assert_equal(99999, max(reverse(range(100000))))
  2740. call assert_equal(99999, max(reverse(range(99999, 0, -1))))
  2741. " min() reverse()
  2742. call assert_equal(0, min(range(0)))
  2743. call assert_equal(0, min(range(10, 9)))
  2744. call assert_equal(5, min(range(5, 10)))
  2745. call assert_equal(5, min(range(5, 10, 3)))
  2746. call assert_equal(2, min(range(20, 0, -3)))
  2747. call assert_equal(0, min(range(100000)))
  2748. call assert_equal(0, min(range(99999, 0, -1)))
  2749. call assert_equal(0, min(reverse(range(100000))))
  2750. call assert_equal(0, min(reverse(range(99999, 0, -1))))
  2751. " remove()
  2752. call assert_equal(1, remove(range(1, 10), 0))
  2753. call assert_equal(2, remove(range(1, 10), 1))
  2754. call assert_equal(9, remove(range(1, 10), 8))
  2755. call assert_equal(10, remove(range(1, 10), 9))
  2756. call assert_equal(10, remove(range(1, 10), -1))
  2757. call assert_equal([3, 4, 5], remove(range(1, 10), 2, 4))
  2758. " repeat()
  2759. call assert_equal([0, 1, 2, 0, 1, 2], repeat(range(3), 2))
  2760. call assert_equal([0, 1, 2], repeat(range(3), 1))
  2761. call assert_equal([], repeat(range(3), 0))
  2762. call assert_equal([], repeat(range(5, 4), 2))
  2763. call assert_equal([], repeat(range(5, 4), 0))
  2764. " reverse()
  2765. call assert_equal([2, 1, 0], reverse(range(3)))
  2766. call assert_equal([0, 1, 2, 3], reverse(range(3, 0, -1)))
  2767. call assert_equal([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], reverse(range(10)))
  2768. call assert_equal([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], reverse(range(10, 20)))
  2769. call assert_equal([16, 13, 10], reverse(range(10, 18, 3)))
  2770. call assert_equal([19, 16, 13, 10], reverse(range(10, 19, 3)))
  2771. call assert_equal([19, 16, 13, 10], reverse(range(10, 20, 3)))
  2772. call assert_equal([11, 14, 17, 20], reverse(range(20, 10, -3)))
  2773. call assert_equal([], reverse(range(0)))
  2774. " TODO: setpos()
  2775. " new
  2776. " call setline(1, repeat([''], bufnr('')))
  2777. " call setline(bufnr('') + 1, repeat('x', bufnr('') * 2 + 6))
  2778. " call setpos('x', range(bufnr(''), bufnr('') + 3))
  2779. " bwipe!
  2780. " setreg()
  2781. call setreg('a', range(3))
  2782. call assert_equal("0\n1\n2\n", getreg('a'))
  2783. " settagstack()
  2784. call settagstack(1, #{items : range(4)})
  2785. " sign_define()
  2786. call assert_fails("call sign_define(range(5))", "E715:")
  2787. call assert_fails("call sign_placelist(range(5))", "E715:")
  2788. " sign_undefine()
  2789. " call assert_fails("call sign_undefine(range(5))", "E908:")
  2790. call assert_fails("call sign_undefine(range(5))", "E155:")
  2791. " sign_unplacelist()
  2792. call assert_fails("call sign_unplacelist(range(5))", "E715:")
  2793. " sort()
  2794. call assert_equal([0, 1, 2, 3, 4, 5], sort(range(5, 0, -1)))
  2795. " string()
  2796. call assert_equal('[0, 1, 2, 3, 4]', string(range(5)))
  2797. " taglist() with 'tagfunc'
  2798. func TagFunc(pattern, flags, info)
  2799. return range(10)
  2800. endfunc
  2801. set tagfunc=TagFunc
  2802. call assert_fails("call taglist('asdf')", 'E987:')
  2803. set tagfunc=
  2804. " term_start()
  2805. if has('terminal') && has('termguicolors')
  2806. call assert_fails('call term_start(range(3, 4))', 'E474:')
  2807. let g:terminal_ansi_colors = range(16)
  2808. if has('win32')
  2809. let cmd = "cmd /D /c dir"
  2810. else
  2811. let cmd = "ls"
  2812. endif
  2813. call assert_fails('call term_start("' .. cmd .. '", #{term_finish: "close"})', 'E475:')
  2814. unlet g:terminal_ansi_colors
  2815. endif
  2816. " type()
  2817. call assert_equal(v:t_list, type(range(5)))
  2818. " uniq()
  2819. call assert_equal([0, 1, 2, 3, 4], uniq(range(5)))
  2820. " errors
  2821. call assert_fails('let x=range(2, 8, 0)', 'E726:')
  2822. call assert_fails('let x=range(3, 1)', 'E727:')
  2823. call assert_fails('let x=range(1, 3, -2)', 'E727:')
  2824. call assert_fails('let x=range([])', 'E745:')
  2825. call assert_fails('let x=range(1, [])', 'E745:')
  2826. call assert_fails('let x=range(1, 4, [])', 'E745:')
  2827. endfunc
  2828. func Test_garbagecollect_now_fails()
  2829. let v:testing = 0
  2830. call assert_fails('call test_garbagecollect_now()', 'E1142:')
  2831. let v:testing = 1
  2832. endfunc
  2833. " Test for echo highlighting
  2834. func Test_echohl()
  2835. echohl Search
  2836. echo 'Vim'
  2837. call assert_equal('Vim', Screenline(&lines))
  2838. " TODO: How to check the highlight group used by echohl?
  2839. " ScreenAttrs() returns all zeros.
  2840. echohl None
  2841. endfunc
  2842. " Test for the eval() function
  2843. func Test_eval()
  2844. call assert_fails("call eval('5 a')", 'E488:')
  2845. endfunc
  2846. " Test for the keytrans() function
  2847. func Test_keytrans()
  2848. call assert_equal('<Space>', keytrans(' '))
  2849. call assert_equal('<lt>', keytrans('<'))
  2850. call assert_equal('<lt>Tab>', keytrans('<Tab>'))
  2851. call assert_equal('<Tab>', keytrans("\<Tab>"))
  2852. call assert_equal('<C-V>', keytrans("\<C-V>"))
  2853. call assert_equal('<BS>', keytrans("\<BS>"))
  2854. call assert_equal('<Home>', keytrans("\<Home>"))
  2855. call assert_equal('<C-Home>', keytrans("\<C-Home>"))
  2856. call assert_equal('<M-Home>', keytrans("\<M-Home>"))
  2857. call assert_equal('<C-Space>', keytrans("\<C-Space>"))
  2858. call assert_equal('<M-Space>', keytrans("\<*M-Space>"))
  2859. call assert_equal('<M-x>', "\<*M-x>"->keytrans())
  2860. call assert_equal('<C-I>', "\<*C-I>"->keytrans())
  2861. call assert_equal('<S-3>', "\<*S-3>"->keytrans())
  2862. call assert_equal('π', 'π'->keytrans())
  2863. call assert_equal('<M-π>', "\<M-π>"->keytrans())
  2864. call assert_equal('ě', 'ě'->keytrans())
  2865. call assert_equal('<M-ě>', "\<M-ě>"->keytrans())
  2866. call assert_equal('', ''->keytrans())
  2867. call assert_equal('', v:_null_string->keytrans())
  2868. call assert_fails('call keytrans(1)', 'E1174:')
  2869. call assert_fails('call keytrans()', 'E119:')
  2870. endfunc
  2871. " Test for the nr2char() function
  2872. func Test_nr2char()
  2873. " set encoding=latin1
  2874. call assert_equal('@', nr2char(64))
  2875. set encoding=utf8
  2876. call assert_equal('a', nr2char(97, 1))
  2877. call assert_equal('a', nr2char(97, 0))
  2878. call assert_equal("\x80\xfc\b" .. nr2char(0x100000), eval('"\<M-' .. nr2char(0x100000) .. '>"'))
  2879. call assert_equal("\x80\xfc\b" .. nr2char(0x40000000), eval('"\<M-' .. nr2char(0x40000000) .. '>"'))
  2880. endfunc
  2881. " Test for screenattr(), screenchar() and screenchars() functions
  2882. func Test_screen_functions()
  2883. call assert_equal(-1, screenattr(-1, -1))
  2884. call assert_equal(-1, screenchar(-1, -1))
  2885. call assert_equal([], screenchars(-1, -1))
  2886. " Run this in a separate Vim instance to avoid messing up.
  2887. let after =<< trim [CODE]
  2888. scriptencoding utf-8
  2889. call setline(1, '口')
  2890. redraw
  2891. call assert_equal(0, screenattr(1, 1))
  2892. call assert_equal(char2nr('口'), screenchar(1, 1))
  2893. call assert_equal([char2nr('口')], screenchars(1, 1))
  2894. call assert_equal('口', screenstring(1, 1))
  2895. call writefile(v:errors, 'Xresult')
  2896. qall!
  2897. [CODE]
  2898. let encodings = ['utf-8', 'cp932', 'cp936', 'cp949', 'cp950']
  2899. if !has('win32')
  2900. let encodings += ['euc-jp']
  2901. endif
  2902. if has('nvim')
  2903. let encodings = ['utf-8']
  2904. endif
  2905. for enc in encodings
  2906. let msg = 'enc=' .. enc
  2907. if RunVim([], after, $'--clean --cmd "set encoding={enc}"')
  2908. call assert_equal([], readfile('Xresult'), msg)
  2909. endif
  2910. call delete('Xresult')
  2911. endfor
  2912. endfunc
  2913. " Test for getcurpos() and setpos()
  2914. func Test_getcurpos_setpos()
  2915. new
  2916. call setline(1, ['012345678', '012345678'])
  2917. normal gg6l
  2918. let sp = getcurpos()
  2919. normal 0
  2920. call setpos('.', sp)
  2921. normal jyl
  2922. call assert_equal('6', @")
  2923. call assert_equal(-1, setpos('.', v:_null_list))
  2924. call assert_equal(-1, setpos('.', {}))
  2925. let winid = win_getid()
  2926. normal G$
  2927. let pos = getcurpos()
  2928. wincmd w
  2929. call assert_equal(pos, getcurpos(winid))
  2930. wincmd w
  2931. close!
  2932. call assert_equal(getcurpos(), getcurpos(0))
  2933. call assert_equal([0, 0, 0, 0, 0], getcurpos(-1))
  2934. call assert_equal([0, 0, 0, 0, 0], getcurpos(1999))
  2935. endfunc
  2936. func Test_getmousepos()
  2937. enew!
  2938. call setline(1, "\t\t\t1234")
  2939. call Ntest_setmouse(1, 1)
  2940. call assert_equal(#{
  2941. \ screenrow: 1,
  2942. \ screencol: 1,
  2943. \ winid: win_getid(),
  2944. \ winrow: 1,
  2945. \ wincol: 1,
  2946. \ line: 1,
  2947. \ column: 1,
  2948. \ coladd: 0,
  2949. \ }, getmousepos())
  2950. call Ntest_setmouse(1, 2)
  2951. call assert_equal(#{
  2952. \ screenrow: 1,
  2953. \ screencol: 2,
  2954. \ winid: win_getid(),
  2955. \ winrow: 1,
  2956. \ wincol: 2,
  2957. \ line: 1,
  2958. \ column: 1,
  2959. \ coladd: 1,
  2960. \ }, getmousepos())
  2961. call Ntest_setmouse(1, 8)
  2962. call assert_equal(#{
  2963. \ screenrow: 1,
  2964. \ screencol: 8,
  2965. \ winid: win_getid(),
  2966. \ winrow: 1,
  2967. \ wincol: 8,
  2968. \ line: 1,
  2969. \ column: 1,
  2970. \ coladd: 7,
  2971. \ }, getmousepos())
  2972. call Ntest_setmouse(1, 9)
  2973. call assert_equal(#{
  2974. \ screenrow: 1,
  2975. \ screencol: 9,
  2976. \ winid: win_getid(),
  2977. \ winrow: 1,
  2978. \ wincol: 9,
  2979. \ line: 1,
  2980. \ column: 2,
  2981. \ coladd: 0,
  2982. \ }, getmousepos())
  2983. call Ntest_setmouse(1, 12)
  2984. call assert_equal(#{
  2985. \ screenrow: 1,
  2986. \ screencol: 12,
  2987. \ winid: win_getid(),
  2988. \ winrow: 1,
  2989. \ wincol: 12,
  2990. \ line: 1,
  2991. \ column: 2,
  2992. \ coladd: 3,
  2993. \ }, getmousepos())
  2994. call Ntest_setmouse(1, 25)
  2995. call assert_equal(#{
  2996. \ screenrow: 1,
  2997. \ screencol: 25,
  2998. \ winid: win_getid(),
  2999. \ winrow: 1,
  3000. \ wincol: 25,
  3001. \ line: 1,
  3002. \ column: 4,
  3003. \ coladd: 0,
  3004. \ }, getmousepos())
  3005. call Ntest_setmouse(1, 28)
  3006. call assert_equal(#{
  3007. \ screenrow: 1,
  3008. \ screencol: 28,
  3009. \ winid: win_getid(),
  3010. \ winrow: 1,
  3011. \ wincol: 28,
  3012. \ line: 1,
  3013. \ column: 7,
  3014. \ coladd: 0,
  3015. \ }, getmousepos())
  3016. call Ntest_setmouse(1, 29)
  3017. call assert_equal(#{
  3018. \ screenrow: 1,
  3019. \ screencol: 29,
  3020. \ winid: win_getid(),
  3021. \ winrow: 1,
  3022. \ wincol: 29,
  3023. \ line: 1,
  3024. \ column: 8,
  3025. \ coladd: 0,
  3026. \ }, getmousepos())
  3027. call Ntest_setmouse(1, 50)
  3028. call assert_equal(#{
  3029. \ screenrow: 1,
  3030. \ screencol: 50,
  3031. \ winid: win_getid(),
  3032. \ winrow: 1,
  3033. \ wincol: 50,
  3034. \ line: 1,
  3035. \ column: 8,
  3036. \ coladd: 21,
  3037. \ }, getmousepos())
  3038. " If the mouse is positioned past the last buffer line, "line" and "column"
  3039. " should act like it's positioned on the last buffer line.
  3040. call Ntest_setmouse(2, 25)
  3041. call assert_equal(#{
  3042. \ screenrow: 2,
  3043. \ screencol: 25,
  3044. \ winid: win_getid(),
  3045. \ winrow: 2,
  3046. \ wincol: 25,
  3047. \ line: 1,
  3048. \ column: 4,
  3049. \ coladd: 0,
  3050. \ }, getmousepos())
  3051. call Ntest_setmouse(2, 50)
  3052. call assert_equal(#{
  3053. \ screenrow: 2,
  3054. \ screencol: 50,
  3055. \ winid: win_getid(),
  3056. \ winrow: 2,
  3057. \ wincol: 50,
  3058. \ line: 1,
  3059. \ column: 8,
  3060. \ coladd: 21,
  3061. \ }, getmousepos())
  3062. 30vnew
  3063. setlocal smoothscroll number
  3064. call setline(1, join(range(100)))
  3065. exe "normal! \<C-E>"
  3066. call Ntest_setmouse(1, 5)
  3067. call assert_equal(#{
  3068. \ screenrow: 1,
  3069. \ screencol: 5,
  3070. \ winid: win_getid(),
  3071. \ winrow: 1,
  3072. \ wincol: 5,
  3073. \ line: 1,
  3074. \ column: 27,
  3075. \ coladd: 0,
  3076. \ }, getmousepos())
  3077. call Ntest_setmouse(2, 5)
  3078. call assert_equal(#{
  3079. \ screenrow: 2,
  3080. \ screencol: 5,
  3081. \ winid: win_getid(),
  3082. \ winrow: 2,
  3083. \ wincol: 5,
  3084. \ line: 1,
  3085. \ column: 53,
  3086. \ coladd: 0,
  3087. \ }, getmousepos())
  3088. exe "normal! \<C-E>"
  3089. call Ntest_setmouse(1, 5)
  3090. call assert_equal(#{
  3091. \ screenrow: 1,
  3092. \ screencol: 5,
  3093. \ winid: win_getid(),
  3094. \ winrow: 1,
  3095. \ wincol: 5,
  3096. \ line: 1,
  3097. \ column: 53,
  3098. \ coladd: 0,
  3099. \ }, getmousepos())
  3100. call Ntest_setmouse(2, 5)
  3101. call assert_equal(#{
  3102. \ screenrow: 2,
  3103. \ screencol: 5,
  3104. \ winid: win_getid(),
  3105. \ winrow: 2,
  3106. \ wincol: 5,
  3107. \ line: 1,
  3108. \ column: 79,
  3109. \ coladd: 0,
  3110. \ }, getmousepos())
  3111. vert resize 4
  3112. call Ntest_setmouse(2, 2)
  3113. " This used to crash Vim
  3114. call assert_equal(#{
  3115. \ screenrow: 2,
  3116. \ screencol: 2,
  3117. \ winid: win_getid(),
  3118. \ winrow: 2,
  3119. \ wincol: 2,
  3120. \ line: 1,
  3121. \ column: 53,
  3122. \ coladd: 0,
  3123. \ }, getmousepos())
  3124. bwipe!
  3125. bwipe!
  3126. endfunc
  3127. " Test for glob()
  3128. func Test_glob()
  3129. call assert_equal('', glob(v:_null_string))
  3130. call assert_equal('', globpath(v:_null_string, v:_null_string))
  3131. call assert_fails("let x = globpath(&rtp, 'syntax/c.vim', [])", 'E745:')
  3132. call writefile([], 'Xglob1')
  3133. call writefile([], 'XGLOB2')
  3134. set wildignorecase
  3135. " Sort output of glob() otherwise we end up with different
  3136. " ordering depending on whether file system is case-sensitive.
  3137. call assert_equal(['XGLOB2', 'Xglob1'], sort(glob('Xglob[12]', 0, 1)))
  3138. " wildignorecase shall be applied even when the pattern contains no wildcards.
  3139. call assert_equal('XGLOB2', glob('xglob2'))
  3140. set wildignorecase&
  3141. call delete('Xglob1')
  3142. call delete('XGLOB2')
  3143. call assert_fails("call glob('*', 0, {})", 'E728:')
  3144. endfunc
  3145. func Test_glob2()
  3146. call mkdir('[XglobDir]', 'R')
  3147. call mkdir('abc[glob]def', 'R')
  3148. call writefile(['glob'], '[XglobDir]/Xglob')
  3149. call writefile(['glob'], 'abc[glob]def/Xglob')
  3150. if has("unix")
  3151. call assert_equal([], (glob('[XglobDir]/*', 0, 1)))
  3152. call assert_equal([], (glob('abc[glob]def/*', 0, 1)))
  3153. call assert_equal(['[XglobDir]/Xglob'], (glob('\[XglobDir]/*', 0, 1)))
  3154. call assert_equal(['abc[glob]def/Xglob'], (glob('abc\[glob]def/*', 0, 1)))
  3155. elseif has("win32")
  3156. let _sl=&shellslash
  3157. call assert_equal([], (glob('[XglobDir]\*', 0, 1)))
  3158. call assert_equal([], (glob('abc[glob]def\*', 0, 1)))
  3159. call assert_equal([], (glob('\[XglobDir]\*', 0, 1)))
  3160. call assert_equal([], (glob('abc\[glob]def\*', 0, 1)))
  3161. set noshellslash
  3162. call assert_equal(['[XglobDir]\Xglob'], (glob('[[]XglobDir]/*', 0, 1)))
  3163. call assert_equal(['abc[glob]def\Xglob'], (glob('abc[[]glob]def/*', 0, 1)))
  3164. set shellslash
  3165. call assert_equal(['[XglobDir]/Xglob'], (glob('[[]XglobDir]/*', 0, 1)))
  3166. call assert_equal(['abc[glob]def/Xglob'], (glob('abc[[]glob]def/*', 0, 1)))
  3167. let &shellslash=_sl
  3168. endif
  3169. endfunc
  3170. func Test_glob_symlinks()
  3171. call writefile([], 'Xglob1')
  3172. if has("win32")
  3173. silent !mklink XglobBad DoesNotExist
  3174. if v:shell_error
  3175. throw 'Skipped: cannot create symlinks'
  3176. endif
  3177. silent !mklink XglobOk Xglob1
  3178. else
  3179. silent !ln -s DoesNotExist XglobBad
  3180. silent !ln -s Xglob1 XglobOk
  3181. endif
  3182. " The broken symlink is excluded when alllinks is false.
  3183. call assert_equal(['Xglob1', 'XglobBad', 'XglobOk'], sort(glob('Xglob*', 0, 1, 1)))
  3184. call assert_equal(['Xglob1', 'XglobOk'], sort(glob('Xglob*', 0, 1, 0)))
  3185. call delete('Xglob1')
  3186. call delete('XglobBad')
  3187. call delete('XglobOk')
  3188. endfunc
  3189. " Test for browse()
  3190. func Test_browse()
  3191. CheckFeature browse
  3192. call assert_fails('call browse([], "open", "x", "a.c")', 'E745:')
  3193. endfunc
  3194. " Test for browsedir()
  3195. func Test_browsedir()
  3196. CheckFeature browse
  3197. call assert_fails('call browsedir("open", [])', 'E730:')
  3198. endfunc
  3199. func HasDefault(msg = 'msg')
  3200. return a:msg
  3201. endfunc
  3202. func Test_default_arg_value()
  3203. call assert_equal('msg', HasDefault())
  3204. endfunc
  3205. " Test for gettext()
  3206. func Test_gettext()
  3207. call assert_fails('call gettext(1)', 'E1174:')
  3208. endfunc
  3209. func Test_builtin_check()
  3210. call assert_fails('let g:["trim"] = {x -> " " .. x}', 'E704:')
  3211. call assert_fails('let g:.trim = {x -> " " .. x}', 'E704:')
  3212. call assert_fails('let l:["trim"] = {x -> " " .. x}', 'E704:')
  3213. call assert_fails('let l:.trim = {x -> " " .. x}', 'E704:')
  3214. let lines =<< trim END
  3215. vim9script
  3216. var trim = (x) => " " .. x
  3217. END
  3218. call CheckScriptFailure(lines, 'E704:')
  3219. call assert_fails('call extend(g:, #{foo: { -> "foo" }})', 'E704:')
  3220. let g:bar = 123
  3221. call extend(g:, #{bar: { -> "foo" }}, "keep")
  3222. call assert_fails('call extend(g:, #{bar: { -> "foo" }}, "force")', 'E704:')
  3223. unlet g:bar
  3224. call assert_fails('call extend(l:, #{foo: { -> "foo" }})', 'E704:')
  3225. let bar = 123
  3226. call extend(l:, #{bar: { -> "foo" }}, "keep")
  3227. call assert_fails('call extend(l:, #{bar: { -> "foo" }}, "force")', 'E704:')
  3228. unlet bar
  3229. call assert_fails('call extend(g:, #{foo: function("extend")})', 'E704:')
  3230. let g:bar = 123
  3231. call extend(g:, #{bar: function("extend")}, "keep")
  3232. call assert_fails('call extend(g:, #{bar: function("extend")}, "force")', 'E704:')
  3233. unlet g:bar
  3234. call assert_fails('call extend(l:, #{foo: function("extend")})', 'E704:')
  3235. let bar = 123
  3236. call extend(l:, #{bar: function("extend")}, "keep")
  3237. call assert_fails('call extend(l:, #{bar: function("extend")}, "force")', 'E704:')
  3238. unlet bar
  3239. endfunc
  3240. " Test for isabsolutepath()
  3241. func Test_isabsolutepath()
  3242. call assert_false(isabsolutepath(''))
  3243. call assert_false(isabsolutepath('.'))
  3244. call assert_false(isabsolutepath('../Foo'))
  3245. call assert_false(isabsolutepath('Foo/'))
  3246. if has('win32')
  3247. call assert_true(isabsolutepath('A:\'))
  3248. call assert_true(isabsolutepath('A:\Foo'))
  3249. call assert_true(isabsolutepath('A:/Foo'))
  3250. call assert_false(isabsolutepath('A:Foo'))
  3251. call assert_false(isabsolutepath('\Windows'))
  3252. call assert_true(isabsolutepath('\\Server2\Share\Test\Foo.txt'))
  3253. else
  3254. call assert_true(isabsolutepath('/'))
  3255. call assert_true(isabsolutepath('/usr/share/'))
  3256. endif
  3257. endfunc
  3258. " Test for exepath()
  3259. func Test_exepath()
  3260. if has('win32')
  3261. call assert_notequal(exepath('cmd'), '')
  3262. let oldNoDefaultCurrentDirectoryInExePath = $NoDefaultCurrentDirectoryInExePath
  3263. call writefile(['@echo off', 'echo Evil'], 'vim-test-evil.bat')
  3264. let $NoDefaultCurrentDirectoryInExePath = ''
  3265. call assert_notequal(exepath("vim-test-evil.bat"), '')
  3266. let $NoDefaultCurrentDirectoryInExePath = '1'
  3267. call assert_equal(exepath("vim-test-evil.bat"), '')
  3268. let $NoDefaultCurrentDirectoryInExePath = oldNoDefaultCurrentDirectoryInExePath
  3269. call delete('vim-test-evil.bat')
  3270. else
  3271. call assert_notequal(exepath('sh'), '')
  3272. endif
  3273. endfunc
  3274. " Test for virtcol()
  3275. func Test_virtcol()
  3276. new
  3277. call setline(1, "the\tquick\tbrown\tfox")
  3278. norm! 4|
  3279. call assert_equal(8, virtcol('.'))
  3280. call assert_equal(8, virtcol('.', v:false))
  3281. call assert_equal([4, 8], virtcol('.', v:true))
  3282. let w = winwidth(0)
  3283. call setline(2, repeat('a', w + 2))
  3284. let win_nosbr = win_getid()
  3285. split
  3286. setlocal showbreak=!!
  3287. let win_sbr = win_getid()
  3288. call assert_equal([w, w], virtcol([2, w], v:true, win_nosbr))
  3289. call assert_equal([w + 1, w + 1], virtcol([2, w + 1], v:true, win_nosbr))
  3290. call assert_equal([w + 2, w + 2], virtcol([2, w + 2], v:true, win_nosbr))
  3291. call assert_equal([w, w], virtcol([2, w], v:true, win_sbr))
  3292. call assert_equal([w + 3, w + 3], virtcol([2, w + 1], v:true, win_sbr))
  3293. call assert_equal([w + 4, w + 4], virtcol([2, w + 2], v:true, win_sbr))
  3294. close
  3295. call assert_equal(0, virtcol(''))
  3296. call assert_equal([0, 0], virtcol('', v:true))
  3297. call assert_equal(0, virtcol('.', v:false, 5001))
  3298. call assert_equal([0, 0], virtcol('.', v:true, 5001))
  3299. bwipe!
  3300. endfunc
  3301. func Test_delfunc_while_listing()
  3302. CheckRunVimInTerminal
  3303. let lines =<< trim END
  3304. set nocompatible
  3305. for i in range(1, 999)
  3306. exe 'func ' .. 'MyFunc' .. i .. '()'
  3307. endfunc
  3308. endfor
  3309. au CmdlineLeave : call timer_start(0, {-> execute('delfunc MyFunc622')})
  3310. END
  3311. call writefile(lines, 'Xfunctionclear', 'D')
  3312. let buf = RunVimInTerminal('-S Xfunctionclear', {'rows': 12})
  3313. " This was using freed memory. The height of the terminal must be so that
  3314. " the next function to be listed with "j" is the one that is deleted in the
  3315. " timer callback, tricky!
  3316. call term_sendkeys(buf, ":func /MyFunc\<CR>")
  3317. call TermWait(buf, 50)
  3318. call term_sendkeys(buf, "j")
  3319. call TermWait(buf, 50)
  3320. call term_sendkeys(buf, "\<CR>")
  3321. call StopVimInTerminal(buf)
  3322. endfunc
  3323. " Test for the reverse() function with a string
  3324. func Test_string_reverse()
  3325. let lines =<< trim END
  3326. call assert_equal('', reverse(v:_null_string))
  3327. for [s1, s2] in [['', ''], ['a', 'a'], ['ab', 'ba'], ['abc', 'cba'],
  3328. \ ['abcd', 'dcba'], ['«-«-»-»', '»-»-«-«'],
  3329. \ ['🇦', '🇦'], ['🇦🇧', '🇦🇧'], ['🇦🇧🇨', '🇨🇦🇧'],
  3330. \ ['🇦«🇧-🇨»🇩', '🇩»🇨-🇧«🇦']]
  3331. call assert_equal(s2, reverse(s1))
  3332. endfor
  3333. END
  3334. call CheckLegacyAndVim9Success(lines)
  3335. " test in latin1 encoding
  3336. let save_enc = &encoding
  3337. " set encoding=latin1
  3338. call assert_equal('dcba', reverse('abcd'))
  3339. let &encoding = save_enc
  3340. endfunc
  3341. func Test_fullcommand()
  3342. " this used to crash vim
  3343. call assert_equal('', fullcommand(10))
  3344. endfunc
  3345. " Test for glob() with shell special patterns
  3346. func Test_glob_extended_bash()
  3347. CheckExecutable bash
  3348. CheckNotMSWindows
  3349. CheckNotMac " The default version of bash is old on macOS.
  3350. let _shell = &shell
  3351. set shell=bash
  3352. call mkdir('Xtestglob/foo/bar/src', 'p')
  3353. call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
  3354. call writefile([], 'Xtestglob/foo/bar/src/foo.h')
  3355. call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
  3356. " Sort output of glob() otherwise we end up with different
  3357. " ordering depending on whether file system is case-sensitive.
  3358. let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h']
  3359. call assert_equal(expected, sort(glob('Xtestglob/**/foo.{h,cpp}', 0, 1)))
  3360. call delete('Xtestglob', 'rf')
  3361. let &shell=_shell
  3362. endfunc
  3363. " Test for glob() with extended patterns (MS-Windows)
  3364. " Vim doesn't use 'shell' to expand wildcards on MS-Windows.
  3365. " Unlike bash, it doesn't support {,} expansion.
  3366. func Test_glob_extended_mswin()
  3367. CheckMSWindows
  3368. call mkdir('Xtestglob/foo/bar/src', 'p')
  3369. call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
  3370. call writefile([], 'Xtestglob/foo/bar/src/foo.h')
  3371. call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
  3372. " Sort output of glob() otherwise we end up with different
  3373. " ordering depending on whether file system is case-sensitive.
  3374. let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h', 'Xtestglob/foo/bar/src/foo.sh']
  3375. call assert_equal(expected, sort(glob('Xtestglob/**/foo.*', 0, 1)))
  3376. call delete('Xtestglob', 'rf')
  3377. endfunc
  3378. " Tests for the slice() function.
  3379. func Test_slice()
  3380. let lines =<< trim END
  3381. call assert_equal([1, 2, 3, 4, 5], slice(range(6), 1))
  3382. call assert_equal([2, 3, 4, 5], slice(range(6), 2))
  3383. call assert_equal([2, 3], slice(range(6), 2, 4))
  3384. call assert_equal([0, 1, 2, 3], slice(range(6), 0, 4))
  3385. call assert_equal([1, 2, 3], slice(range(6), 1, 4))
  3386. call assert_equal([1, 2, 3, 4], slice(range(6), 1, -1))
  3387. call assert_equal([1, 2], slice(range(6), 1, -3))
  3388. call assert_equal([1], slice(range(6), 1, -4))
  3389. call assert_equal([], slice(range(6), 1, -5))
  3390. call assert_equal([], slice(range(6), 1, -6))
  3391. call assert_equal(0z1122334455, slice(0z001122334455, 1))
  3392. call assert_equal(0z22334455, slice(0z001122334455, 2))
  3393. call assert_equal(0z2233, slice(0z001122334455, 2, 4))
  3394. call assert_equal(0z00112233, slice(0z001122334455, 0, 4))
  3395. call assert_equal(0z112233, slice(0z001122334455, 1, 4))
  3396. call assert_equal(0z11223344, slice(0z001122334455, 1, -1))
  3397. call assert_equal(0z1122, slice(0z001122334455, 1, -3))
  3398. call assert_equal(0z11, slice(0z001122334455, 1, -4))
  3399. call assert_equal(0z, slice(0z001122334455, 1, -5))
  3400. call assert_equal(0z, slice(0z001122334455, 1, -6))
  3401. call assert_equal('12345', slice('012345', 1))
  3402. call assert_equal('2345', slice('012345', 2))
  3403. call assert_equal('23', slice('012345', 2, 4))
  3404. call assert_equal('0123', slice('012345', 0, 4))
  3405. call assert_equal('123', slice('012345', 1, 4))
  3406. call assert_equal('1234', slice('012345', 1, -1))
  3407. call assert_equal('12', slice('012345', 1, -3))
  3408. call assert_equal('1', slice('012345', 1, -4))
  3409. call assert_equal('', slice('012345', 1, -5))
  3410. call assert_equal('', slice('012345', 1, -6))
  3411. #" Composing chars are treated as a part of the preceding base char.
  3412. call assert_equal('β̳́γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1))
  3413. call assert_equal('γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2))
  3414. call assert_equal('γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2, 4))
  3415. call assert_equal('ὰ̳β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(0, 4))
  3416. call assert_equal('β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, 4))
  3417. call assert_equal('β̳́γ̳̂δ̳̃ε̳̄', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -1))
  3418. call assert_equal('β̳́γ̳̂', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -3))
  3419. call assert_equal('β̳́', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -4))
  3420. call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -5))
  3421. call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -6))
  3422. END
  3423. call CheckLegacyAndVim9Success(lines)
  3424. call assert_equal(0, slice(v:true, 1))
  3425. endfunc
  3426. " vim: shiftwidth=2 sts=2 expandtab