test_functions.vim 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787
  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 setline(1, 'xxxx')
  2101. call Ntest_setmouse(1, 3)
  2102. let v:mouse_win = 9
  2103. let v:mouse_winid = 9
  2104. let v:mouse_lnum = 9
  2105. let v:mouse_col = 9
  2106. call feedkeys("\<S-LeftMouse>", '')
  2107. call assert_equal("\<S-LeftMouse>", getchar())
  2108. call assert_equal(1, v:mouse_win)
  2109. call assert_equal(win_getid(1), v:mouse_winid)
  2110. call assert_equal(1, v:mouse_lnum)
  2111. call assert_equal(3, v:mouse_col)
  2112. enew!
  2113. endfunc
  2114. func Test_libcall_libcallnr()
  2115. if !has('libcall')
  2116. return
  2117. endif
  2118. if has('win32')
  2119. let libc = 'msvcrt.dll'
  2120. elseif has('mac')
  2121. let libc = 'libSystem.B.dylib'
  2122. elseif executable('ldd')
  2123. let libc = matchstr(split(system('ldd ' . GetVimProg())), '/libc\.so\>')
  2124. endif
  2125. if get(l:, 'libc', '') ==# ''
  2126. " On Unix, libc.so can be in various places.
  2127. if has('linux')
  2128. " There is not documented but regarding the 1st argument of glibc's
  2129. " dlopen an empty string and nullptr are equivalent, so using an empty
  2130. " string for the 1st argument of libcall allows to call functions.
  2131. let libc = ''
  2132. elseif has('sun')
  2133. " Set the path to libc.so according to the architecture.
  2134. let test_bits = system('file ' . GetVimProg())
  2135. let test_arch = system('uname -p')
  2136. if test_bits =~ '64-bit' && test_arch =~ 'sparc'
  2137. let libc = '/usr/lib/sparcv9/libc.so'
  2138. elseif test_bits =~ '64-bit' && test_arch =~ 'i386'
  2139. let libc = '/usr/lib/amd64/libc.so'
  2140. else
  2141. let libc = '/usr/lib/libc.so'
  2142. endif
  2143. else
  2144. " Unfortunately skip this test until a good way is found.
  2145. return
  2146. endif
  2147. endif
  2148. if has('win32')
  2149. call assert_equal($USERPROFILE, 'USERPROFILE'->libcall(libc, 'getenv'))
  2150. else
  2151. call assert_equal($HOME, 'HOME'->libcall(libc, 'getenv'))
  2152. endif
  2153. " If function returns NULL, libcall() should return an empty string.
  2154. call assert_equal('', libcall(libc, 'getenv', 'X_ENV_DOES_NOT_EXIT'))
  2155. " Test libcallnr() with string and integer argument.
  2156. call assert_equal(4, 'abcd'->libcallnr(libc, 'strlen'))
  2157. call assert_equal(char2nr('A'), char2nr('a')->libcallnr(libc, 'toupper'))
  2158. call assert_fails("call libcall(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
  2159. call assert_fails("call libcallnr(libc, 'Xdoesnotexist_', '')", ['', 'E364:'])
  2160. call assert_fails("call libcall('Xdoesnotexist_', 'getenv', 'HOME')", ['', 'E364:'])
  2161. call assert_fails("call libcallnr('Xdoesnotexist_', 'strlen', 'abcd')", ['', 'E364:'])
  2162. endfunc
  2163. sandbox function Fsandbox()
  2164. normal ix
  2165. endfunc
  2166. func Test_func_sandbox()
  2167. sandbox let F = {-> 'hello'}
  2168. call assert_equal('hello', F())
  2169. sandbox let F = {-> "normal ix\<Esc>"->execute()}
  2170. call assert_fails('call F()', 'E48:')
  2171. unlet F
  2172. call assert_fails('call Fsandbox()', 'E48:')
  2173. delfunc Fsandbox
  2174. " From a sandbox try to set a predefined variable (which cannot be modified
  2175. " from a sandbox)
  2176. call assert_fails('sandbox let v:lnum = 10', 'E794:')
  2177. endfunc
  2178. func EditAnotherFile()
  2179. let word = expand('<cword>')
  2180. edit Xfuncrange2
  2181. endfunc
  2182. func Test_func_range_with_edit()
  2183. " Define a function that edits another buffer, then call it with a range that
  2184. " is invalid in that buffer.
  2185. call writefile(['just one line'], 'Xfuncrange2')
  2186. new
  2187. eval 10->range()->setline(1)
  2188. write Xfuncrange1
  2189. call assert_fails('5,8call EditAnotherFile()', 'E16:')
  2190. call delete('Xfuncrange1')
  2191. call delete('Xfuncrange2')
  2192. bwipe!
  2193. endfunc
  2194. func Test_func_exists_on_reload()
  2195. call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists')
  2196. call assert_equal(0, exists('*ExistingFunction'))
  2197. source Xfuncexists
  2198. call assert_equal(1, '*ExistingFunction'->exists())
  2199. " Redefining a function when reloading a script is OK.
  2200. source Xfuncexists
  2201. call assert_equal(1, exists('*ExistingFunction'))
  2202. " But redefining in another script is not OK.
  2203. call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists2')
  2204. call assert_fails('source Xfuncexists2', 'E122:')
  2205. delfunc ExistingFunction
  2206. call assert_equal(0, exists('*ExistingFunction'))
  2207. call writefile([
  2208. \ 'func ExistingFunction()', 'echo "yes"', 'endfunc',
  2209. \ 'func ExistingFunction()', 'echo "no"', 'endfunc',
  2210. \ ], 'Xfuncexists')
  2211. call assert_fails('source Xfuncexists', 'E122:')
  2212. call assert_equal(1, exists('*ExistingFunction'))
  2213. call delete('Xfuncexists2')
  2214. call delete('Xfuncexists')
  2215. delfunc ExistingFunction
  2216. endfunc
  2217. func Test_platform_name()
  2218. " The system matches at most only one name.
  2219. let names = ['amiga', 'beos', 'bsd', 'hpux', 'linux', 'mac', 'qnx', 'sun', 'vms', 'win32', 'win32unix']
  2220. call assert_inrange(0, 1, len(filter(copy(names), 'has(v:val)')))
  2221. " Is Unix?
  2222. call assert_equal(has('beos'), has('beos') && has('unix'))
  2223. call assert_equal(has('bsd'), has('bsd') && has('unix'))
  2224. call assert_equal(has('hpux'), has('hpux') && has('unix'))
  2225. call assert_equal(has('linux'), has('linux') && has('unix'))
  2226. call assert_equal(has('mac'), has('mac') && has('unix'))
  2227. call assert_equal(has('qnx'), has('qnx') && has('unix'))
  2228. call assert_equal(has('sun'), has('sun') && has('unix'))
  2229. call assert_equal(has('win32'), has('win32') && !has('unix'))
  2230. call assert_equal(has('win32unix'), has('win32unix') && has('unix'))
  2231. if has('unix') && executable('uname')
  2232. let uname = system('uname')
  2233. call assert_equal(uname =~? 'BeOS', has('beos'))
  2234. " GNU userland on BSD kernels (e.g., GNU/kFreeBSD) don't have BSD defined
  2235. call assert_equal(uname =~? '\%(GNU/k\w\+\)\@<!BSD\|DragonFly', has('bsd'))
  2236. call assert_equal(uname =~? 'HP-UX', has('hpux'))
  2237. call assert_equal(uname =~? 'Linux', has('linux'))
  2238. call assert_equal(uname =~? 'Darwin', has('mac'))
  2239. call assert_equal(uname =~? 'QNX', has('qnx'))
  2240. call assert_equal(uname =~? 'SunOS', has('sun'))
  2241. call assert_equal(uname =~? 'CYGWIN\|MSYS', has('win32unix'))
  2242. endif
  2243. endfunc
  2244. " Test confirm({msg} [, {choices} [, {default} [, {type}]]])
  2245. func Test_confirm()
  2246. CheckUnix
  2247. CheckNotGui
  2248. call feedkeys('o', 'L')
  2249. let a = confirm('Press O to proceed')
  2250. call assert_equal(1, a)
  2251. call feedkeys('y', 'L')
  2252. let a = 'Are you sure?'->confirm("&Yes\n&No")
  2253. call assert_equal(1, a)
  2254. call feedkeys('n', 'L')
  2255. let a = confirm('Are you sure?', "&Yes\n&No")
  2256. call assert_equal(2, a)
  2257. " confirm() should return 0 when pressing CTRL-C.
  2258. call feedkeys("\<C-C>", 'L')
  2259. let a = confirm('Are you sure?', "&Yes\n&No")
  2260. call assert_equal(0, a)
  2261. " <Esc> requires another character to avoid it being seen as the start of an
  2262. " escape sequence. Zero should be harmless.
  2263. eval "\<Esc>0"->feedkeys('L')
  2264. let a = confirm('Are you sure?', "&Yes\n&No")
  2265. call assert_equal(0, a)
  2266. " Default choice is returned when pressing <CR>.
  2267. call feedkeys("\<CR>", 'L')
  2268. let a = confirm('Are you sure?', "&Yes\n&No")
  2269. call assert_equal(1, a)
  2270. call feedkeys("\<CR>", 'L')
  2271. let a = confirm('Are you sure?', "&Yes\n&No", 2)
  2272. call assert_equal(2, a)
  2273. call feedkeys("\<CR>", 'L')
  2274. let a = confirm('Are you sure?', "&Yes\n&No", 0)
  2275. call assert_equal(0, a)
  2276. " Test with the {type} 4th argument
  2277. for type in ['Error', 'Question', 'Info', 'Warning', 'Generic']
  2278. call feedkeys('y', 'L')
  2279. let a = confirm('Are you sure?', "&Yes\n&No\n", 1, type)
  2280. call assert_equal(1, a)
  2281. endfor
  2282. call assert_fails('call confirm([])', 'E730:')
  2283. call assert_fails('call confirm("Are you sure?", [])', 'E730:')
  2284. call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", [])', 'E745:')
  2285. call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", 0, [])', 'E730:')
  2286. endfunc
  2287. func Test_readdir()
  2288. call mkdir('Xdir')
  2289. call writefile([], 'Xdir/foo.txt')
  2290. call writefile([], 'Xdir/bar.txt')
  2291. call mkdir('Xdir/dir')
  2292. " All results
  2293. let files = readdir('Xdir')
  2294. call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files))
  2295. " Only results containing "f"
  2296. let files = 'Xdir'->readdir({ x -> stridx(x, 'f') !=- 1 })
  2297. call assert_equal(['foo.txt'], sort(files))
  2298. " Only .txt files
  2299. let files = readdir('Xdir', { x -> x =~ '.txt$' })
  2300. call assert_equal(['bar.txt', 'foo.txt'], sort(files))
  2301. " Only .txt files with string
  2302. let files = readdir('Xdir', 'v:val =~ ".txt$"')
  2303. call assert_equal(['bar.txt', 'foo.txt'], sort(files))
  2304. " Limit to 1 result.
  2305. let l = []
  2306. let files = readdir('Xdir', {x -> len(add(l, x)) == 2 ? -1 : 1})
  2307. call assert_equal(1, len(files))
  2308. " Nested readdir() must not crash
  2309. let files = readdir('Xdir', 'readdir("Xdir", "1") != []')
  2310. call sort(files)->assert_equal(['bar.txt', 'dir', 'foo.txt'])
  2311. eval 'Xdir'->delete('rf')
  2312. endfunc
  2313. func Test_delete_rf()
  2314. call mkdir('Xdir')
  2315. call writefile([], 'Xdir/foo.txt')
  2316. call writefile([], 'Xdir/bar.txt')
  2317. call mkdir('Xdir/[a-1]') " issue #696
  2318. call writefile([], 'Xdir/[a-1]/foo.txt')
  2319. call writefile([], 'Xdir/[a-1]/bar.txt')
  2320. call assert_true(filereadable('Xdir/foo.txt'))
  2321. call assert_true('Xdir/[a-1]/foo.txt'->filereadable())
  2322. call assert_equal(0, delete('Xdir', 'rf'))
  2323. call assert_false(filereadable('Xdir/foo.txt'))
  2324. call assert_false(filereadable('Xdir/[a-1]/foo.txt'))
  2325. if has('unix')
  2326. call mkdir('Xdir/Xdir2', 'p')
  2327. silent !chmod 555 Xdir
  2328. call assert_equal(-1, delete('Xdir/Xdir2', 'rf'))
  2329. call assert_equal(-1, delete('Xdir', 'rf'))
  2330. silent !chmod 755 Xdir
  2331. call assert_equal(0, delete('Xdir', 'rf'))
  2332. endif
  2333. endfunc
  2334. func Test_call()
  2335. call assert_equal(3, call('len', [123]))
  2336. call assert_equal(3, 'len'->call([123]))
  2337. call assert_fails("call call('len', 123)", 'E714:')
  2338. call assert_equal(0, call('', []))
  2339. call assert_equal(0, call('len', v:_null_list))
  2340. function Mylen() dict
  2341. return len(self.data)
  2342. endfunction
  2343. let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")}
  2344. eval mydict.len->call([], mydict)->assert_equal(4)
  2345. call assert_fails("call call('Mylen', [], 0)", 'E1206:')
  2346. call assert_fails('call foo', 'E107:')
  2347. " These once caused a crash.
  2348. " Nvim doesn't have null functions
  2349. " call call(test_null_function(), [])
  2350. " Nvim doesn't have null partials
  2351. " call call(test_null_partial(), [])
  2352. " Nvim doesn't have null functions
  2353. " call assert_fails('call test_null_function()()', 'E1192:')
  2354. " Nvim doesn't have null partials
  2355. " call assert_fails('call test_null_partial()()', 'E117:')
  2356. let lines =<< trim END
  2357. let Time = 'localtime'
  2358. call Time()
  2359. END
  2360. call CheckScriptFailure(lines, 'E1085:')
  2361. endfunc
  2362. func Test_char2nr()
  2363. call assert_equal(12354, char2nr('あ', 1))
  2364. call assert_equal(120, 'x'->char2nr())
  2365. " set encoding=latin1
  2366. call assert_equal(120, 'x'->char2nr())
  2367. set encoding=utf-8
  2368. endfunc
  2369. func Test_charclass()
  2370. call assert_equal(0, charclass(' '))
  2371. call assert_equal(1, charclass('.'))
  2372. call assert_equal(2, charclass('x'))
  2373. call assert_equal(3, charclass("\u203c"))
  2374. " this used to crash vim
  2375. call assert_equal(0, "xxx"[-1]->charclass())
  2376. endfunc
  2377. func Test_eventhandler()
  2378. call assert_equal(0, eventhandler())
  2379. endfunc
  2380. func Test_bufadd_bufload()
  2381. call assert_equal(0, bufexists('someName'))
  2382. let buf = bufadd('someName')
  2383. call assert_notequal(0, buf)
  2384. call assert_equal(1, bufexists('someName'))
  2385. call assert_equal(0, getbufvar(buf, '&buflisted'))
  2386. call assert_equal(0, bufloaded(buf))
  2387. call bufload(buf)
  2388. call assert_equal(1, bufloaded(buf))
  2389. call assert_equal([''], getbufline(buf, 1, '$'))
  2390. let curbuf = bufnr('')
  2391. eval ['some', 'text']->writefile('XotherName')
  2392. let buf = 'XotherName'->bufadd()
  2393. call assert_notequal(0, buf)
  2394. eval 'XotherName'->bufexists()->assert_equal(1)
  2395. call assert_equal(0, getbufvar(buf, '&buflisted'))
  2396. call assert_equal(0, bufloaded(buf))
  2397. eval buf->bufload()
  2398. call assert_equal(1, bufloaded(buf))
  2399. call assert_equal(['some', 'text'], getbufline(buf, 1, '$'))
  2400. call assert_equal(curbuf, bufnr(''))
  2401. let buf1 = bufadd('')
  2402. let buf2 = bufadd('')
  2403. call assert_notequal(0, buf1)
  2404. call assert_notequal(0, buf2)
  2405. call assert_notequal(buf1, buf2)
  2406. call assert_equal(1, bufexists(buf1))
  2407. call assert_equal(1, bufexists(buf2))
  2408. call assert_equal(0, bufloaded(buf1))
  2409. exe 'bwipe ' .. buf1
  2410. call assert_equal(0, bufexists(buf1))
  2411. call assert_equal(1, bufexists(buf2))
  2412. exe 'bwipe ' .. buf2
  2413. call assert_equal(0, bufexists(buf2))
  2414. " When 'buftype' is "nofile" then bufload() does not read the file.
  2415. " Other values too.
  2416. for val in [['nofile', 0],
  2417. \ ['nowrite', 1],
  2418. \ ['acwrite', 1],
  2419. \ ['quickfix', 0],
  2420. \ ['help', 1],
  2421. "\ ['terminal', 0],
  2422. \ ['prompt', 0],
  2423. "\ ['popup', 0],
  2424. \ ]
  2425. bwipe! XotherName
  2426. let buf = bufadd('XotherName')
  2427. call setbufvar(buf, '&bt', val[0])
  2428. call bufload(buf)
  2429. call assert_equal(val[1] ? ['some', 'text'] : [''], getbufline(buf, 1, '$'), val[0])
  2430. endfor
  2431. bwipe someName
  2432. bwipe XotherName
  2433. call assert_equal(0, bufexists('someName'))
  2434. call delete('XotherName')
  2435. endfunc
  2436. func Test_state()
  2437. CheckRunVimInTerminal
  2438. let getstate = ":echo 'state: ' .. g:state .. '; mode: ' .. g:mode\<CR>"
  2439. let lines =<< trim END
  2440. call setline(1, ['one', 'two', 'three'])
  2441. map ;; gg
  2442. set complete=.
  2443. func RunTimer()
  2444. call timer_start(10, {id -> execute('let g:state = state()') .. execute('let g:mode = mode()')})
  2445. endfunc
  2446. au Filetype foobar let g:state = state()|let g:mode = mode()
  2447. END
  2448. call writefile(lines, 'XState')
  2449. let buf = RunVimInTerminal('-S XState', #{rows: 6})
  2450. " Using a ":" command Vim is busy, thus "S" is returned
  2451. call term_sendkeys(buf, ":echo 'state: ' .. state() .. '; mode: ' .. mode()\<CR>")
  2452. call WaitForAssert({-> assert_match('state: S; mode: n', term_getline(buf, 6))}, 1000)
  2453. call term_sendkeys(buf, ":\<CR>")
  2454. " Using a timer callback
  2455. call term_sendkeys(buf, ":call RunTimer()\<CR>")
  2456. call TermWait(buf, 25)
  2457. call term_sendkeys(buf, getstate)
  2458. call WaitForAssert({-> assert_match('state: c; mode: n', term_getline(buf, 6))}, 1000)
  2459. " Halfway a mapping
  2460. call term_sendkeys(buf, ":call RunTimer()\<CR>;")
  2461. call TermWait(buf, 25)
  2462. call term_sendkeys(buf, ";")
  2463. call term_sendkeys(buf, getstate)
  2464. call WaitForAssert({-> assert_match('state: mSc; mode: n', term_getline(buf, 6))}, 1000)
  2465. " An operator is pending
  2466. call term_sendkeys(buf, ":call RunTimer()\<CR>y")
  2467. call TermWait(buf, 25)
  2468. call term_sendkeys(buf, "y")
  2469. call term_sendkeys(buf, getstate)
  2470. call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
  2471. " A register was specified
  2472. call term_sendkeys(buf, ":call RunTimer()\<CR>\"r")
  2473. call TermWait(buf, 25)
  2474. call term_sendkeys(buf, "yy")
  2475. call term_sendkeys(buf, getstate)
  2476. call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000)
  2477. " Insert mode completion (bit slower on Mac)
  2478. call term_sendkeys(buf, ":call RunTimer()\<CR>Got\<C-N>")
  2479. call TermWait(buf, 25)
  2480. call term_sendkeys(buf, "\<Esc>")
  2481. call term_sendkeys(buf, getstate)
  2482. call WaitForAssert({-> assert_match('state: aSc; mode: i', term_getline(buf, 6))}, 1000)
  2483. " Autocommand executing
  2484. call term_sendkeys(buf, ":set filetype=foobar\<CR>")
  2485. call TermWait(buf, 25)
  2486. call term_sendkeys(buf, getstate)
  2487. call WaitForAssert({-> assert_match('state: xS; mode: n', term_getline(buf, 6))}, 1000)
  2488. " Todo: "w" - waiting for ch_evalexpr()
  2489. " messages scrolled
  2490. call term_sendkeys(buf, ":call RunTimer()\<CR>:echo \"one\\ntwo\\nthree\"\<CR>")
  2491. call TermWait(buf, 25)
  2492. call term_sendkeys(buf, "\<CR>")
  2493. call term_sendkeys(buf, getstate)
  2494. call WaitForAssert({-> assert_match('state: Scs; mode: r', term_getline(buf, 6))}, 1000)
  2495. call StopVimInTerminal(buf)
  2496. call delete('XState')
  2497. endfunc
  2498. func Test_range()
  2499. " destructuring
  2500. let [x, y] = range(2)
  2501. call assert_equal([0, 1], [x, y])
  2502. " index
  2503. call assert_equal(4, range(1, 10)[3])
  2504. " add()
  2505. call assert_equal([0, 1, 2, 3], add(range(3), 3))
  2506. call assert_equal([0, 1, 2, [0, 1, 2]], add([0, 1, 2], range(3)))
  2507. call assert_equal([0, 1, 2, [0, 1, 2]], add(range(3), range(3)))
  2508. " append()
  2509. new
  2510. call append('.', range(5))
  2511. call assert_equal(['', '0', '1', '2', '3', '4'], getline(1, '$'))
  2512. bwipe!
  2513. " appendbufline()
  2514. new
  2515. call appendbufline(bufnr(''), '.', range(5))
  2516. call assert_equal(['0', '1', '2', '3', '4', ''], getline(1, '$'))
  2517. bwipe!
  2518. " call()
  2519. func TwoArgs(a, b)
  2520. return [a:a, a:b]
  2521. endfunc
  2522. call assert_equal([0, 1], call('TwoArgs', range(2)))
  2523. " col()
  2524. new
  2525. call setline(1, ['foo', 'bar'])
  2526. call assert_equal(2, col(range(1, 2)))
  2527. bwipe!
  2528. " complete()
  2529. execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>"
  2530. " complete_info()
  2531. execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>\<C-r>=[complete_info(range(5)), ''][1]\<CR>"
  2532. " copy()
  2533. call assert_equal([1, 2, 3], copy(range(1, 3)))
  2534. " count()
  2535. call assert_equal(0, count(range(0), 3))
  2536. call assert_equal(0, count(range(2), 3))
  2537. call assert_equal(1, count(range(5), 3))
  2538. " cursor()
  2539. new
  2540. call setline(1, ['aaa', 'bbb', 'ccc'])
  2541. call cursor(range(1, 2))
  2542. call assert_equal([2, 1], [col('.'), line('.')])
  2543. bwipe!
  2544. " deepcopy()
  2545. call assert_equal([1, 2, 3], deepcopy(range(1, 3)))
  2546. " empty()
  2547. call assert_true(empty(range(0)))
  2548. call assert_false(empty(range(2)))
  2549. " execute()
  2550. new
  2551. call setline(1, ['aaa', 'bbb', 'ccc'])
  2552. call execute(range(3))
  2553. call assert_equal(2, line('.'))
  2554. bwipe!
  2555. " extend()
  2556. call assert_equal([1, 2, 3, 4], extend([1], range(2, 4)))
  2557. call assert_equal([1, 2, 3, 4], extend(range(1, 1), range(2, 4)))
  2558. call assert_equal([1, 2, 3, 4], extend(range(1, 1), [2, 3, 4]))
  2559. " filter()
  2560. call assert_equal([1, 3], filter(range(5), 'v:val % 2'))
  2561. " funcref()
  2562. call assert_equal([0, 1], funcref('TwoArgs', range(2))())
  2563. " function()
  2564. call assert_equal([0, 1], function('TwoArgs', range(2))())
  2565. " garbagecollect()
  2566. let thelist = [1, range(2), 3]
  2567. let otherlist = range(3)
  2568. call test_garbagecollect_now()
  2569. " get()
  2570. call assert_equal(4, get(range(1, 10), 3))
  2571. call assert_equal(-1, get(range(1, 10), 42, -1))
  2572. " index()
  2573. call assert_equal(1, index(range(1, 5), 2))
  2574. call assert_fails("echo index([1, 2], 1, [])", 'E745:')
  2575. " insert()
  2576. call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42))
  2577. call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42, 0))
  2578. call assert_equal([1, 42, 2, 3, 4, 5], insert(range(1, 5), 42, 1))
  2579. call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, 4))
  2580. call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, -1))
  2581. call assert_equal([1, 2, 3, 4, 5, 42], insert(range(1, 5), 42, 5))
  2582. " join()
  2583. call assert_equal('0 1 2 3 4', join(range(5)))
  2584. " json_encode()
  2585. " call assert_equal('[0,1,2,3]', json_encode(range(4)))
  2586. call assert_equal('[0, 1, 2, 3]', json_encode(range(4)))
  2587. " len()
  2588. call assert_equal(0, len(range(0)))
  2589. call assert_equal(2, len(range(2)))
  2590. call assert_equal(5, len(range(0, 12, 3)))
  2591. call assert_equal(4, len(range(3, 0, -1)))
  2592. " list2str()
  2593. call assert_equal('ABC', list2str(range(65, 67)))
  2594. call assert_fails('let s = list2str(5)', 'E474:')
  2595. " lock()
  2596. let thelist = range(5)
  2597. lockvar thelist
  2598. " map()
  2599. call assert_equal([0, 2, 4, 6, 8], map(range(5), 'v:val * 2'))
  2600. " match()
  2601. call assert_equal(3, match(range(5), 3))
  2602. " matchaddpos()
  2603. highlight MyGreenGroup ctermbg=green guibg=green
  2604. call matchaddpos('MyGreenGroup', range(line('.'), line('.')))
  2605. " matchend()
  2606. call assert_equal(4, matchend(range(5), '4'))
  2607. call assert_equal(3, matchend(range(1, 5), '4'))
  2608. call assert_equal(-1, matchend(range(1, 5), '42'))
  2609. " matchstrpos()
  2610. call assert_equal(['4', 4, 0, 1], matchstrpos(range(5), '4'))
  2611. call assert_equal(['4', 3, 0, 1], matchstrpos(range(1, 5), '4'))
  2612. call assert_equal(['', -1, -1, -1], matchstrpos(range(1, 5), '42'))
  2613. " max() reverse()
  2614. call assert_equal(0, max(range(0)))
  2615. call assert_equal(0, max(range(10, 9)))
  2616. call assert_equal(9, max(range(10)))
  2617. call assert_equal(18, max(range(0, 20, 3)))
  2618. call assert_equal(20, max(range(20, 0, -3)))
  2619. call assert_equal(99999, max(range(100000)))
  2620. call assert_equal(99999, max(range(99999, 0, -1)))
  2621. call assert_equal(99999, max(reverse(range(100000))))
  2622. call assert_equal(99999, max(reverse(range(99999, 0, -1))))
  2623. " min() reverse()
  2624. call assert_equal(0, min(range(0)))
  2625. call assert_equal(0, min(range(10, 9)))
  2626. call assert_equal(5, min(range(5, 10)))
  2627. call assert_equal(5, min(range(5, 10, 3)))
  2628. call assert_equal(2, min(range(20, 0, -3)))
  2629. call assert_equal(0, min(range(100000)))
  2630. call assert_equal(0, min(range(99999, 0, -1)))
  2631. call assert_equal(0, min(reverse(range(100000))))
  2632. call assert_equal(0, min(reverse(range(99999, 0, -1))))
  2633. " remove()
  2634. call assert_equal(1, remove(range(1, 10), 0))
  2635. call assert_equal(2, remove(range(1, 10), 1))
  2636. call assert_equal(9, remove(range(1, 10), 8))
  2637. call assert_equal(10, remove(range(1, 10), 9))
  2638. call assert_equal(10, remove(range(1, 10), -1))
  2639. call assert_equal([3, 4, 5], remove(range(1, 10), 2, 4))
  2640. " repeat()
  2641. call assert_equal([0, 1, 2, 0, 1, 2], repeat(range(3), 2))
  2642. call assert_equal([0, 1, 2], repeat(range(3), 1))
  2643. call assert_equal([], repeat(range(3), 0))
  2644. call assert_equal([], repeat(range(5, 4), 2))
  2645. call assert_equal([], repeat(range(5, 4), 0))
  2646. " reverse()
  2647. call assert_equal([2, 1, 0], reverse(range(3)))
  2648. call assert_equal([0, 1, 2, 3], reverse(range(3, 0, -1)))
  2649. call assert_equal([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], reverse(range(10)))
  2650. call assert_equal([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], reverse(range(10, 20)))
  2651. call assert_equal([16, 13, 10], reverse(range(10, 18, 3)))
  2652. call assert_equal([19, 16, 13, 10], reverse(range(10, 19, 3)))
  2653. call assert_equal([19, 16, 13, 10], reverse(range(10, 20, 3)))
  2654. call assert_equal([11, 14, 17, 20], reverse(range(20, 10, -3)))
  2655. call assert_equal([], reverse(range(0)))
  2656. " TODO: setpos()
  2657. " new
  2658. " call setline(1, repeat([''], bufnr('')))
  2659. " call setline(bufnr('') + 1, repeat('x', bufnr('') * 2 + 6))
  2660. " call setpos('x', range(bufnr(''), bufnr('') + 3))
  2661. " bwipe!
  2662. " setreg()
  2663. call setreg('a', range(3))
  2664. call assert_equal("0\n1\n2\n", getreg('a'))
  2665. " settagstack()
  2666. call settagstack(1, #{items : range(4)})
  2667. " sign_define()
  2668. call assert_fails("call sign_define(range(5))", "E715:")
  2669. call assert_fails("call sign_placelist(range(5))", "E715:")
  2670. " sign_undefine()
  2671. " call assert_fails("call sign_undefine(range(5))", "E908:")
  2672. call assert_fails("call sign_undefine(range(5))", "E155:")
  2673. " sign_unplacelist()
  2674. call assert_fails("call sign_unplacelist(range(5))", "E715:")
  2675. " sort()
  2676. call assert_equal([0, 1, 2, 3, 4, 5], sort(range(5, 0, -1)))
  2677. " string()
  2678. call assert_equal('[0, 1, 2, 3, 4]', string(range(5)))
  2679. " taglist() with 'tagfunc'
  2680. func TagFunc(pattern, flags, info)
  2681. return range(10)
  2682. endfunc
  2683. set tagfunc=TagFunc
  2684. call assert_fails("call taglist('asdf')", 'E987:')
  2685. set tagfunc=
  2686. " term_start()
  2687. if has('terminal') && has('termguicolors')
  2688. call assert_fails('call term_start(range(3, 4))', 'E474:')
  2689. let g:terminal_ansi_colors = range(16)
  2690. if has('win32')
  2691. let cmd = "cmd /D /c dir"
  2692. else
  2693. let cmd = "ls"
  2694. endif
  2695. call assert_fails('call term_start("' .. cmd .. '", #{term_finish: "close"})', 'E475:')
  2696. unlet g:terminal_ansi_colors
  2697. endif
  2698. " type()
  2699. call assert_equal(v:t_list, type(range(5)))
  2700. " uniq()
  2701. call assert_equal([0, 1, 2, 3, 4], uniq(range(5)))
  2702. " errors
  2703. call assert_fails('let x=range(2, 8, 0)', 'E726:')
  2704. call assert_fails('let x=range(3, 1)', 'E727:')
  2705. call assert_fails('let x=range(1, 3, -2)', 'E727:')
  2706. call assert_fails('let x=range([])', 'E745:')
  2707. call assert_fails('let x=range(1, [])', 'E745:')
  2708. call assert_fails('let x=range(1, 4, [])', 'E745:')
  2709. endfunc
  2710. func Test_garbagecollect_now_fails()
  2711. let v:testing = 0
  2712. call assert_fails('call test_garbagecollect_now()', 'E1142:')
  2713. let v:testing = 1
  2714. endfunc
  2715. " Test for echo highlighting
  2716. func Test_echohl()
  2717. echohl Search
  2718. echo 'Vim'
  2719. call assert_equal('Vim', Screenline(&lines))
  2720. " TODO: How to check the highlight group used by echohl?
  2721. " ScreenAttrs() returns all zeros.
  2722. echohl None
  2723. endfunc
  2724. " Test for the eval() function
  2725. func Test_eval()
  2726. call assert_fails("call eval('5 a')", 'E488:')
  2727. endfunc
  2728. " Test for the keytrans() function
  2729. func Test_keytrans()
  2730. call assert_equal('<Space>', keytrans(' '))
  2731. call assert_equal('<lt>', keytrans('<'))
  2732. call assert_equal('<lt>Tab>', keytrans('<Tab>'))
  2733. call assert_equal('<Tab>', keytrans("\<Tab>"))
  2734. call assert_equal('<C-V>', keytrans("\<C-V>"))
  2735. call assert_equal('<BS>', keytrans("\<BS>"))
  2736. call assert_equal('<Home>', keytrans("\<Home>"))
  2737. call assert_equal('<C-Home>', keytrans("\<C-Home>"))
  2738. call assert_equal('<M-Home>', keytrans("\<M-Home>"))
  2739. call assert_equal('<C-Space>', keytrans("\<C-Space>"))
  2740. call assert_equal('<M-Space>', keytrans("\<*M-Space>"))
  2741. call assert_equal('<M-x>', "\<*M-x>"->keytrans())
  2742. call assert_equal('<C-I>', "\<*C-I>"->keytrans())
  2743. call assert_equal('<S-3>', "\<*S-3>"->keytrans())
  2744. call assert_equal('π', 'π'->keytrans())
  2745. call assert_equal('<M-π>', "\<M-π>"->keytrans())
  2746. call assert_equal('ě', 'ě'->keytrans())
  2747. call assert_equal('<M-ě>', "\<M-ě>"->keytrans())
  2748. call assert_equal('', ''->keytrans())
  2749. call assert_equal('', v:_null_string->keytrans())
  2750. call assert_fails('call keytrans(1)', 'E1174:')
  2751. call assert_fails('call keytrans()', 'E119:')
  2752. endfunc
  2753. " Test for the nr2char() function
  2754. func Test_nr2char()
  2755. " set encoding=latin1
  2756. call assert_equal('@', nr2char(64))
  2757. set encoding=utf8
  2758. call assert_equal('a', nr2char(97, 1))
  2759. call assert_equal('a', nr2char(97, 0))
  2760. call assert_equal("\x80\xfc\b" .. nr2char(0x100000), eval('"\<M-' .. nr2char(0x100000) .. '>"'))
  2761. call assert_equal("\x80\xfc\b" .. nr2char(0x40000000), eval('"\<M-' .. nr2char(0x40000000) .. '>"'))
  2762. endfunc
  2763. " Test for screenattr(), screenchar() and screenchars() functions
  2764. func Test_screen_functions()
  2765. call assert_equal(-1, screenattr(-1, -1))
  2766. call assert_equal(-1, screenchar(-1, -1))
  2767. call assert_equal([], screenchars(-1, -1))
  2768. " Run this in a separate Vim instance to avoid messing up.
  2769. let after =<< trim [CODE]
  2770. scriptencoding utf-8
  2771. call setline(1, '口')
  2772. redraw
  2773. call assert_equal(0, screenattr(1, 1))
  2774. call assert_equal(char2nr('口'), screenchar(1, 1))
  2775. call assert_equal([char2nr('口')], screenchars(1, 1))
  2776. call assert_equal('口', screenstring(1, 1))
  2777. call writefile(v:errors, 'Xresult')
  2778. qall!
  2779. [CODE]
  2780. let encodings = ['utf-8', 'cp932', 'cp936', 'cp949', 'cp950']
  2781. if !has('win32')
  2782. let encodings += ['euc-jp']
  2783. endif
  2784. if has('nvim')
  2785. let encodings = ['utf-8']
  2786. endif
  2787. for enc in encodings
  2788. let msg = 'enc=' .. enc
  2789. if RunVim([], after, $'--clean --cmd "set encoding={enc}"')
  2790. call assert_equal([], readfile('Xresult'), msg)
  2791. endif
  2792. call delete('Xresult')
  2793. endfor
  2794. endfunc
  2795. " Test for getcurpos() and setpos()
  2796. func Test_getcurpos_setpos()
  2797. new
  2798. call setline(1, ['012345678', '012345678'])
  2799. normal gg6l
  2800. let sp = getcurpos()
  2801. normal 0
  2802. call setpos('.', sp)
  2803. normal jyl
  2804. call assert_equal('6', @")
  2805. call assert_equal(-1, setpos('.', v:_null_list))
  2806. call assert_equal(-1, setpos('.', {}))
  2807. let winid = win_getid()
  2808. normal G$
  2809. let pos = getcurpos()
  2810. wincmd w
  2811. call assert_equal(pos, getcurpos(winid))
  2812. wincmd w
  2813. close!
  2814. call assert_equal(getcurpos(), getcurpos(0))
  2815. call assert_equal([0, 0, 0, 0, 0], getcurpos(-1))
  2816. call assert_equal([0, 0, 0, 0, 0], getcurpos(1999))
  2817. endfunc
  2818. func Test_getmousepos()
  2819. enew!
  2820. call setline(1, "\t\t\t1234")
  2821. call Ntest_setmouse(1, 1)
  2822. call assert_equal(#{
  2823. \ screenrow: 1,
  2824. \ screencol: 1,
  2825. \ winid: win_getid(),
  2826. \ winrow: 1,
  2827. \ wincol: 1,
  2828. \ line: 1,
  2829. \ column: 1,
  2830. \ coladd: 0,
  2831. \ }, getmousepos())
  2832. call Ntest_setmouse(1, 2)
  2833. call assert_equal(#{
  2834. \ screenrow: 1,
  2835. \ screencol: 2,
  2836. \ winid: win_getid(),
  2837. \ winrow: 1,
  2838. \ wincol: 2,
  2839. \ line: 1,
  2840. \ column: 1,
  2841. \ coladd: 1,
  2842. \ }, getmousepos())
  2843. call Ntest_setmouse(1, 8)
  2844. call assert_equal(#{
  2845. \ screenrow: 1,
  2846. \ screencol: 8,
  2847. \ winid: win_getid(),
  2848. \ winrow: 1,
  2849. \ wincol: 8,
  2850. \ line: 1,
  2851. \ column: 1,
  2852. \ coladd: 7,
  2853. \ }, getmousepos())
  2854. call Ntest_setmouse(1, 9)
  2855. call assert_equal(#{
  2856. \ screenrow: 1,
  2857. \ screencol: 9,
  2858. \ winid: win_getid(),
  2859. \ winrow: 1,
  2860. \ wincol: 9,
  2861. \ line: 1,
  2862. \ column: 2,
  2863. \ coladd: 0,
  2864. \ }, getmousepos())
  2865. call Ntest_setmouse(1, 12)
  2866. call assert_equal(#{
  2867. \ screenrow: 1,
  2868. \ screencol: 12,
  2869. \ winid: win_getid(),
  2870. \ winrow: 1,
  2871. \ wincol: 12,
  2872. \ line: 1,
  2873. \ column: 2,
  2874. \ coladd: 3,
  2875. \ }, getmousepos())
  2876. call Ntest_setmouse(1, 25)
  2877. call assert_equal(#{
  2878. \ screenrow: 1,
  2879. \ screencol: 25,
  2880. \ winid: win_getid(),
  2881. \ winrow: 1,
  2882. \ wincol: 25,
  2883. \ line: 1,
  2884. \ column: 4,
  2885. \ coladd: 0,
  2886. \ }, getmousepos())
  2887. call Ntest_setmouse(1, 28)
  2888. call assert_equal(#{
  2889. \ screenrow: 1,
  2890. \ screencol: 28,
  2891. \ winid: win_getid(),
  2892. \ winrow: 1,
  2893. \ wincol: 28,
  2894. \ line: 1,
  2895. \ column: 7,
  2896. \ coladd: 0,
  2897. \ }, getmousepos())
  2898. call Ntest_setmouse(1, 29)
  2899. call assert_equal(#{
  2900. \ screenrow: 1,
  2901. \ screencol: 29,
  2902. \ winid: win_getid(),
  2903. \ winrow: 1,
  2904. \ wincol: 29,
  2905. \ line: 1,
  2906. \ column: 8,
  2907. \ coladd: 0,
  2908. \ }, getmousepos())
  2909. call Ntest_setmouse(1, 50)
  2910. call assert_equal(#{
  2911. \ screenrow: 1,
  2912. \ screencol: 50,
  2913. \ winid: win_getid(),
  2914. \ winrow: 1,
  2915. \ wincol: 50,
  2916. \ line: 1,
  2917. \ column: 8,
  2918. \ coladd: 21,
  2919. \ }, getmousepos())
  2920. " If the mouse is positioned past the last buffer line, "line" and "column"
  2921. " should act like it's positioned on the last buffer line.
  2922. call Ntest_setmouse(2, 25)
  2923. call assert_equal(#{
  2924. \ screenrow: 2,
  2925. \ screencol: 25,
  2926. \ winid: win_getid(),
  2927. \ winrow: 2,
  2928. \ wincol: 25,
  2929. \ line: 1,
  2930. \ column: 4,
  2931. \ coladd: 0,
  2932. \ }, getmousepos())
  2933. call Ntest_setmouse(2, 50)
  2934. call assert_equal(#{
  2935. \ screenrow: 2,
  2936. \ screencol: 50,
  2937. \ winid: win_getid(),
  2938. \ winrow: 2,
  2939. \ wincol: 50,
  2940. \ line: 1,
  2941. \ column: 8,
  2942. \ coladd: 21,
  2943. \ }, getmousepos())
  2944. 30vnew
  2945. setlocal smoothscroll number
  2946. call setline(1, join(range(100)))
  2947. exe "normal! \<C-E>"
  2948. call Ntest_setmouse(1, 5)
  2949. call assert_equal(#{
  2950. \ screenrow: 1,
  2951. \ screencol: 5,
  2952. \ winid: win_getid(),
  2953. \ winrow: 1,
  2954. \ wincol: 5,
  2955. \ line: 1,
  2956. \ column: 27,
  2957. \ coladd: 0,
  2958. \ }, getmousepos())
  2959. call Ntest_setmouse(2, 5)
  2960. call assert_equal(#{
  2961. \ screenrow: 2,
  2962. \ screencol: 5,
  2963. \ winid: win_getid(),
  2964. \ winrow: 2,
  2965. \ wincol: 5,
  2966. \ line: 1,
  2967. \ column: 53,
  2968. \ coladd: 0,
  2969. \ }, getmousepos())
  2970. exe "normal! \<C-E>"
  2971. call Ntest_setmouse(1, 5)
  2972. call assert_equal(#{
  2973. \ screenrow: 1,
  2974. \ screencol: 5,
  2975. \ winid: win_getid(),
  2976. \ winrow: 1,
  2977. \ wincol: 5,
  2978. \ line: 1,
  2979. \ column: 53,
  2980. \ coladd: 0,
  2981. \ }, getmousepos())
  2982. call Ntest_setmouse(2, 5)
  2983. call assert_equal(#{
  2984. \ screenrow: 2,
  2985. \ screencol: 5,
  2986. \ winid: win_getid(),
  2987. \ winrow: 2,
  2988. \ wincol: 5,
  2989. \ line: 1,
  2990. \ column: 79,
  2991. \ coladd: 0,
  2992. \ }, getmousepos())
  2993. vert resize 4
  2994. call Ntest_setmouse(2, 2)
  2995. " This used to crash Vim
  2996. call assert_equal(#{
  2997. \ screenrow: 2,
  2998. \ screencol: 2,
  2999. \ winid: win_getid(),
  3000. \ winrow: 2,
  3001. \ wincol: 2,
  3002. \ line: 1,
  3003. \ column: 53,
  3004. \ coladd: 0,
  3005. \ }, getmousepos())
  3006. bwipe!
  3007. bwipe!
  3008. endfunc
  3009. " Test for glob()
  3010. func Test_glob()
  3011. call assert_equal('', glob(v:_null_string))
  3012. call assert_equal('', globpath(v:_null_string, v:_null_string))
  3013. call assert_fails("let x = globpath(&rtp, 'syntax/c.vim', [])", 'E745:')
  3014. call writefile([], 'Xglob1')
  3015. call writefile([], 'XGLOB2')
  3016. set wildignorecase
  3017. " Sort output of glob() otherwise we end up with different
  3018. " ordering depending on whether file system is case-sensitive.
  3019. call assert_equal(['XGLOB2', 'Xglob1'], sort(glob('Xglob[12]', 0, 1)))
  3020. " wildignorecase shall be applied even when the pattern contains no wildcards.
  3021. call assert_equal('XGLOB2', glob('xglob2'))
  3022. set wildignorecase&
  3023. call delete('Xglob1')
  3024. call delete('XGLOB2')
  3025. call assert_fails("call glob('*', 0, {})", 'E728:')
  3026. endfunc
  3027. func Test_glob2()
  3028. call mkdir('[XglobDir]', 'R')
  3029. call mkdir('abc[glob]def', 'R')
  3030. call writefile(['glob'], '[XglobDir]/Xglob')
  3031. call writefile(['glob'], 'abc[glob]def/Xglob')
  3032. if has("unix")
  3033. call assert_equal([], (glob('[XglobDir]/*', 0, 1)))
  3034. call assert_equal([], (glob('abc[glob]def/*', 0, 1)))
  3035. call assert_equal(['[XglobDir]/Xglob'], (glob('\[XglobDir]/*', 0, 1)))
  3036. call assert_equal(['abc[glob]def/Xglob'], (glob('abc\[glob]def/*', 0, 1)))
  3037. elseif has("win32")
  3038. let _sl=&shellslash
  3039. call assert_equal([], (glob('[XglobDir]\*', 0, 1)))
  3040. call assert_equal([], (glob('abc[glob]def\*', 0, 1)))
  3041. call assert_equal([], (glob('\[XglobDir]\*', 0, 1)))
  3042. call assert_equal([], (glob('abc\[glob]def\*', 0, 1)))
  3043. set noshellslash
  3044. call assert_equal(['[XglobDir]\Xglob'], (glob('[[]XglobDir]/*', 0, 1)))
  3045. call assert_equal(['abc[glob]def\Xglob'], (glob('abc[[]glob]def/*', 0, 1)))
  3046. set shellslash
  3047. call assert_equal(['[XglobDir]/Xglob'], (glob('[[]XglobDir]/*', 0, 1)))
  3048. call assert_equal(['abc[glob]def/Xglob'], (glob('abc[[]glob]def/*', 0, 1)))
  3049. let &shellslash=_sl
  3050. endif
  3051. endfunc
  3052. func Test_glob_symlinks()
  3053. call writefile([], 'Xglob1')
  3054. if has("win32")
  3055. silent !mklink XglobBad DoesNotExist
  3056. if v:shell_error
  3057. throw 'Skipped: cannot create symlinks'
  3058. endif
  3059. silent !mklink XglobOk Xglob1
  3060. else
  3061. silent !ln -s DoesNotExist XglobBad
  3062. silent !ln -s Xglob1 XglobOk
  3063. endif
  3064. " The broken symlink is excluded when alllinks is false.
  3065. call assert_equal(['Xglob1', 'XglobBad', 'XglobOk'], sort(glob('Xglob*', 0, 1, 1)))
  3066. call assert_equal(['Xglob1', 'XglobOk'], sort(glob('Xglob*', 0, 1, 0)))
  3067. call delete('Xglob1')
  3068. call delete('XglobBad')
  3069. call delete('XglobOk')
  3070. endfunc
  3071. " Test for browse()
  3072. func Test_browse()
  3073. CheckFeature browse
  3074. call assert_fails('call browse([], "open", "x", "a.c")', 'E745:')
  3075. endfunc
  3076. " Test for browsedir()
  3077. func Test_browsedir()
  3078. CheckFeature browse
  3079. call assert_fails('call browsedir("open", [])', 'E730:')
  3080. endfunc
  3081. func HasDefault(msg = 'msg')
  3082. return a:msg
  3083. endfunc
  3084. func Test_default_arg_value()
  3085. call assert_equal('msg', HasDefault())
  3086. endfunc
  3087. " Test for gettext()
  3088. func Test_gettext()
  3089. call assert_fails('call gettext(1)', 'E1174:')
  3090. endfunc
  3091. func Test_builtin_check()
  3092. call assert_fails('let g:["trim"] = {x -> " " .. x}', 'E704:')
  3093. call assert_fails('let g:.trim = {x -> " " .. x}', 'E704:')
  3094. call assert_fails('let l:["trim"] = {x -> " " .. x}', 'E704:')
  3095. call assert_fails('let l:.trim = {x -> " " .. x}', 'E704:')
  3096. let lines =<< trim END
  3097. vim9script
  3098. var trim = (x) => " " .. x
  3099. END
  3100. call CheckScriptFailure(lines, 'E704:')
  3101. call assert_fails('call extend(g:, #{foo: { -> "foo" }})', 'E704:')
  3102. let g:bar = 123
  3103. call extend(g:, #{bar: { -> "foo" }}, "keep")
  3104. call assert_fails('call extend(g:, #{bar: { -> "foo" }}, "force")', 'E704:')
  3105. unlet g:bar
  3106. call assert_fails('call extend(l:, #{foo: { -> "foo" }})', 'E704:')
  3107. let bar = 123
  3108. call extend(l:, #{bar: { -> "foo" }}, "keep")
  3109. call assert_fails('call extend(l:, #{bar: { -> "foo" }}, "force")', 'E704:')
  3110. unlet bar
  3111. call assert_fails('call extend(g:, #{foo: function("extend")})', 'E704:')
  3112. let g:bar = 123
  3113. call extend(g:, #{bar: function("extend")}, "keep")
  3114. call assert_fails('call extend(g:, #{bar: function("extend")}, "force")', 'E704:')
  3115. unlet g:bar
  3116. call assert_fails('call extend(l:, #{foo: function("extend")})', 'E704:')
  3117. let bar = 123
  3118. call extend(l:, #{bar: function("extend")}, "keep")
  3119. call assert_fails('call extend(l:, #{bar: function("extend")}, "force")', 'E704:')
  3120. unlet bar
  3121. endfunc
  3122. " Test for isabsolutepath()
  3123. func Test_isabsolutepath()
  3124. call assert_false(isabsolutepath(''))
  3125. call assert_false(isabsolutepath('.'))
  3126. call assert_false(isabsolutepath('../Foo'))
  3127. call assert_false(isabsolutepath('Foo/'))
  3128. if has('win32')
  3129. call assert_true(isabsolutepath('A:\'))
  3130. call assert_true(isabsolutepath('A:\Foo'))
  3131. call assert_true(isabsolutepath('A:/Foo'))
  3132. call assert_false(isabsolutepath('A:Foo'))
  3133. call assert_false(isabsolutepath('\Windows'))
  3134. call assert_true(isabsolutepath('\\Server2\Share\Test\Foo.txt'))
  3135. else
  3136. call assert_true(isabsolutepath('/'))
  3137. call assert_true(isabsolutepath('/usr/share/'))
  3138. endif
  3139. endfunc
  3140. " Test for exepath()
  3141. func Test_exepath()
  3142. if has('win32')
  3143. call assert_notequal(exepath('cmd'), '')
  3144. let oldNoDefaultCurrentDirectoryInExePath = $NoDefaultCurrentDirectoryInExePath
  3145. call writefile(['@echo off', 'echo Evil'], 'vim-test-evil.bat')
  3146. let $NoDefaultCurrentDirectoryInExePath = ''
  3147. call assert_notequal(exepath("vim-test-evil.bat"), '')
  3148. let $NoDefaultCurrentDirectoryInExePath = '1'
  3149. call assert_equal(exepath("vim-test-evil.bat"), '')
  3150. let $NoDefaultCurrentDirectoryInExePath = oldNoDefaultCurrentDirectoryInExePath
  3151. call delete('vim-test-evil.bat')
  3152. else
  3153. call assert_notequal(exepath('sh'), '')
  3154. endif
  3155. endfunc
  3156. " Test for virtcol()
  3157. func Test_virtcol()
  3158. new
  3159. call setline(1, "the\tquick\tbrown\tfox")
  3160. norm! 4|
  3161. call assert_equal(8, virtcol('.'))
  3162. call assert_equal(8, virtcol('.', v:false))
  3163. call assert_equal([4, 8], virtcol('.', v:true))
  3164. let w = winwidth(0)
  3165. call setline(2, repeat('a', w + 2))
  3166. let win_nosbr = win_getid()
  3167. split
  3168. setlocal showbreak=!!
  3169. let win_sbr = win_getid()
  3170. call assert_equal([w, w], virtcol([2, w], v:true, win_nosbr))
  3171. call assert_equal([w + 1, w + 1], virtcol([2, w + 1], v:true, win_nosbr))
  3172. call assert_equal([w + 2, w + 2], virtcol([2, w + 2], v:true, win_nosbr))
  3173. call assert_equal([w, w], virtcol([2, w], v:true, win_sbr))
  3174. call assert_equal([w + 3, w + 3], virtcol([2, w + 1], v:true, win_sbr))
  3175. call assert_equal([w + 4, w + 4], virtcol([2, w + 2], v:true, win_sbr))
  3176. close
  3177. call assert_equal(0, virtcol(''))
  3178. call assert_equal([0, 0], virtcol('', v:true))
  3179. call assert_equal(0, virtcol('.', v:false, 5001))
  3180. call assert_equal([0, 0], virtcol('.', v:true, 5001))
  3181. bwipe!
  3182. endfunc
  3183. func Test_delfunc_while_listing()
  3184. CheckRunVimInTerminal
  3185. let lines =<< trim END
  3186. set nocompatible
  3187. for i in range(1, 999)
  3188. exe 'func ' .. 'MyFunc' .. i .. '()'
  3189. endfunc
  3190. endfor
  3191. au CmdlineLeave : call timer_start(0, {-> execute('delfunc MyFunc622')})
  3192. END
  3193. call writefile(lines, 'Xfunctionclear', 'D')
  3194. let buf = RunVimInTerminal('-S Xfunctionclear', {'rows': 12})
  3195. " This was using freed memory. The height of the terminal must be so that
  3196. " the next function to be listed with "j" is the one that is deleted in the
  3197. " timer callback, tricky!
  3198. call term_sendkeys(buf, ":func /MyFunc\<CR>")
  3199. call TermWait(buf, 50)
  3200. call term_sendkeys(buf, "j")
  3201. call TermWait(buf, 50)
  3202. call term_sendkeys(buf, "\<CR>")
  3203. call StopVimInTerminal(buf)
  3204. endfunc
  3205. " Test for the reverse() function with a string
  3206. func Test_string_reverse()
  3207. let lines =<< trim END
  3208. call assert_equal('', reverse(v:_null_string))
  3209. for [s1, s2] in [['', ''], ['a', 'a'], ['ab', 'ba'], ['abc', 'cba'],
  3210. \ ['abcd', 'dcba'], ['«-«-»-»', '»-»-«-«'],
  3211. \ ['🇦', '🇦'], ['🇦🇧', '🇦🇧'], ['🇦🇧🇨', '🇨🇦🇧'],
  3212. \ ['🇦«🇧-🇨»🇩', '🇩»🇨-🇧«🇦']]
  3213. call assert_equal(s2, reverse(s1))
  3214. endfor
  3215. END
  3216. call CheckLegacyAndVim9Success(lines)
  3217. " test in latin1 encoding
  3218. let save_enc = &encoding
  3219. " set encoding=latin1
  3220. call assert_equal('dcba', reverse('abcd'))
  3221. let &encoding = save_enc
  3222. endfunc
  3223. func Test_fullcommand()
  3224. " this used to crash vim
  3225. call assert_equal('', fullcommand(10))
  3226. endfunc
  3227. " Test for glob() with shell special patterns
  3228. func Test_glob_extended_bash()
  3229. CheckExecutable bash
  3230. CheckNotMSWindows
  3231. CheckNotMac " The default version of bash is old on macOS.
  3232. let _shell = &shell
  3233. set shell=bash
  3234. call mkdir('Xtestglob/foo/bar/src', 'p')
  3235. call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
  3236. call writefile([], 'Xtestglob/foo/bar/src/foo.h')
  3237. call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
  3238. " Sort output of glob() otherwise we end up with different
  3239. " ordering depending on whether file system is case-sensitive.
  3240. let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h']
  3241. call assert_equal(expected, sort(glob('Xtestglob/**/foo.{h,cpp}', 0, 1)))
  3242. call delete('Xtestglob', 'rf')
  3243. let &shell=_shell
  3244. endfunc
  3245. " Test for glob() with extended patterns (MS-Windows)
  3246. " Vim doesn't use 'shell' to expand wildcards on MS-Windows.
  3247. " Unlike bash, it doesn't support {,} expansion.
  3248. func Test_glob_extended_mswin()
  3249. CheckMSWindows
  3250. call mkdir('Xtestglob/foo/bar/src', 'p')
  3251. call writefile([], 'Xtestglob/foo/bar/src/foo.sh')
  3252. call writefile([], 'Xtestglob/foo/bar/src/foo.h')
  3253. call writefile([], 'Xtestglob/foo/bar/src/foo.cpp')
  3254. " Sort output of glob() otherwise we end up with different
  3255. " ordering depending on whether file system is case-sensitive.
  3256. let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h', 'Xtestglob/foo/bar/src/foo.sh']
  3257. call assert_equal(expected, sort(glob('Xtestglob/**/foo.*', 0, 1)))
  3258. call delete('Xtestglob', 'rf')
  3259. endfunc
  3260. " Tests for the slice() function.
  3261. func Test_slice()
  3262. let lines =<< trim END
  3263. call assert_equal([1, 2, 3, 4, 5], slice(range(6), 1))
  3264. call assert_equal([2, 3, 4, 5], slice(range(6), 2))
  3265. call assert_equal([2, 3], slice(range(6), 2, 4))
  3266. call assert_equal([0, 1, 2, 3], slice(range(6), 0, 4))
  3267. call assert_equal([1, 2, 3], slice(range(6), 1, 4))
  3268. call assert_equal([1, 2, 3, 4], slice(range(6), 1, -1))
  3269. call assert_equal([1, 2], slice(range(6), 1, -3))
  3270. call assert_equal([1], slice(range(6), 1, -4))
  3271. call assert_equal([], slice(range(6), 1, -5))
  3272. call assert_equal([], slice(range(6), 1, -6))
  3273. call assert_equal(0z1122334455, slice(0z001122334455, 1))
  3274. call assert_equal(0z22334455, slice(0z001122334455, 2))
  3275. call assert_equal(0z2233, slice(0z001122334455, 2, 4))
  3276. call assert_equal(0z00112233, slice(0z001122334455, 0, 4))
  3277. call assert_equal(0z112233, slice(0z001122334455, 1, 4))
  3278. call assert_equal(0z11223344, slice(0z001122334455, 1, -1))
  3279. call assert_equal(0z1122, slice(0z001122334455, 1, -3))
  3280. call assert_equal(0z11, slice(0z001122334455, 1, -4))
  3281. call assert_equal(0z, slice(0z001122334455, 1, -5))
  3282. call assert_equal(0z, slice(0z001122334455, 1, -6))
  3283. call assert_equal('12345', slice('012345', 1))
  3284. call assert_equal('2345', slice('012345', 2))
  3285. call assert_equal('23', slice('012345', 2, 4))
  3286. call assert_equal('0123', slice('012345', 0, 4))
  3287. call assert_equal('123', slice('012345', 1, 4))
  3288. call assert_equal('1234', slice('012345', 1, -1))
  3289. call assert_equal('12', slice('012345', 1, -3))
  3290. call assert_equal('1', slice('012345', 1, -4))
  3291. call assert_equal('', slice('012345', 1, -5))
  3292. call assert_equal('', slice('012345', 1, -6))
  3293. #" Composing chars are treated as a part of the preceding base char.
  3294. call assert_equal('β̳́γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1))
  3295. call assert_equal('γ̳̂δ̳̃ε̳̄ζ̳̅', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2))
  3296. call assert_equal('γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(2, 4))
  3297. call assert_equal('ὰ̳β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(0, 4))
  3298. call assert_equal('β̳́γ̳̂δ̳̃', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, 4))
  3299. call assert_equal('β̳́γ̳̂δ̳̃ε̳̄', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -1))
  3300. call assert_equal('β̳́γ̳̂', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -3))
  3301. call assert_equal('β̳́', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -4))
  3302. call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -5))
  3303. call assert_equal('', 'ὰ̳β̳́γ̳̂δ̳̃ε̳̄ζ̳̅'->slice(1, -6))
  3304. END
  3305. call CheckLegacyAndVim9Success(lines)
  3306. call assert_equal(0, slice(v:true, 1))
  3307. endfunc
  3308. " vim: shiftwidth=2 sts=2 expandtab