lua.txt 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663
  1. *lua.txt* Nvim
  2. NVIM REFERENCE MANUAL
  3. Lua engine *lua* *Lua*
  4. Type |gO| to see the table of contents.
  5. ==============================================================================
  6. INTRODUCTION *lua-intro*
  7. The Lua 5.1 script engine is builtin and always available. Try this command to
  8. get an idea of what lurks beneath: >vim
  9. :lua vim.print(package.loaded)
  10. Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the
  11. "editor stdlib" (|vimscript-functions| + |Ex-commands|) and the |API|, all of
  12. which can be used from Lua code (|lua-vimscript| |vim.api|). These three
  13. namespaces form the Nvim programming interface.
  14. Lua plugins and user config are automatically discovered and loaded, just like
  15. Vimscript. See |lua-guide| for practical guidance.
  16. You can also run Lua scripts from your shell using the |-l| argument: >
  17. nvim -l foo.lua [args...]
  18. <
  19. *lua-compat*
  20. Lua 5.1 is the permanent interface for Nvim Lua. Plugins should target Lua 5.1
  21. as specified in |luaref|; later versions (which are essentially different,
  22. incompatible, dialects) are not supported. This includes extensions such as
  23. `goto` that some Lua 5.1 interpreters like LuaJIT may support.
  24. *lua-luajit*
  25. While Nvim officially only requires Lua 5.1 support, it should be built with
  26. LuaJIT or a compatible fork on supported platforms for performance reasons.
  27. LuaJIT also comes with useful extensions such as `ffi`, |lua-profile|, and
  28. enhanced standard library functions; these cannot be assumed to be available,
  29. and Lua code in |init.lua| or plugins should check the `jit` global variable
  30. before using them: >lua
  31. if jit then
  32. -- code for luajit
  33. else
  34. -- code for plain lua 5.1
  35. end
  36. <
  37. *lua-bit*
  38. One exception is the LuaJIT `bit` extension, which is always available: when
  39. built with PUC Lua, Nvim includes a fallback implementation which provides
  40. `require("bit")`.
  41. *lua-profile*
  42. If Nvim is built with LuaJIT, Lua code can be profiled via >lua
  43. -- Start a profiling session:
  44. require('jit.p').start('ri1', '/tmp/profile')
  45. -- Perform arbitrary tasks (use plugins, scripts, etc.) ...
  46. -- Stop the session. Profile is written to /tmp/profile.
  47. require('jit.p').stop()
  48. See https://luajit.org/ext_profiler.html or the `p.lua` source for details: >
  49. :lua vim.cmd.edit(package.searchpath('jit.p', package.path))
  50. ==============================================================================
  51. LUA CONCEPTS AND IDIOMS *lua-concepts*
  52. Lua is very simple, and _consistent_: while there are some quirks, once you
  53. internalize those quirks, everything works the same everywhere. Scopes
  54. (closures) in particular are very consistent, unlike JavaScript or most other
  55. languages.
  56. Lua has three fundamental mechanisms—one for "each major aspect of
  57. programming": tables, closures, and coroutines.
  58. https://www.lua.org/doc/cacm2018.pdf
  59. - Tables are the "object" or container datastructure: they represent both
  60. lists and maps, you can extend them to represent your own datatypes and
  61. change their behavior using |metatable|s (like Python's "datamodel").
  62. - EVERY scope in Lua is a closure: a function is a closure, a module is
  63. a closure, a `do` block (|lua-do|) is a closure--and they all work the same.
  64. A Lua module is literally just a big closure discovered on the "path"
  65. (where your modules are found: |package.cpath|).
  66. - Stackful coroutines enable cooperative multithreading, generators, and
  67. versatile control for both Lua and its host (Nvim).
  68. *lua-error-handling*
  69. Lua functions may throw |lua-errors| for exceptional (unexpected) failures,
  70. which you can handle with |pcall()|.
  71. *lua-result-or-message*
  72. When failure is normal and expected, it's idiomatic to return `nil` which
  73. signals to the caller that failure is not "exceptional" and must be handled.
  74. This "result-or-message" pattern is expressed as the multi-value return type
  75. `any|nil,nil|string`, or in LuaLS notation: >
  76. ---@return any|nil # result on success, nil on failure.
  77. ---@return nil|string # nil on success, error message on failure.
  78. <
  79. Examples of the "result-or-message" pattern:
  80. - |vim.ui.open()|
  81. - |io.open()|
  82. - |luv-error-handling|
  83. When a caller can't proceed on failure, it's idiomatic to `assert()` the
  84. "result-or-message" result: >lua
  85. local value = assert(fn())
  86. Guidance: use the "result-or-message" pattern for...
  87. - Functions where failure is expected, especially when communicating with the
  88. external world. E.g. HTTP requests or LSP requests often fail because of
  89. server problems, even if the caller did everything right.
  90. - Functions that return a value, e.g. Foo:new().
  91. - When there is a list of known error codes which can be returned as a third
  92. value (like |luv-error-handling|).
  93. <
  94. *iterator*
  95. An iterator is just a function that can be called repeatedly to get the "next"
  96. value of a collection (or any other |iterable|). This interface is expected by
  97. |for-in| loops, produced by |pairs()|, supported by |vim.iter|, etc.
  98. https://www.lua.org/pil/7.1.html
  99. *iterable*
  100. An "iterable" is anything that |vim.iter()| can consume: tables, dicts, lists,
  101. iterator functions, tables implementing the |__call()| metamethod, and
  102. |vim.iter()| objects.
  103. *list-iterator*
  104. Iterators on |lua-list| tables have a "middle" and "end", whereas iterators in
  105. general may be logically infinite. Therefore some |vim.iter| operations (e.g.
  106. |Iter:rev()|) make sense only on list-like tables (which are finite by
  107. definition).
  108. *lua-function-call*
  109. Lua functions can be called in multiple ways. Consider the function: >lua
  110. local foo = function(a, b)
  111. print("A: ", a)
  112. print("B: ", b)
  113. end
  114. The first way to call this function is: >lua
  115. foo(1, 2)
  116. -- ==== Result ====
  117. -- A: 1
  118. -- B: 2
  119. This way of calling a function is familiar from most scripting languages. In
  120. Lua, any missing arguments are passed as `nil`, and extra parameters are
  121. silently discarded. Example: >lua
  122. foo(1)
  123. -- ==== Result ====
  124. -- A: 1
  125. -- B: nil
  126. <
  127. *kwargs*
  128. When calling a function, you can omit the parentheses if the function takes
  129. exactly one string literal (`"foo"`) or table literal (`{1,2,3}`). The latter
  130. is often used to mimic "named parameters" ("kwargs" or "keyword args") as in
  131. languages like Python and C#. Example: >lua
  132. local func_with_opts = function(opts)
  133. local will_do_foo = opts.foo
  134. local filename = opts.filename
  135. -- ...
  136. end
  137. func_with_opts { foo = true, filename = "hello.world" }
  138. <
  139. There's nothing special going on here except that parentheses are implicitly
  140. added. But visually, this small bit of sugar gets reasonably close to a
  141. "keyword args" interface.
  142. *lua-regex*
  143. Lua intentionally does not support regular expressions, instead it has limited
  144. |lua-patterns| which avoid the performance pitfalls of extended regex. Lua
  145. scripts can also use Vim regex via |vim.regex()|.
  146. Examples: >lua
  147. print(string.match("foo123bar123", "%d+"))
  148. -- 123
  149. print(string.match("foo123bar123", "[^%d]+"))
  150. -- foo
  151. print(string.match("foo123bar123", "[abc]+"))
  152. -- ba
  153. print(string.match("foo.bar", "%.bar"))
  154. -- .bar
  155. ==============================================================================
  156. IMPORTING LUA MODULES *lua-module-load*
  157. Modules are searched for under the directories specified in 'runtimepath', in
  158. the order they appear. Any "." in the module name is treated as a directory
  159. separator when searching. For a module `foo.bar`, each directory is searched
  160. for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found,
  161. the directories are searched again for a shared library with a name matching
  162. `lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`) derived from
  163. the initial value of |package.cpath|. If still no files are found, Nvim falls
  164. back to Lua's default search mechanism. The first script found is run and
  165. `require()` returns the value returned by the script if any, else `true`.
  166. The return value is cached after the first call to `require()` for each module,
  167. with subsequent calls returning the cached value without searching for, or
  168. executing any script. For further details see |require()|.
  169. For example, if 'runtimepath' is `foo,bar` and |package.cpath| was
  170. `./?.so;./?.dll` at startup, `require('mod')` searches these paths in order
  171. and loads the first module found ("first wins"): >
  172. foo/lua/mod.lua
  173. foo/lua/mod/init.lua
  174. bar/lua/mod.lua
  175. bar/lua/mod/init.lua
  176. foo/lua/mod.so
  177. foo/lua/mod.dll
  178. bar/lua/mod.so
  179. bar/lua/mod.dll
  180. <
  181. *lua-package-path*
  182. Nvim automatically adjusts |package.path| and |package.cpath| according to the
  183. effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is
  184. changed. `package.path` is adjusted by simply appending `/lua/?.lua` and
  185. `/lua/?/init.lua` to each directory from 'runtimepath' (`/` is actually the
  186. first character of `package.config`).
  187. Similarly to |package.path|, modified directories from 'runtimepath' are also
  188. added to |package.cpath|. In this case, instead of appending `/lua/?.lua` and
  189. `/lua/?/init.lua` to each runtimepath, all unique `?`-containing suffixes of
  190. the existing |package.cpath| are used. Example:
  191. - 1. Given that
  192. - 'runtimepath' contains `/foo/bar,/xxx;yyy/baz,/abc`;
  193. - initial |package.cpath| (defined at compile-time or derived from
  194. `$LUA_CPATH` / `$LUA_INIT`) contains `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`.
  195. - 2. It finds `?`-containing suffixes `/?.so`, `/a?d/j/g.elf` and `/?.so`, in
  196. order: parts of the path starting from the first path component containing
  197. question mark and preceding path separator.
  198. - 3. The suffix of `/def/?.so`, namely `/?.so` is not unique, as it’s the same
  199. as the suffix of the first path from |package.path| (i.e. `./?.so`). Which
  200. leaves `/?.so` and `/a?d/j/g.elf`, in this order.
  201. - 4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The
  202. second one contains a semicolon which is a paths separator so it is out,
  203. leaving only `/foo/bar` and `/abc`, in order.
  204. - 5. The cartesian product of paths from 4. and suffixes from 3. is taken,
  205. giving four variants. In each variant a `/lua` path segment is inserted
  206. between path and suffix, leaving:
  207. - `/foo/bar/lua/?.so`
  208. - `/foo/bar/lua/a?d/j/g.elf`
  209. - `/abc/lua/?.so`
  210. - `/abc/lua/a?d/j/g.elf`
  211. - 6. New paths are prepended to the original |package.cpath|.
  212. The result will look like this: >
  213. /foo/bar,/xxx;yyy/baz,/abc ('runtimepath')
  214. × ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so (package.cpath)
  215. = /foo/bar/lua/?.so;/foo/bar/lua/a?d/j/g.elf;/abc/lua/?.so;/abc/lua/a?d/j/g.elf;./?.so;/def/ghi/a?d/j/g.elf;/def/?.so
  216. Note:
  217. - To track 'runtimepath' updates, paths added at previous update are
  218. remembered and removed at the next update, while all paths derived from the
  219. new 'runtimepath' are prepended as described above. This allows removing
  220. paths when path is removed from 'runtimepath', adding paths when they are
  221. added and reordering |package.path|/|package.cpath| content if 'runtimepath'
  222. was reordered.
  223. - Although adjustments happen automatically, Nvim does not track current
  224. values of |package.path| or |package.cpath|. If you happen to delete some
  225. paths from there you can set 'runtimepath' to trigger an update: >vim
  226. let &runtimepath = &runtimepath
  227. - Skipping paths from 'runtimepath' which contain semicolons applies both to
  228. |package.path| and |package.cpath|. Given that there are some badly written
  229. plugins using shell, which will not work with paths containing semicolons,
  230. it is better to not have them in 'runtimepath' at all.
  231. ==============================================================================
  232. COMMANDS *lua-commands*
  233. These commands execute a Lua chunk from either the command line (:lua, :luado)
  234. or a file (:luafile) on the given line [range]. As always in Lua, each chunk
  235. has its own scope (closure), so only global variables are shared between
  236. command calls. The |lua-stdlib| modules, user modules, and anything else on
  237. |package.path| are available.
  238. The Lua print() function redirects its output to the Nvim message area, with
  239. arguments separated by " " (space) instead of "\t" (tab).
  240. *:lua=* *:lua*
  241. :lua {chunk}
  242. Executes Lua chunk {chunk}. If {chunk} starts with "=" the rest of the
  243. chunk is evaluated as an expression and printed. `:lua =expr` and `:=expr`
  244. are equivalent to `:lua vim.print(expr)`.
  245. Examples: >vim
  246. :lua vim.api.nvim_command('echo "Hello, Nvim!"')
  247. < To see the Lua version: >vim
  248. :lua print(_VERSION)
  249. < To see the LuaJIT version: >vim
  250. :lua =jit.version
  251. <
  252. :{range}lua
  253. Executes buffer lines in {range} as Lua code. Unlike |:source|, this
  254. always treats the lines as Lua code.
  255. Example: select the following code and type ":lua<Enter>" to execute it: >lua
  256. print(string.format(
  257. 'unix time: %s', os.time()))
  258. <
  259. *:lua-heredoc*
  260. :lua << [trim] [{endmarker}]
  261. {script}
  262. {endmarker}
  263. Executes Lua script {script} from within Vimscript. You can omit
  264. [endmarker] after the "<<" and use a dot "." after {script} (similar to
  265. |:append|, |:insert|). Refer to |:let-heredoc| for more information.
  266. Example: >vim
  267. function! CurrentLineInfo()
  268. lua << EOF
  269. local linenr = vim.api.nvim_win_get_cursor(0)[1]
  270. local curline = vim.api.nvim_buf_get_lines(0, linenr - 1, linenr, false)[1]
  271. print(string.format('Line [%d] has %d bytes', linenr, #curline))
  272. EOF
  273. endfunction
  274. <
  275. Note that the `local` variables will disappear when the block finishes.
  276. But not globals.
  277. *:luado*
  278. :[range]luado {body}
  279. Executes Lua chunk "function(line, linenr) {body} end" for each buffer
  280. line in [range], where `line` is the current line text (without <EOL>),
  281. and `linenr` is the current line number. If the function returns a string
  282. that becomes the text of the corresponding buffer line. Default [range] is
  283. the whole file: "1,$".
  284. Examples: >vim
  285. :luado return string.format("%s\t%d", line:reverse(), #line)
  286. :lua require"lpeg"
  287. :lua -- balanced parenthesis grammar:
  288. :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
  289. :luado if bp:match(line) then return "=>\t" .. line end
  290. <
  291. *:luafile*
  292. :luafile {file}
  293. Execute Lua script in {file}.
  294. The whole argument is used as the filename (like |:edit|), spaces do not
  295. need to be escaped. Alternatively you can |:source| Lua files.
  296. Examples: >vim
  297. :luafile script.lua
  298. :luafile %
  299. <
  300. ==============================================================================
  301. luaeval() *lua-eval*
  302. The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is
  303. "luaeval". "luaeval" takes an expression string and an optional argument used
  304. for _A inside expression and returns the result of the expression. It is
  305. semantically equivalent in Lua to: >lua
  306. local chunkheader = "local _A = select(1, ...) return "
  307. function luaeval (expstr, arg)
  308. local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
  309. return chunk(arg) -- return typval
  310. end
  311. <
  312. Lua nils, numbers, strings, tables and booleans are converted to their
  313. respective Vimscript types. If a Lua string contains a NUL byte, it will be
  314. converted to a |Blob|. Conversion of other Lua types is an error.
  315. The magic global "_A" contains the second argument to luaeval().
  316. Example: >vim
  317. :echo luaeval('_A[1] + _A[2]', [40, 2])
  318. " 42
  319. :echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123')
  320. " foo
  321. <
  322. *lua-table-ambiguous*
  323. Lua tables are used as both dictionaries and lists, so it is impossible to
  324. decide whether empty table is a list or a dict. Also Lua does not have integer
  325. numbers. To disambiguate these cases, we define:
  326. *lua-list*
  327. 0. Empty table is a list. Use |vim.empty_dict()| to represent empty dict.
  328. 1. Table with N consecutive (no `nil` values, aka "holes") integer keys 1…N is
  329. a list. See also |list-iterator|.
  330. *lua-dict*
  331. 2. Table with string keys, none of which contains NUL byte, is a dict.
  332. 3. Table with string keys, at least one of which contains NUL byte, is also
  333. considered to be a dictionary, but this time it is converted to
  334. a |msgpack-special-map|.
  335. *lua-special-tbl*
  336. 4. Table with `vim.type_idx` key may be a dictionary, a list or floating-point
  337. value:
  338. - `{[vim.type_idx]=vim.types.float, [vim.val_idx]=1}` is converted to
  339. a floating-point 1.0. Note that by default integral Lua numbers are
  340. converted to |Number|s, non-integral are converted to |Float|s. This
  341. variant allows integral |Float|s.
  342. - `{[vim.type_idx]=vim.types.dictionary}` is converted to an empty
  343. dictionary, `{[vim.type_idx]=vim.types.dictionary, [42]=1, a=2}` is
  344. converted to a dictionary `{'a': 42}`: non-string keys are ignored.
  345. Without `vim.type_idx` key tables with keys not fitting in 1., 2. or 3.
  346. are errors.
  347. - `{[vim.type_idx]=vim.types.array}` is converted to an empty list. As well
  348. as `{[vim.type_idx]=vim.types.array, [42]=1}`: integral keys that do not
  349. form a 1-step sequence from 1 to N are ignored, as well as all
  350. non-integral keys.
  351. Examples: >vim
  352. :echo luaeval('math.pi')
  353. :function Rand(x,y) " random uniform between x and y
  354. : return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
  355. : endfunction
  356. :echo Rand(1,10)
  357. <
  358. Note: Second argument to `luaeval` is converted ("marshalled") from Vimscript
  359. to Lua, so changes to Lua containers do not affect values in Vimscript. Return
  360. value is also always converted. When converting, |msgpack-special-dict|s are
  361. treated specially.
  362. ==============================================================================
  363. Vimscript v:lua interface *v:lua-call*
  364. From Vimscript the special `v:lua` prefix can be used to call Lua functions
  365. which are global or accessible from global tables. The expression >vim
  366. call v:lua.func(arg1, arg2)
  367. is equivalent to the Lua chunk >lua
  368. return func(...)
  369. where the args are converted to Lua values. The expression >vim
  370. call v:lua.somemod.func(args)
  371. is equivalent to the Lua chunk >lua
  372. return somemod.func(...)
  373. In addition, functions of packages can be accessed like >vim
  374. call v:lua.require'mypack'.func(arg1, arg2)
  375. call v:lua.require'mypack.submod'.func(arg1, arg2)
  376. Note: Only single quote form without parens is allowed. Using
  377. `require"mypack"` or `require('mypack')` as prefixes do NOT work (the latter
  378. is still valid as a function call of itself, in case require returns a useful
  379. value).
  380. The `v:lua` prefix may be used to call Lua functions as |method|s. For
  381. example: >vim
  382. :eval arg1->v:lua.somemod.func(arg2)
  383. <
  384. You can use `v:lua` in "func" options like 'tagfunc', 'omnifunc', etc.
  385. For example consider the following Lua omnifunc handler: >lua
  386. function mymod.omnifunc(findstart, base)
  387. if findstart == 1 then
  388. return 0
  389. else
  390. return {'stuff', 'steam', 'strange things'}
  391. end
  392. end
  393. vim.bo[buf].omnifunc = 'v:lua.mymod.omnifunc'
  394. Note: The module ("mymod" in the above example) must either be a Lua global,
  395. or use require() as shown above to access it from a package.
  396. Note: `v:lua` without a call is not allowed in a Vimscript expression:
  397. |Funcref|s cannot represent Lua functions. The following are errors: >vim
  398. let g:Myvar = v:lua.myfunc " Error
  399. call SomeFunc(v:lua.mycallback) " Error
  400. let g:foo = v:lua " Error
  401. let g:foo = v:['lua'] " Error
  402. <
  403. ==============================================================================
  404. Lua standard modules *lua-stdlib*
  405. The Nvim Lua "standard library" (stdlib) is the `vim` module, which exposes
  406. various functions and sub-modules. It is always loaded, thus `require("vim")`
  407. is unnecessary.
  408. You can peek at the module properties: >vim
  409. :lua vim.print(vim)
  410. Result is something like this: >
  411. {
  412. _os_proc_children = <function 1>,
  413. _os_proc_info = <function 2>,
  414. ...
  415. api = {
  416. nvim__id = <function 5>,
  417. nvim__id_array = <function 6>,
  418. ...
  419. },
  420. deepcopy = <function 106>,
  421. gsplit = <function 107>,
  422. ...
  423. }
  424. To find documentation on e.g. the "deepcopy" function: >vim
  425. :help vim.deepcopy()
  426. Note that underscore-prefixed functions (e.g. "_os_proc_children") are
  427. internal/private and must not be used by plugins.
  428. ------------------------------------------------------------------------------
  429. VIM.UV *lua-loop* *vim.uv*
  430. `vim.uv` exposes the "luv" Lua bindings for the libUV library that Nvim uses
  431. for networking, filesystem, and process management, see |luvref.txt|.
  432. In particular, it allows interacting with the main Nvim |luv-event-loop|.
  433. *E5560* *lua-loop-callbacks*
  434. It is an error to directly invoke `vim.api` functions (except |api-fast|) in
  435. `vim.uv` callbacks. For example, this is an error: >lua
  436. local timer = vim.uv.new_timer()
  437. timer:start(1000, 0, function()
  438. vim.api.nvim_command('echomsg "test"')
  439. end)
  440. <
  441. To avoid the error use |vim.schedule_wrap()| to defer the callback: >lua
  442. local timer = vim.uv.new_timer()
  443. timer:start(1000, 0, vim.schedule_wrap(function()
  444. vim.api.nvim_command('echomsg "test"')
  445. end))
  446. <
  447. (For one-shot timers, see |vim.defer_fn()|, which automatically adds the
  448. wrapping.)
  449. Example: repeating timer
  450. 1. Save this code to a file.
  451. 2. Execute it with ":luafile %". >lua
  452. -- Create a timer handle (implementation detail: uv_timer_t).
  453. local timer = vim.uv.new_timer()
  454. local i = 0
  455. -- Waits 1000ms, then repeats every 750ms until timer:close().
  456. timer:start(1000, 750, function()
  457. print('timer invoked! i='..tostring(i))
  458. if i > 4 then
  459. timer:close() -- Always close handles to avoid leaks.
  460. end
  461. i = i + 1
  462. end)
  463. print('sleeping');
  464. <
  465. Example: File-change detection *watch-file*
  466. 1. Save this code to a file.
  467. 2. Execute it with ":luafile %".
  468. 3. Use ":Watch %" to watch any file.
  469. 4. Try editing the file from another text editor.
  470. 5. Observe that the file reloads in Nvim (because on_change() calls
  471. |:checktime|). >lua
  472. local w = vim.uv.new_fs_event()
  473. local function on_change(err, fname, status)
  474. -- Do work...
  475. vim.api.nvim_command('checktime')
  476. -- Debounce: stop/start.
  477. w:stop()
  478. watch_file(fname)
  479. end
  480. function watch_file(fname)
  481. local fullpath = vim.api.nvim_call_function(
  482. 'fnamemodify', {fname, ':p'})
  483. w:start(fullpath, {}, vim.schedule_wrap(function(...)
  484. on_change(...) end))
  485. end
  486. vim.api.nvim_command(
  487. "command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))")
  488. <
  489. *inotify-limitations*
  490. When on Linux you may need to increase the maximum number of `inotify` watches
  491. and queued events as the default limit can be too low. To increase the limit,
  492. run: >sh
  493. sysctl fs.inotify.max_user_watches=494462
  494. <
  495. This will increase the limit to 494462 watches and queued events. These lines
  496. can be added to `/etc/sysctl.conf` to make the changes persistent.
  497. Note that each watch is a structure in the Kernel, thus available memory is
  498. also a bottleneck for using inotify. In fact, a watch can take up to 1KB of
  499. space. This means a million watches could result in 1GB of extra RAM usage.
  500. Example: TCP echo-server *tcp-server*
  501. 1. Save this code to a file.
  502. 2. Execute it with ":luafile %".
  503. 3. Note the port number.
  504. 4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): >lua
  505. local function create_server(host, port, on_connect)
  506. local server = vim.uv.new_tcp()
  507. server:bind(host, port)
  508. server:listen(128, function(err)
  509. assert(not err, err) -- Check for errors.
  510. local sock = vim.uv.new_tcp()
  511. server:accept(sock) -- Accept client connection.
  512. on_connect(sock) -- Start reading messages.
  513. end)
  514. return server
  515. end
  516. local server = create_server('0.0.0.0', 0, function(sock)
  517. sock:read_start(function(err, chunk)
  518. assert(not err, err) -- Check for errors.
  519. if chunk then
  520. sock:write(chunk) -- Echo received messages to the channel.
  521. else -- EOF (stream closed).
  522. sock:close() -- Always close handles to avoid leaks.
  523. end
  524. end)
  525. end)
  526. print('TCP echo-server listening on port: '..server:getsockname().port)
  527. <
  528. Multithreading *lua-loop-threading*
  529. Plugins can perform work in separate (os-level) threads using the threading
  530. APIs in luv, for instance `vim.uv.new_thread`. Each thread has its own
  531. separate Lua interpreter state, with no access to Lua globals on the main
  532. thread. Neither can the editor state (buffers, windows, etc) be directly
  533. accessed from threads.
  534. A subset of the `vim.*` stdlib is available in threads, including:
  535. - `vim.uv` with a separate event loop per thread.
  536. - `vim.mpack` and `vim.json` (useful for serializing messages between threads)
  537. - `require` in threads can use Lua packages from the global |package.path|
  538. - `print()` and `vim.inspect`
  539. - `vim.diff`
  540. - Most utility functions in `vim.*` that work with pure Lua values, like
  541. `vim.split`, `vim.tbl_*`, `vim.list_*`, etc.
  542. - `vim.is_thread()` returns true from a non-main thread.
  543. ==============================================================================
  544. VIM.HL *vim.hl*
  545. vim.hl.on_yank({opts}) *vim.hl.on_yank()*
  546. Highlight the yanked text during a |TextYankPost| event.
  547. Add the following to your `init.vim`: >vim
  548. autocmd TextYankPost * silent! lua vim.hl.on_yank {higroup='Visual', timeout=300}
  549. <
  550. Parameters: ~
  551. • {opts} (`table?`) Optional parameters
  552. • higroup highlight group for yanked region (default
  553. "IncSearch")
  554. • timeout time in ms before highlight is cleared (default 150)
  555. • on_macro highlight when executing macro (default false)
  556. • on_visual highlight when yanking visual selection (default
  557. true)
  558. • event event structure (default vim.v.event)
  559. • priority integer priority (default
  560. |vim.hl.priorities|`.user`)
  561. vim.hl.priorities *vim.hl.priorities*
  562. Table with default priorities used for highlighting:
  563. • `syntax`: `50`, used for standard syntax highlighting
  564. • `treesitter`: `100`, used for treesitter-based highlighting
  565. • `semantic_tokens`: `125`, used for LSP semantic token highlighting
  566. • `diagnostics`: `150`, used for code analysis such as diagnostics
  567. • `user`: `200`, used for user-triggered highlights such as LSP document
  568. symbols or `on_yank` autocommands
  569. *vim.hl.range()*
  570. vim.hl.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts})
  571. Apply highlight group to range of text.
  572. Parameters: ~
  573. • {bufnr} (`integer`) Buffer number to apply highlighting to
  574. • {ns} (`integer`) Namespace to add highlight to
  575. • {higroup} (`string`) Highlight group to use for highlighting
  576. • {start} (`integer[]|string`) Start of region as a (line, column)
  577. tuple or string accepted by |getpos()|
  578. • {finish} (`integer[]|string`) End of region as a (line, column)
  579. tuple or string accepted by |getpos()|
  580. • {opts} (`table?`) A table with the following fields:
  581. • {regtype}? (`string`, default: `'v'` i.e. charwise) Type
  582. of range. See |getregtype()|
  583. • {inclusive}? (`boolean`, default: `false`) Indicates
  584. whether the range is end-inclusive
  585. • {priority}? (`integer`, default:
  586. `vim.hl.priorities.user`) Highlight priority
  587. • {timeout}? (`integer`, default: -1 no timeout) Time in ms
  588. before highlight is cleared
  589. ==============================================================================
  590. VIM.DIFF *vim.diff*
  591. vim.diff({a}, {b}, {opts}) *vim.diff()*
  592. Run diff on strings {a} and {b}. Any indices returned by this function,
  593. either directly or via callback arguments, are 1-based.
  594. Examples: >lua
  595. vim.diff('a\n', 'b\nc\n')
  596. -- =>
  597. -- @@ -1 +1,2 @@
  598. -- -a
  599. -- +b
  600. -- +c
  601. vim.diff('a\n', 'b\nc\n', {result_type = 'indices'})
  602. -- =>
  603. -- {
  604. -- {1, 1, 1, 2}
  605. -- }
  606. <
  607. Parameters: ~
  608. • {a} (`string`) First string to compare
  609. • {b} (`string`) Second string to compare
  610. • {opts} (`table?`) Optional parameters:
  611. • {on_hunk}?
  612. (`fun(start_a: integer, count_a: integer, start_b: integer, count_b: integer): integer?`)
  613. Invoked for each hunk in the diff. Return a negative number
  614. to cancel the callback for any remaining hunks. Arguments:
  615. • `start_a` (`integer`): Start line of hunk in {a}.
  616. • `count_a` (`integer`): Hunk size in {a}.
  617. • `start_b` (`integer`): Start line of hunk in {b}.
  618. • `count_b` (`integer`): Hunk size in {b}.
  619. • {result_type}? (`'unified'|'indices'`, default: `'unified'`)
  620. Form of the returned diff:
  621. • `unified`: String in unified format.
  622. • `indices`: Array of hunk locations. Note: This option is
  623. ignored if `on_hunk` is used.
  624. • {linematch}? (`boolean|integer`) Run linematch on the
  625. resulting hunks from xdiff. When integer, only hunks upto
  626. this size in lines are run through linematch. Requires
  627. `result_type = indices`, ignored otherwise.
  628. • {algorithm}? (`'myers'|'minimal'|'patience'|'histogram'`,
  629. default: `'myers'`) Diff algorithm to use. Values:
  630. • `myers`: the default algorithm
  631. • `minimal`: spend extra time to generate the smallest
  632. possible diff
  633. • `patience`: patience diff algorithm
  634. • `histogram`: histogram diff algorithm
  635. • {ctxlen}? (`integer`) Context length
  636. • {interhunkctxlen}? (`integer`) Inter hunk context length
  637. • {ignore_whitespace}? (`boolean`) Ignore whitespace
  638. • {ignore_whitespace_change}? (`boolean`) Ignore whitespace
  639. change
  640. • {ignore_whitespace_change_at_eol}? (`boolean`) Ignore
  641. whitespace change at end-of-line.
  642. • {ignore_cr_at_eol}? (`boolean`) Ignore carriage return at
  643. end-of-line
  644. • {ignore_blank_lines}? (`boolean`) Ignore blank lines
  645. • {indent_heuristic}? (`boolean`) Use the indent heuristic for
  646. the internal diff library.
  647. Return: ~
  648. (`string|integer[][]?`) See {opts.result_type}. `nil` if
  649. {opts.on_hunk} is given.
  650. ==============================================================================
  651. VIM.MPACK *vim.mpack*
  652. This module provides encoding and decoding of Lua objects to and from
  653. msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
  654. vim.mpack.decode({str}) *vim.mpack.decode()*
  655. Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object.
  656. Parameters: ~
  657. • {str} (`string`)
  658. Return: ~
  659. (`any`)
  660. vim.mpack.encode({obj}) *vim.mpack.encode()*
  661. Encodes (or "packs") Lua object {obj} as msgpack in a Lua string.
  662. Parameters: ~
  663. • {obj} (`any`)
  664. Return: ~
  665. (`string`)
  666. ==============================================================================
  667. VIM.JSON *vim.json*
  668. This module provides encoding and decoding of Lua objects to and from
  669. JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
  670. vim.json.decode({str}, {opts}) *vim.json.decode()*
  671. Decodes (or "unpacks") the JSON-encoded {str} to a Lua object.
  672. • Decodes JSON "null" as |vim.NIL| (controllable by {opts}, see below).
  673. • Decodes empty object as |vim.empty_dict()|.
  674. • Decodes empty array as `{}` (empty Lua table).
  675. Example: >lua
  676. vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
  677. -- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
  678. <
  679. Parameters: ~
  680. • {str} (`string`) Stringified JSON data.
  681. • {opts} (`table<string,any>?`) Options table with keys:
  682. • luanil: (table) Table with keys:
  683. • object: (boolean) When true, converts `null` in JSON
  684. objects to Lua `nil` instead of |vim.NIL|.
  685. • array: (boolean) When true, converts `null` in JSON arrays
  686. to Lua `nil` instead of |vim.NIL|.
  687. Return: ~
  688. (`any`)
  689. vim.json.encode({obj}, {opts}) *vim.json.encode()*
  690. Encodes (or "packs") Lua object {obj} as JSON in a Lua string.
  691. Parameters: ~
  692. • {obj} (`any`)
  693. • {opts} (`table<string,any>?`) Options table with keys:
  694. • escape_slash: (boolean) (default false) Escape slash
  695. characters "/" in string values.
  696. Return: ~
  697. (`string`)
  698. ==============================================================================
  699. VIM.BASE64 *vim.base64*
  700. vim.base64.decode({str}) *vim.base64.decode()*
  701. Decode a Base64 encoded string.
  702. Parameters: ~
  703. • {str} (`string`) Base64 encoded string
  704. Return: ~
  705. (`string`) Decoded string
  706. vim.base64.encode({str}) *vim.base64.encode()*
  707. Encode {str} using Base64.
  708. Parameters: ~
  709. • {str} (`string`) String to encode
  710. Return: ~
  711. (`string`) Encoded string
  712. ==============================================================================
  713. VIM.SPELL *vim.spell*
  714. vim.spell.check({str}) *vim.spell.check()*
  715. Check {str} for spelling errors. Similar to the Vimscript function
  716. |spellbadword()|.
  717. Note: The behaviour of this function is dependent on: 'spelllang',
  718. 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to
  719. the buffer. Consider calling this with |nvim_buf_call()|.
  720. Example: >lua
  721. vim.spell.check("the quik brown fox")
  722. -- =>
  723. -- {
  724. -- {'quik', 'bad', 5}
  725. -- }
  726. <
  727. Parameters: ~
  728. • {str} (`string`)
  729. Return: ~
  730. (`[string, 'bad'|'rare'|'local'|'caps', integer][]`) List of tuples
  731. with three items:
  732. • The badly spelled word.
  733. • The type of the spelling error: "bad" spelling mistake "rare" rare
  734. word "local" word only valid in another region "caps" word should
  735. start with Capital
  736. • The position in {str} where the word begins.
  737. ==============================================================================
  738. VIM *vim.builtin*
  739. vim.api.{func}({...}) *vim.api*
  740. Invokes Nvim |API| function {func} with arguments {...}.
  741. Example: call the "nvim_get_current_line()" API function: >lua
  742. print(tostring(vim.api.nvim_get_current_line()))
  743. vim.NIL *vim.NIL*
  744. Special value representing NIL in |RPC| and |v:null| in Vimscript
  745. conversion, and similar cases. Lua `nil` cannot be used as part of a Lua
  746. table representing a Dictionary or Array, because it is treated as
  747. missing: `{"foo", nil}` is the same as `{"foo"}`.
  748. vim.type_idx *vim.type_idx*
  749. Type index for use in |lua-special-tbl|. Specifying one of the values from
  750. |vim.types| allows typing the empty table (it is unclear whether empty Lua
  751. table represents empty list or empty array) and forcing integral numbers
  752. to be |Float|. See |lua-special-tbl| for more details.
  753. vim.val_idx *vim.val_idx*
  754. Value index for tables representing |Float|s. A table representing
  755. floating-point value 1.0 looks like this: >lua
  756. {
  757. [vim.type_idx] = vim.types.float,
  758. [vim.val_idx] = 1.0,
  759. }
  760. < See also |vim.type_idx| and |lua-special-tbl|.
  761. vim.types *vim.types*
  762. Table with possible values for |vim.type_idx|. Contains two sets of
  763. key-value pairs: first maps possible values for |vim.type_idx| to
  764. human-readable strings, second maps human-readable type names to values
  765. for |vim.type_idx|. Currently contains pairs for `float`, `array` and
  766. `dictionary` types.
  767. Note: One must expect that values corresponding to `vim.types.float`,
  768. `vim.types.array` and `vim.types.dictionary` fall under only two following
  769. assumptions:
  770. 1. Value may serve both as a key and as a value in a table. Given the
  771. properties of Lua tables this basically means “value is not `nil`”.
  772. 2. For each value in `vim.types` table `vim.types[vim.types[value]]` is the
  773. same as `value`.
  774. No other restrictions are put on types, and it is not guaranteed that
  775. values corresponding to `vim.types.float`, `vim.types.array` and
  776. `vim.types.dictionary` will not change or that `vim.types` table will only
  777. contain values for these three types.
  778. *log_levels* *vim.log.levels*
  779. Log levels are one of the values defined in `vim.log.levels`:
  780. vim.log.levels.DEBUG
  781. vim.log.levels.ERROR
  782. vim.log.levels.INFO
  783. vim.log.levels.TRACE
  784. vim.log.levels.WARN
  785. vim.log.levels.OFF
  786. vim.empty_dict() *vim.empty_dict()*
  787. Creates a special empty table (marked with a metatable), which Nvim
  788. converts to an empty dictionary when translating Lua values to Vimscript
  789. or API types. Nvim by default converts an empty table `{}` without this
  790. metatable to an list/array.
  791. Note: If numeric keys are present in the table, Nvim ignores the metatable
  792. marker and converts the dict to a list/array anyway.
  793. Return: ~
  794. (`table`)
  795. vim.iconv({str}, {from}, {to}) *vim.iconv()*
  796. The result is a String, which is the text {str} converted from encoding
  797. {from} to encoding {to}. When the conversion fails `nil` is returned. When
  798. some characters could not be converted they are replaced with "?". The
  799. encoding names are whatever the iconv() library function can accept, see
  800. ":Man 3 iconv".
  801. Parameters: ~
  802. • {str} (`string`) Text to convert
  803. • {from} (`string`) Encoding of {str}
  804. • {to} (`string`) Target encoding
  805. Return: ~
  806. (`string?`) Converted string if conversion succeeds, `nil` otherwise.
  807. vim.in_fast_event() *vim.in_fast_event()*
  808. Returns true if the code is executing as part of a "fast" event handler,
  809. where most of the API is disabled. These are low-level events (e.g.
  810. |lua-loop-callbacks|) which can be invoked whenever Nvim polls for input.
  811. When this is `false` most API functions are callable (but may be subject
  812. to other restrictions such as |textlock|).
  813. vim.rpcnotify({channel}, {method}, {...}) *vim.rpcnotify()*
  814. Sends {event} to {channel} via |RPC| and returns immediately. If {channel}
  815. is 0, the event is broadcast to all channels.
  816. This function also works in a fast callback |lua-loop-callbacks|.
  817. Parameters: ~
  818. • {channel} (`integer`)
  819. • {method} (`string`)
  820. • {...} (`any?`)
  821. vim.rpcrequest({channel}, {method}, {...}) *vim.rpcrequest()*
  822. Sends a request to {channel} to invoke {method} via |RPC| and blocks until
  823. a response is received.
  824. Note: NIL values as part of the return value is represented as |vim.NIL|
  825. special value
  826. Parameters: ~
  827. • {channel} (`integer`)
  828. • {method} (`string`)
  829. • {...} (`any?`)
  830. vim.schedule({fn}) *vim.schedule()*
  831. Schedules {fn} to be invoked soon by the main event-loop. Useful to avoid
  832. |textlock| or other temporary restrictions.
  833. Parameters: ~
  834. • {fn} (`fun()`)
  835. vim.str_utf_end({str}, {index}) *vim.str_utf_end()*
  836. Gets the distance (in bytes) from the last byte of the codepoint
  837. (character) that {index} points to.
  838. Examples: >lua
  839. -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)
  840. -- Returns 0 because the index is pointing at the last byte of a character
  841. vim.str_utf_end('æ', 2)
  842. -- Returns 1 because the index is pointing at the penultimate byte of a character
  843. vim.str_utf_end('æ', 1)
  844. <
  845. Parameters: ~
  846. • {str} (`string`)
  847. • {index} (`integer`)
  848. Return: ~
  849. (`integer`)
  850. vim.str_utf_pos({str}) *vim.str_utf_pos()*
  851. Gets a list of the starting byte positions of each UTF-8 codepoint in the
  852. given string.
  853. Embedded NUL bytes are treated as terminating the string.
  854. Parameters: ~
  855. • {str} (`string`)
  856. Return: ~
  857. (`integer[]`)
  858. vim.str_utf_start({str}, {index}) *vim.str_utf_start()*
  859. Gets the distance (in bytes) from the starting byte of the codepoint
  860. (character) that {index} points to.
  861. The result can be added to {index} to get the starting byte of a
  862. character.
  863. Examples: >lua
  864. -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)
  865. -- Returns 0 because the index is pointing at the first byte of a character
  866. vim.str_utf_start('æ', 1)
  867. -- Returns -1 because the index is pointing at the second byte of a character
  868. vim.str_utf_start('æ', 2)
  869. <
  870. Parameters: ~
  871. • {str} (`string`)
  872. • {index} (`integer`)
  873. Return: ~
  874. (`integer`)
  875. vim.stricmp({a}, {b}) *vim.stricmp()*
  876. Compares strings case-insensitively.
  877. Parameters: ~
  878. • {a} (`string`)
  879. • {b} (`string`)
  880. Return: ~
  881. (`0|1|-1`) if strings are equal, {a} is greater than {b} or {a} is
  882. lesser than {b}, respectively.
  883. vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()*
  884. WARNING: This feature is experimental/unstable.
  885. Attach to |ui-events|, similar to |nvim_ui_attach()| but receive events as
  886. Lua callback. Can be used to implement screen elements like popupmenu or
  887. message handling in Lua.
  888. {options} should be a dictionary-like table, where `ext_...` options
  889. should be set to true to receive events for the respective external
  890. element.
  891. {callback} receives event name plus additional parameters. See
  892. |ui-popupmenu| and the sections below for event format for respective
  893. events.
  894. Callbacks for `msg_show` events are executed in |api-fast| context;
  895. showing the message should be scheduled.
  896. Excessive errors inside the callback will result in forced detachment.
  897. WARNING: This api is considered experimental. Usability will vary for
  898. different screen elements. In particular `ext_messages` behavior is
  899. subject to further changes and usability improvements. This is expected to
  900. be used to handle messages when setting 'cmdheight' to zero (which is
  901. likewise experimental).
  902. Example (stub for a |ui-popupmenu| implementation): >lua
  903. ns = vim.api.nvim_create_namespace('my_fancy_pum')
  904. vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...)
  905. if event == "popupmenu_show" then
  906. local items, selected, row, col, grid = ...
  907. print("display pum ", #items)
  908. elseif event == "popupmenu_select" then
  909. local selected = ...
  910. print("selected", selected)
  911. elseif event == "popupmenu_hide" then
  912. print("FIN")
  913. end
  914. end)
  915. <
  916. Parameters: ~
  917. • {ns} (`integer`)
  918. • {options} (`table<string, any>`)
  919. • {callback} (`fun()`)
  920. vim.ui_detach({ns}) *vim.ui_detach()*
  921. Detach a callback previously attached with |vim.ui_attach()| for the given
  922. namespace {ns}.
  923. Parameters: ~
  924. • {ns} (`integer`)
  925. vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()*
  926. Wait for {time} in milliseconds until {callback} returns `true`.
  927. Executes {callback} immediately and at approximately {interval}
  928. milliseconds (default 200). Nvim still processes other events during this
  929. time.
  930. Cannot be called while in an |api-fast| event.
  931. Examples: >lua
  932. ---
  933. -- Wait for 100 ms, allowing other events to process
  934. vim.wait(100, function() end)
  935. ---
  936. -- Wait for 100 ms or until global variable set.
  937. vim.wait(100, function() return vim.g.waiting_for_var end)
  938. ---
  939. -- Wait for 1 second or until global variable set, checking every ~500 ms
  940. vim.wait(1000, function() return vim.g.waiting_for_var end, 500)
  941. ---
  942. -- Schedule a function to set a value in 100ms
  943. vim.defer_fn(function() vim.g.timer_result = true end, 100)
  944. -- Would wait ten seconds if results blocked. Actually only waits 100 ms
  945. if vim.wait(10000, function() return vim.g.timer_result end) then
  946. print('Only waiting a little bit of time!')
  947. end
  948. <
  949. Parameters: ~
  950. • {time} (`integer`) Number of milliseconds to wait
  951. • {callback} (`fun(): boolean?`) Optional callback. Waits until
  952. {callback} returns true
  953. • {interval} (`integer?`) (Approximate) number of milliseconds to wait
  954. between polls
  955. • {fast_only} (`boolean?`) If true, only |api-fast| events will be
  956. processed.
  957. Return (multiple): ~
  958. (`boolean`)
  959. (`-1|-2?`)
  960. • If {callback} returns `true` during the {time}: `true, nil`
  961. • If {callback} never returns `true` during the {time}: `false, -1`
  962. • If {callback} is interrupted during the {time}: `false, -2`
  963. • If {callback} errors, the error is raised.
  964. ==============================================================================
  965. LUA-VIMSCRIPT BRIDGE *lua-vimscript*
  966. Nvim Lua provides an interface or "bridge" to Vimscript variables and
  967. functions, and editor commands and options.
  968. Objects passed over this bridge are COPIED (marshalled): there are no
  969. "references". |lua-guide-variables| For example, using `vim.fn.remove()` on a
  970. Lua list copies the list object to Vimscript and does NOT modify the Lua list: >lua
  971. local list = { 1, 2, 3 }
  972. vim.fn.remove(list, 0)
  973. vim.print(list) --> "{ 1, 2, 3 }"
  974. <
  975. vim.call({func}, {...}) *vim.call()*
  976. Invokes |vim-function| or |user-function| {func} with arguments {...}.
  977. See also |vim.fn|.
  978. Equivalent to: >lua
  979. vim.fn[func]({...})
  980. <
  981. vim.cmd({command})
  982. See |vim.cmd()|.
  983. vim.fn.{func}({...}) *vim.fn*
  984. Invokes |vim-function| or |user-function| {func} with arguments {...}.
  985. To call autoload functions, use the syntax: >lua
  986. vim.fn['some#function']({...})
  987. <
  988. Unlike vim.api.|nvim_call_function()| this converts directly between Vim
  989. objects and Lua objects. If the Vim function returns a float, it will be
  990. represented directly as a Lua number. Empty lists and dictionaries both
  991. are represented by an empty table.
  992. Note: |v:null| values as part of the return value is represented as
  993. |vim.NIL| special value
  994. Note: vim.fn keys are generated lazily, thus `pairs(vim.fn)` only
  995. enumerates functions that were called at least once.
  996. Note: The majority of functions cannot run in |api-fast| callbacks with some
  997. undocumented exceptions which are allowed.
  998. *lua-vim-variables*
  999. The Vim editor global dictionaries |g:| |w:| |b:| |t:| |v:| can be accessed
  1000. from Lua conveniently and idiomatically by referencing the `vim.*` Lua tables
  1001. described below. In this way you can easily read and modify global Vimscript
  1002. variables from Lua.
  1003. Example: >lua
  1004. vim.g.foo = 5 -- Set the g:foo Vimscript variable.
  1005. print(vim.g.foo) -- Get and print the g:foo Vimscript variable.
  1006. vim.g.foo = nil -- Delete (:unlet) the Vimscript variable.
  1007. vim.b[2].foo = 6 -- Set b:foo for buffer 2
  1008. <
  1009. Note that setting dictionary fields directly will not write them back into
  1010. Nvim. This is because the index into the namespace simply returns a copy.
  1011. Instead the whole dictionary must be written as one. This can be achieved by
  1012. creating a short-lived temporary.
  1013. Example: >lua
  1014. vim.g.my_dict.field1 = 'value' -- Does not work
  1015. local my_dict = vim.g.my_dict --
  1016. my_dict.field1 = 'value' -- Instead do
  1017. vim.g.my_dict = my_dict --
  1018. vim.g *vim.g*
  1019. Global (|g:|) editor variables.
  1020. Key with no value returns `nil`.
  1021. vim.b *vim.b*
  1022. Buffer-scoped (|b:|) variables for the current buffer.
  1023. Invalid or unset key returns `nil`. Can be indexed with
  1024. an integer to access variables for a specific buffer.
  1025. vim.w *vim.w*
  1026. Window-scoped (|w:|) variables for the current window.
  1027. Invalid or unset key returns `nil`. Can be indexed with
  1028. an integer to access variables for a specific window.
  1029. vim.t *vim.t*
  1030. Tabpage-scoped (|t:|) variables for the current tabpage.
  1031. Invalid or unset key returns `nil`. Can be indexed with
  1032. an integer to access variables for a specific tabpage.
  1033. vim.v *vim.v*
  1034. |v:| variables.
  1035. Invalid or unset key returns `nil`.
  1036. *lua-options*
  1037. *lua-vim-options*
  1038. *lua-vim-set*
  1039. *lua-vim-setlocal*
  1040. Vim options can be accessed through |vim.o|, which behaves like Vimscript
  1041. |:set|.
  1042. Examples: ~
  1043. To set a boolean toggle:
  1044. Vimscript: `set number`
  1045. Lua: `vim.o.number = true`
  1046. To set a string value:
  1047. Vimscript: `set wildignore=*.o,*.a,__pycache__`
  1048. Lua: `vim.o.wildignore = '*.o,*.a,__pycache__'`
  1049. Similarly, there is |vim.bo| and |vim.wo| for setting buffer-scoped and
  1050. window-scoped options. Note that this must NOT be confused with
  1051. |local-options| and |:setlocal|. There is also |vim.go| that only accesses the
  1052. global value of a |global-local| option, see |:setglobal|.
  1053. *vim.opt_local*
  1054. *vim.opt_global*
  1055. *vim.opt*
  1056. A special interface |vim.opt| exists for conveniently interacting with list-
  1057. and map-style options from Lua: It allows accessing them as Lua tables and
  1058. offers object-oriented method for adding and removing entries.
  1059. Examples: ~
  1060. The following methods of setting a list-style option are equivalent:
  1061. In Vimscript: >vim
  1062. set wildignore=*.o,*.a,__pycache__
  1063. <
  1064. In Lua using `vim.o`: >lua
  1065. vim.o.wildignore = '*.o,*.a,__pycache__'
  1066. <
  1067. In Lua using `vim.opt`: >lua
  1068. vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
  1069. <
  1070. To replicate the behavior of |:set+=|, use: >lua
  1071. vim.opt.wildignore:append { "*.pyc", "node_modules" }
  1072. <
  1073. To replicate the behavior of |:set^=|, use: >lua
  1074. vim.opt.wildignore:prepend { "new_first_value" }
  1075. <
  1076. To replicate the behavior of |:set-=|, use: >lua
  1077. vim.opt.wildignore:remove { "node_modules" }
  1078. <
  1079. The following methods of setting a map-style option are equivalent:
  1080. In Vimscript: >vim
  1081. set listchars=space:_,tab:>~
  1082. <
  1083. In Lua using `vim.o`: >lua
  1084. vim.o.listchars = 'space:_,tab:>~'
  1085. <
  1086. In Lua using `vim.opt`: >lua
  1087. vim.opt.listchars = { space = '_', tab = '>~' }
  1088. <
  1089. Note that |vim.opt| returns an `Option` object, not the value of the option,
  1090. which is accessed through |vim.opt:get()|:
  1091. Examples: ~
  1092. The following methods of getting a list-style option are equivalent:
  1093. In Vimscript: >vim
  1094. echo wildignore
  1095. <
  1096. In Lua using `vim.o`: >lua
  1097. print(vim.o.wildignore)
  1098. <
  1099. In Lua using `vim.opt`: >lua
  1100. vim.print(vim.opt.wildignore:get())
  1101. <
  1102. In any of the above examples, to replicate the behavior |:setlocal|, use
  1103. `vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use
  1104. `vim.opt_global`.
  1105. Option:append({value}) *vim.opt:append()*
  1106. Append a value to string-style options. See |:set+=|
  1107. These are equivalent: >lua
  1108. vim.opt.formatoptions:append('j')
  1109. vim.opt.formatoptions = vim.opt.formatoptions + 'j'
  1110. <
  1111. Parameters: ~
  1112. • {value} (`string`) Value to append
  1113. Option:get() *vim.opt:get()*
  1114. Returns a Lua-representation of the option. Boolean, number and string
  1115. values will be returned in exactly the same fashion.
  1116. For values that are comma-separated lists, an array will be returned with
  1117. the values as entries in the array: >lua
  1118. vim.cmd [[set wildignore=*.pyc,*.o]]
  1119. vim.print(vim.opt.wildignore:get())
  1120. -- { "*.pyc", "*.o", }
  1121. for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
  1122. print("Will ignore:", ignore_pattern)
  1123. end
  1124. -- Will ignore: *.pyc
  1125. -- Will ignore: *.o
  1126. <
  1127. For values that are comma-separated maps, a table will be returned with
  1128. the names as keys and the values as entries: >lua
  1129. vim.cmd [[set listchars=space:_,tab:>~]]
  1130. vim.print(vim.opt.listchars:get())
  1131. -- { space = "_", tab = ">~", }
  1132. for char, representation in pairs(vim.opt.listchars:get()) do
  1133. print(char, "=>", representation)
  1134. end
  1135. <
  1136. For values that are lists of flags, a set will be returned with the flags
  1137. as keys and `true` as entries. >lua
  1138. vim.cmd [[set formatoptions=njtcroql]]
  1139. vim.print(vim.opt.formatoptions:get())
  1140. -- { n = true, j = true, c = true, ... }
  1141. local format_opts = vim.opt.formatoptions:get()
  1142. if format_opts.j then
  1143. print("J is enabled!")
  1144. end
  1145. <
  1146. Return: ~
  1147. (`string|integer|boolean?`) value of option
  1148. Option:prepend({value}) *vim.opt:prepend()*
  1149. Prepend a value to string-style options. See |:set^=|
  1150. These are equivalent: >lua
  1151. vim.opt.wildignore:prepend('*.o')
  1152. vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
  1153. <
  1154. Parameters: ~
  1155. • {value} (`string`) Value to prepend
  1156. Option:remove({value}) *vim.opt:remove()*
  1157. Remove a value from string-style options. See |:set-=|
  1158. These are equivalent: >lua
  1159. vim.opt.wildignore:remove('*.pyc')
  1160. vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
  1161. <
  1162. Parameters: ~
  1163. • {value} (`string`) Value to remove
  1164. vim.bo[{bufnr}] *vim.bo*
  1165. Get or set buffer-scoped |options| for the buffer with number {bufnr}.
  1166. Like `:setlocal`. If {bufnr} is omitted then the current buffer is used.
  1167. Invalid {bufnr} or key is an error.
  1168. Example: >lua
  1169. local bufnr = vim.api.nvim_get_current_buf()
  1170. vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
  1171. print(vim.bo.comments)
  1172. print(vim.bo.baz) -- error: invalid key
  1173. <
  1174. vim.env *vim.env*
  1175. Environment variables defined in the editor session. See |expand-env| and
  1176. |:let-environment| for the Vimscript behavior. Invalid or unset key
  1177. returns `nil`.
  1178. Example: >lua
  1179. vim.env.FOO = 'bar'
  1180. print(vim.env.TERM)
  1181. <
  1182. vim.go *vim.go*
  1183. Get or set global |options|. Like `:setglobal`. Invalid key is an error.
  1184. Note: this is different from |vim.o| because this accesses the global
  1185. option value and thus is mostly useful for use with |global-local|
  1186. options.
  1187. Example: >lua
  1188. vim.go.cmdheight = 4
  1189. print(vim.go.columns)
  1190. print(vim.go.bar) -- error: invalid key
  1191. <
  1192. vim.o *vim.o*
  1193. Get or set |options|. Works like `:set`, so buffer/window-scoped options
  1194. target the current buffer/window. Invalid key is an error.
  1195. Example: >lua
  1196. vim.o.cmdheight = 4
  1197. print(vim.o.columns)
  1198. print(vim.o.foo) -- error: invalid key
  1199. <
  1200. vim.wo[{winid}][{bufnr}] *vim.wo*
  1201. Get or set window-scoped |options| for the window with handle {winid} and
  1202. buffer with number {bufnr}. Like `:setlocal` if setting a |global-local|
  1203. option or if {bufnr} is provided, like `:set` otherwise. If {winid} is
  1204. omitted then the current window is used. Invalid {winid}, {bufnr} or key
  1205. is an error.
  1206. Note: only {bufnr} with value `0` (the current buffer in the window) is
  1207. supported.
  1208. Example: >lua
  1209. local winid = vim.api.nvim_get_current_win()
  1210. vim.wo[winid].number = true -- same as vim.wo.number = true
  1211. print(vim.wo.foldmarker)
  1212. print(vim.wo.quux) -- error: invalid key
  1213. vim.wo[winid][0].spell = false -- like ':setlocal nospell'
  1214. <
  1215. ==============================================================================
  1216. Lua module: vim *lua-vim*
  1217. vim.cmd({command}) *vim.cmd()*
  1218. Executes Vimscript (|Ex-commands|).
  1219. Note that `vim.cmd` can be indexed with a command name to return a
  1220. callable function to the command.
  1221. Example: >lua
  1222. vim.cmd('echo 42')
  1223. vim.cmd([[
  1224. augroup My_group
  1225. autocmd!
  1226. autocmd FileType c setlocal cindent
  1227. augroup END
  1228. ]])
  1229. -- Ex command :echo "foo"
  1230. -- Note string literals need to be double quoted.
  1231. vim.cmd('echo "foo"')
  1232. vim.cmd { cmd = 'echo', args = { '"foo"' } }
  1233. vim.cmd.echo({ args = { '"foo"' } })
  1234. vim.cmd.echo('"foo"')
  1235. -- Ex command :write! myfile.txt
  1236. vim.cmd('write! myfile.txt')
  1237. vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true }
  1238. vim.cmd.write { args = { "myfile.txt" }, bang = true }
  1239. vim.cmd.write { "myfile.txt", bang = true }
  1240. -- Ex command :colorscheme blue
  1241. vim.cmd('colorscheme blue')
  1242. vim.cmd.colorscheme('blue')
  1243. <
  1244. Parameters: ~
  1245. • {command} (`string|table`) Command(s) to execute. If a string,
  1246. executes multiple lines of Vimscript at once. In this case,
  1247. it is an alias to |nvim_exec2()|, where `opts.output` is
  1248. set to false. Thus it works identical to |:source|. If a
  1249. table, executes a single command. In this case, it is an
  1250. alias to |nvim_cmd()| where `opts` is empty.
  1251. See also: ~
  1252. • |ex-cmd-index|
  1253. vim.defer_fn({fn}, {timeout}) *vim.defer_fn()*
  1254. Defers calling {fn} until {timeout} ms passes.
  1255. Use to do a one-shot timer that calls {fn} Note: The {fn} is
  1256. |vim.schedule_wrap()|ped automatically, so API functions are safe to call.
  1257. Parameters: ~
  1258. • {fn} (`function`) Callback to call once `timeout` expires
  1259. • {timeout} (`integer`) Number of milliseconds to wait before calling
  1260. `fn`
  1261. Return: ~
  1262. (`table`) timer luv timer object
  1263. *vim.deprecate()*
  1264. vim.deprecate({name}, {alternative}, {version}, {plugin}, {backtrace})
  1265. Shows a deprecation message to the user.
  1266. Parameters: ~
  1267. • {name} (`string`) Deprecated feature (function, API, etc.).
  1268. • {alternative} (`string?`) Suggested alternative feature.
  1269. • {version} (`string`) Version when the deprecated function will be
  1270. removed.
  1271. • {plugin} (`string?`) Name of the plugin that owns the deprecated
  1272. feature. Defaults to "Nvim".
  1273. • {backtrace} (`boolean?`) Prints backtrace. Defaults to true.
  1274. Return: ~
  1275. (`string?`) Deprecated message, or nil if no message was shown.
  1276. vim.inspect() *vim.inspect()*
  1277. Gets a human-readable representation of the given object.
  1278. Return: ~
  1279. (`string`)
  1280. See also: ~
  1281. • |vim.print()|
  1282. • https://github.com/kikito/inspect.lua
  1283. • https://github.com/mpeterv/vinspect
  1284. vim.keycode({str}) *vim.keycode()*
  1285. Translates keycodes.
  1286. Example: >lua
  1287. local k = vim.keycode
  1288. vim.g.mapleader = k'<bs>'
  1289. <
  1290. Parameters: ~
  1291. • {str} (`string`) String to be converted.
  1292. Return: ~
  1293. (`string`)
  1294. See also: ~
  1295. • |nvim_replace_termcodes()|
  1296. vim.lua_omnifunc({find_start}) *vim.lua_omnifunc()*
  1297. Omnifunc for completing Lua values from the runtime Lua interpreter,
  1298. similar to the builtin completion for the `:lua` command.
  1299. Activate using `set omnifunc=v:lua.vim.lua_omnifunc` in a Lua buffer.
  1300. Parameters: ~
  1301. • {find_start} (`1|0`)
  1302. vim.notify({msg}, {level}, {opts}) *vim.notify()*
  1303. Displays a notification to the user.
  1304. This function can be overridden by plugins to display notifications using
  1305. a custom provider (such as the system notification provider). By default,
  1306. writes to |:messages|.
  1307. Parameters: ~
  1308. • {msg} (`string`) Content of the notification to show to the user.
  1309. • {level} (`integer?`) One of the values from |vim.log.levels|.
  1310. • {opts} (`table?`) Optional parameters. Unused by default.
  1311. vim.notify_once({msg}, {level}, {opts}) *vim.notify_once()*
  1312. Displays a notification only one time.
  1313. Like |vim.notify()|, but subsequent calls with the same message will not
  1314. display a notification.
  1315. Parameters: ~
  1316. • {msg} (`string`) Content of the notification to show to the user.
  1317. • {level} (`integer?`) One of the values from |vim.log.levels|.
  1318. • {opts} (`table?`) Optional parameters. Unused by default.
  1319. Return: ~
  1320. (`boolean`) true if message was displayed, else false
  1321. vim.on_key({fn}, {ns_id}, {opts}) *vim.on_key()*
  1322. Adds Lua function {fn} with namespace id {ns_id} as a listener to every,
  1323. yes every, input key.
  1324. The Nvim command-line option |-w| is related but does not support
  1325. callbacks and cannot be toggled dynamically.
  1326. Note: ~
  1327. • {fn} will be removed on error.
  1328. • {fn} won't be invoked recursively, i.e. if {fn} itself consumes input,
  1329. it won't be invoked for those keys.
  1330. • {fn} will not be cleared by |nvim_buf_clear_namespace()|
  1331. Parameters: ~
  1332. • {fn} (`fun(key: string, typed: string): string??`) Function
  1333. invoked for every input key, after mappings have been applied
  1334. but before further processing. Arguments {key} and {typed}
  1335. are raw keycodes, where {key} is the key after mappings are
  1336. applied, and {typed} is the key(s) before mappings are
  1337. applied. {typed} may be empty if {key} is produced by
  1338. non-typed key(s) or by the same typed key(s) that produced a
  1339. previous {key}. If {fn} returns an empty string, {key} is
  1340. discarded/ignored. When {fn} is `nil`, the callback
  1341. associated with namespace {ns_id} is removed.
  1342. • {ns_id} (`integer?`) Namespace ID. If nil or 0, generates and returns
  1343. a new |nvim_create_namespace()| id.
  1344. • {opts} (`table?`) Optional parameters
  1345. Return: ~
  1346. (`integer`) Namespace id associated with {fn}. Or count of all
  1347. callbacks if on_key() is called without arguments.
  1348. See also: ~
  1349. • |keytrans()|
  1350. vim.paste({lines}, {phase}) *vim.paste()*
  1351. Paste handler, invoked by |nvim_paste()|.
  1352. Note: This is provided only as a "hook", don't call it directly; call
  1353. |nvim_paste()| instead, which arranges redo (dot-repeat) and invokes
  1354. `vim.paste`.
  1355. Example: To remove ANSI color codes when pasting: >lua
  1356. vim.paste = (function(overridden)
  1357. return function(lines, phase)
  1358. for i,line in ipairs(lines) do
  1359. -- Scrub ANSI color codes from paste input.
  1360. lines[i] = line:gsub('\27%[[0-9;mK]+', '')
  1361. end
  1362. return overridden(lines, phase)
  1363. end
  1364. end)(vim.paste)
  1365. <
  1366. Parameters: ~
  1367. • {lines} (`string[]`) |readfile()|-style list of lines to paste.
  1368. |channel-lines|
  1369. • {phase} (`-1|1|2|3`) -1: "non-streaming" paste: the call contains all
  1370. lines. If paste is "streamed", `phase` indicates the stream
  1371. state:
  1372. • 1: starts the paste (exactly once)
  1373. • 2: continues the paste (zero or more times)
  1374. • 3: ends the paste (exactly once)
  1375. Return: ~
  1376. (`boolean`) result false if client should cancel the paste.
  1377. See also: ~
  1378. • |paste|
  1379. vim.print({...}) *vim.print()*
  1380. "Pretty prints" the given arguments and returns them unmodified.
  1381. Example: >lua
  1382. local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
  1383. <
  1384. Parameters: ~
  1385. • {...} (`any`)
  1386. Return: ~
  1387. (`any`) given arguments.
  1388. See also: ~
  1389. • |vim.inspect()|
  1390. • |:=|
  1391. vim.schedule_wrap({fn}) *vim.schedule_wrap()*
  1392. Returns a function which calls {fn} via |vim.schedule()|.
  1393. The returned function passes all arguments to {fn}.
  1394. Example: >lua
  1395. function notify_readable(_err, readable)
  1396. vim.notify("readable? " .. tostring(readable))
  1397. end
  1398. vim.uv.fs_access(vim.fn.stdpath("config"), "R", vim.schedule_wrap(notify_readable))
  1399. <
  1400. Parameters: ~
  1401. • {fn} (`function`)
  1402. Return: ~
  1403. (`function`)
  1404. See also: ~
  1405. • |lua-loop-callbacks|
  1406. • |vim.schedule()|
  1407. • |vim.in_fast_event()|
  1408. *vim.str_byteindex()*
  1409. vim.str_byteindex({s}, {encoding}, {index}, {strict_indexing})
  1410. Convert UTF-32, UTF-16 or UTF-8 {index} to byte index. If
  1411. {strict_indexing} is false then then an out of range index will return
  1412. byte length instead of throwing an error.
  1413. Invalid UTF-8 and NUL is treated like in |vim.str_utfindex()|. An {index}
  1414. in the middle of a UTF-16 sequence is rounded upwards to the end of that
  1415. sequence.
  1416. Parameters: ~
  1417. • {s} (`string`)
  1418. • {encoding} (`"utf-8"|"utf-16"|"utf-32"`)
  1419. • {index} (`integer`)
  1420. • {strict_indexing} (`boolean?`) default: true
  1421. Return: ~
  1422. (`integer`)
  1423. *vim.str_utfindex()*
  1424. vim.str_utfindex({s}, {encoding}, {index}, {strict_indexing})
  1425. Convert byte index to UTF-32, UTF-16 or UTF-8 indices. If {index} is not
  1426. supplied, the length of the string is used. All indices are zero-based.
  1427. If {strict_indexing} is false then an out of range index will return
  1428. string length instead of throwing an error. Invalid UTF-8 bytes, and
  1429. embedded surrogates are counted as one code point each. An {index} in the
  1430. middle of a UTF-8 sequence is rounded upwards to the end of that sequence.
  1431. Parameters: ~
  1432. • {s} (`string`)
  1433. • {encoding} (`"utf-8"|"utf-16"|"utf-32"`)
  1434. • {index} (`integer?`)
  1435. • {strict_indexing} (`boolean?`) default: true
  1436. Return: ~
  1437. (`integer`)
  1438. vim.system({cmd}, {opts}, {on_exit}) *vim.system()*
  1439. Runs a system command or throws an error if {cmd} cannot be run.
  1440. Examples: >lua
  1441. local on_exit = function(obj)
  1442. print(obj.code)
  1443. print(obj.signal)
  1444. print(obj.stdout)
  1445. print(obj.stderr)
  1446. end
  1447. -- Runs asynchronously:
  1448. vim.system({'echo', 'hello'}, { text = true }, on_exit)
  1449. -- Runs synchronously:
  1450. local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
  1451. -- { code = 0, signal = 0, stdout = 'hello\n', stderr = '' }
  1452. <
  1453. See |uv.spawn()| for more details. Note: unlike |uv.spawn()|, vim.system
  1454. throws an error if {cmd} cannot be run.
  1455. Parameters: ~
  1456. • {cmd} (`string[]`) Command to execute
  1457. • {opts} (`vim.SystemOpts?`) Options:
  1458. • cwd: (string) Set the current working directory for the
  1459. sub-process.
  1460. • env: table<string,string> Set environment variables for
  1461. the new process. Inherits the current environment with
  1462. `NVIM` set to |v:servername|.
  1463. • clear_env: (boolean) `env` defines the job environment
  1464. exactly, instead of merging current environment.
  1465. • stdin: (string|string[]|boolean) If `true`, then a pipe
  1466. to stdin is opened and can be written to via the
  1467. `write()` method to SystemObj. If string or string[] then
  1468. will be written to stdin and closed. Defaults to `false`.
  1469. • stdout: (boolean|function) Handle output from stdout.
  1470. When passed as a function must have the signature
  1471. `fun(err: string, data: string)`. Defaults to `true`
  1472. • stderr: (boolean|function) Handle output from stderr.
  1473. When passed as a function must have the signature
  1474. `fun(err: string, data: string)`. Defaults to `true`.
  1475. • text: (boolean) Handle stdout and stderr as text.
  1476. Replaces `\r\n` with `\n`.
  1477. • timeout: (integer) Run the command with a time limit.
  1478. Upon timeout the process is sent the TERM signal (15) and
  1479. the exit code is set to 124.
  1480. • detach: (boolean) If true, spawn the child process in a
  1481. detached state - this will make it a process group
  1482. leader, and will effectively enable the child to keep
  1483. running after the parent exits. Note that the child
  1484. process will still keep the parent's event loop alive
  1485. unless the parent process calls |uv.unref()| on the
  1486. child's process handle.
  1487. • {on_exit} (`fun(out: vim.SystemCompleted)?`) Called when subprocess
  1488. exits. When provided, the command runs asynchronously.
  1489. Receives SystemCompleted object, see return of
  1490. SystemObj:wait().
  1491. Return: ~
  1492. (`vim.SystemObj`) Object with the fields:
  1493. • cmd (string[]) Command name and args
  1494. • pid (integer) Process ID
  1495. • wait (fun(timeout: integer|nil): SystemCompleted) Wait for the
  1496. process to complete. Upon timeout the process is sent the KILL
  1497. signal (9) and the exit code is set to 124. Cannot be called in
  1498. |api-fast|.
  1499. • SystemCompleted is an object with the fields:
  1500. • code: (integer)
  1501. • signal: (integer)
  1502. • stdout: (string), nil if stdout argument is passed
  1503. • stderr: (string), nil if stderr argument is passed
  1504. • kill (fun(signal: integer|string))
  1505. • write (fun(data: string|nil)) Requires `stdin=true`. Pass `nil` to
  1506. close the stream.
  1507. • is_closing (fun(): boolean)
  1508. ==============================================================================
  1509. Lua module: vim.inspector *vim.inspector*
  1510. vim.inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()*
  1511. Get all the items at a given buffer position.
  1512. Can also be pretty-printed with `:Inspect!`. *:Inspect!*
  1513. Attributes: ~
  1514. Since: 0.9.0
  1515. Parameters: ~
  1516. • {bufnr} (`integer?`) defaults to the current buffer
  1517. • {row} (`integer?`) row to inspect, 0-based. Defaults to the row of
  1518. the current cursor
  1519. • {col} (`integer?`) col to inspect, 0-based. Defaults to the col of
  1520. the current cursor
  1521. • {filter} (`table?`) Table with key-value pairs to filter the items
  1522. • {syntax} (`boolean`, default: `true`) Include syntax based
  1523. highlight groups.
  1524. • {treesitter} (`boolean`, default: `true`) Include
  1525. treesitter based highlight groups.
  1526. • {extmarks} (`boolean|"all"`, default: true) Include
  1527. extmarks. When `all`, then extmarks without a `hl_group`
  1528. will also be included.
  1529. • {semantic_tokens} (`boolean`, default: true) Include
  1530. semantic token highlights.
  1531. Return: ~
  1532. (`table`) a table with the following key-value pairs. Items are in
  1533. "traversal order":
  1534. • treesitter: a list of treesitter captures
  1535. • syntax: a list of syntax groups
  1536. • semantic_tokens: a list of semantic tokens
  1537. • extmarks: a list of extmarks
  1538. • buffer: the buffer used to get the items
  1539. • row: the row used to get the items
  1540. • col: the col used to get the items
  1541. vim.show_pos({bufnr}, {row}, {col}, {filter}) *vim.show_pos()*
  1542. Show all the items at a given buffer position.
  1543. Can also be shown with `:Inspect`. *:Inspect*
  1544. Example: To bind this function to the vim-scriptease inspired `zS` in
  1545. Normal mode: >lua
  1546. vim.keymap.set('n', 'zS', vim.show_pos)
  1547. <
  1548. Attributes: ~
  1549. Since: 0.9.0
  1550. Parameters: ~
  1551. • {bufnr} (`integer?`) defaults to the current buffer
  1552. • {row} (`integer?`) row to inspect, 0-based. Defaults to the row of
  1553. the current cursor
  1554. • {col} (`integer?`) col to inspect, 0-based. Defaults to the col of
  1555. the current cursor
  1556. • {filter} (`table?`) A table with the following fields:
  1557. • {syntax} (`boolean`, default: `true`) Include syntax based
  1558. highlight groups.
  1559. • {treesitter} (`boolean`, default: `true`) Include
  1560. treesitter based highlight groups.
  1561. • {extmarks} (`boolean|"all"`, default: true) Include
  1562. extmarks. When `all`, then extmarks without a `hl_group`
  1563. will also be included.
  1564. • {semantic_tokens} (`boolean`, default: true) Include
  1565. semantic token highlights.
  1566. *vim.Ringbuf*
  1567. Fields: ~
  1568. • {clear} (`fun()`) See |Ringbuf:clear()|.
  1569. • {push} (`fun(item: T)`) See |Ringbuf:push()|.
  1570. • {pop} (`fun(): T?`) See |Ringbuf:pop()|.
  1571. • {peek} (`fun(): T?`) See |Ringbuf:peek()|.
  1572. Ringbuf:clear() *Ringbuf:clear()*
  1573. Clear all items
  1574. Ringbuf:peek() *Ringbuf:peek()*
  1575. Returns the first unread item without removing it
  1576. Return: ~
  1577. (`any?`)
  1578. Ringbuf:pop() *Ringbuf:pop()*
  1579. Removes and returns the first unread item
  1580. Return: ~
  1581. (`any?`)
  1582. Ringbuf:push({item}) *Ringbuf:push()*
  1583. Adds an item, overriding the oldest item if the buffer is full.
  1584. Parameters: ~
  1585. • {item} (`any`)
  1586. vim.deep_equal({a}, {b}) *vim.deep_equal()*
  1587. Deep compare values for equality
  1588. Tables are compared recursively unless they both provide the `eq`
  1589. metamethod. All other types are compared using the equality `==` operator.
  1590. Parameters: ~
  1591. • {a} (`any`) First value
  1592. • {b} (`any`) Second value
  1593. Return: ~
  1594. (`boolean`) `true` if values are equals, else `false`
  1595. vim.deepcopy({orig}, {noref}) *vim.deepcopy()*
  1596. Returns a deep copy of the given object. Non-table objects are copied as
  1597. in a typical Lua assignment, whereas table objects are copied recursively.
  1598. Functions are naively copied, so functions in the copied table point to
  1599. the same functions as those in the input table. Userdata and threads are
  1600. not copied and will throw an error.
  1601. Note: `noref=true` is much more performant on tables with unique table
  1602. fields, while `noref=false` is more performant on tables that reuse table
  1603. fields.
  1604. Parameters: ~
  1605. • {orig} (`table`) Table to copy
  1606. • {noref} (`boolean?`) When `false` (default) a contained table is only
  1607. copied once and all references point to this single copy.
  1608. When `true` every occurrence of a table results in a new
  1609. copy. This also means that a cyclic reference can cause
  1610. `deepcopy()` to fail.
  1611. Return: ~
  1612. (`table`) Table of copied keys and (nested) values.
  1613. vim.defaulttable({createfn}) *vim.defaulttable()*
  1614. Creates a table whose missing keys are provided by {createfn} (like
  1615. Python's "defaultdict").
  1616. If {createfn} is `nil` it defaults to defaulttable() itself, so accessing
  1617. nested keys creates nested tables: >lua
  1618. local a = vim.defaulttable()
  1619. a.b.c = 1
  1620. <
  1621. Parameters: ~
  1622. • {createfn} (`fun(key:any):any?`) Provides the value for a missing
  1623. `key`.
  1624. Return: ~
  1625. (`table`) Empty table with `__index` metamethod.
  1626. vim.endswith({s}, {suffix}) *vim.endswith()*
  1627. Tests if `s` ends with `suffix`.
  1628. Parameters: ~
  1629. • {s} (`string`) String
  1630. • {suffix} (`string`) Suffix to match
  1631. Return: ~
  1632. (`boolean`) `true` if `suffix` is a suffix of `s`
  1633. vim.gsplit({s}, {sep}, {opts}) *vim.gsplit()*
  1634. Gets an |iterator| that splits a string at each instance of a separator,
  1635. in "lazy" fashion (as opposed to |vim.split()| which is "eager").
  1636. Example: >lua
  1637. for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
  1638. print(s)
  1639. end
  1640. <
  1641. If you want to also inspect the separator itself (instead of discarding
  1642. it), use |string.gmatch()|. Example: >lua
  1643. for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
  1644. print(('word: %s num: %s'):format(word, num))
  1645. end
  1646. <
  1647. Parameters: ~
  1648. • {s} (`string`) String to split
  1649. • {sep} (`string`) Separator or pattern
  1650. • {opts} (`table?`) Keyword arguments |kwargs|:
  1651. • {plain}? (`boolean`) Use `sep` literally (as in
  1652. string.find).
  1653. • {trimempty}? (`boolean`) Discard empty segments at start and
  1654. end of the sequence.
  1655. Return: ~
  1656. (`fun():string?`) Iterator over the split components
  1657. See also: ~
  1658. • |string.gmatch()|
  1659. • |vim.split()|
  1660. • |lua-patterns|
  1661. • https://www.lua.org/pil/20.2.html
  1662. • http://lua-users.org/wiki/StringLibraryTutorial
  1663. vim.is_callable({f}) *vim.is_callable()*
  1664. Returns true if object `f` can be called as a function.
  1665. Parameters: ~
  1666. • {f} (`any`) Any object
  1667. Return: ~
  1668. (`boolean`) `true` if `f` is callable, else `false`
  1669. vim.isarray({t}) *vim.isarray()*
  1670. Tests if `t` is an "array": a table indexed only by integers (potentially
  1671. non-contiguous).
  1672. If the indexes start from 1 and are contiguous then the array is also a
  1673. list. |vim.islist()|
  1674. Empty table `{}` is an array, unless it was created by |vim.empty_dict()|
  1675. or returned as a dict-like |API| or Vimscript result, for example from
  1676. |rpcrequest()| or |vim.fn|.
  1677. Parameters: ~
  1678. • {t} (`table?`)
  1679. Return: ~
  1680. (`boolean`) `true` if array-like table, else `false`.
  1681. See also: ~
  1682. • https://github.com/openresty/luajit2#tableisarray
  1683. vim.islist({t}) *vim.islist()*
  1684. Tests if `t` is a "list": a table indexed only by contiguous integers
  1685. starting from 1 (what |lua-length| calls a "regular array").
  1686. Empty table `{}` is a list, unless it was created by |vim.empty_dict()| or
  1687. returned as a dict-like |API| or Vimscript result, for example from
  1688. |rpcrequest()| or |vim.fn|.
  1689. Parameters: ~
  1690. • {t} (`table?`)
  1691. Return: ~
  1692. (`boolean`) `true` if list-like table, else `false`.
  1693. See also: ~
  1694. • |vim.isarray()|
  1695. vim.list_contains({t}, {value}) *vim.list_contains()*
  1696. Checks if a list-like table (integer keys without gaps) contains `value`.
  1697. Parameters: ~
  1698. • {t} (`table`) Table to check (must be list-like, not validated)
  1699. • {value} (`any`) Value to compare
  1700. Return: ~
  1701. (`boolean`) `true` if `t` contains `value`
  1702. See also: ~
  1703. • |vim.tbl_contains()| for checking values in general tables
  1704. vim.list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()*
  1705. Extends a list-like table with the values of another list-like table.
  1706. NOTE: This mutates dst!
  1707. Parameters: ~
  1708. • {dst} (`table`) List which will be modified and appended to
  1709. • {src} (`table`) List from which values will be inserted
  1710. • {start} (`integer?`) Start index on src. Defaults to 1
  1711. • {finish} (`integer?`) Final index on src. Defaults to `#src`
  1712. Return: ~
  1713. (`table`) dst
  1714. See also: ~
  1715. • |vim.tbl_extend()|
  1716. vim.list_slice({list}, {start}, {finish}) *vim.list_slice()*
  1717. Creates a copy of a table containing only elements from start to end
  1718. (inclusive)
  1719. Parameters: ~
  1720. • {list} (`any[]`) Table
  1721. • {start} (`integer?`) Start range of slice
  1722. • {finish} (`integer?`) End range of slice
  1723. Return: ~
  1724. (`any[]`) Copy of table sliced from start to finish (inclusive)
  1725. vim.pesc({s}) *vim.pesc()*
  1726. Escapes magic chars in |lua-patterns|.
  1727. Parameters: ~
  1728. • {s} (`string`) String to escape
  1729. Return: ~
  1730. (`string`) %-escaped pattern string
  1731. See also: ~
  1732. • https://github.com/rxi/lume
  1733. vim.ringbuf({size}) *vim.ringbuf()*
  1734. Create a ring buffer limited to a maximal number of items. Once the buffer
  1735. is full, adding a new entry overrides the oldest entry. >lua
  1736. local ringbuf = vim.ringbuf(4)
  1737. ringbuf:push("a")
  1738. ringbuf:push("b")
  1739. ringbuf:push("c")
  1740. ringbuf:push("d")
  1741. ringbuf:push("e") -- overrides "a"
  1742. print(ringbuf:pop()) -- returns "b"
  1743. print(ringbuf:pop()) -- returns "c"
  1744. -- Can be used as iterator. Pops remaining items:
  1745. for val in ringbuf do
  1746. print(val)
  1747. end
  1748. <
  1749. Returns a Ringbuf instance with the following methods:
  1750. • |Ringbuf:push()|
  1751. • |Ringbuf:pop()|
  1752. • |Ringbuf:peek()|
  1753. • |Ringbuf:clear()|
  1754. Parameters: ~
  1755. • {size} (`integer`)
  1756. Return: ~
  1757. (`vim.Ringbuf`) ringbuf See |vim.Ringbuf|.
  1758. vim.spairs({t}) *vim.spairs()*
  1759. Enumerates key-value pairs of a table, ordered by key.
  1760. Parameters: ~
  1761. • {t} (`table`) Dict-like table
  1762. Return (multiple): ~
  1763. (`fun(table: table<K, V>, index?: K):K, V`) |for-in| iterator over
  1764. sorted keys and their values
  1765. (`table`)
  1766. See also: ~
  1767. • Based on
  1768. https://github.com/premake/premake-core/blob/master/src/base/table.lua
  1769. vim.split({s}, {sep}, {opts}) *vim.split()*
  1770. Splits a string at each instance of a separator and returns the result as
  1771. a table (unlike |vim.gsplit()|).
  1772. Examples: >lua
  1773. split(":aa::b:", ":") --> {'','aa','','b',''}
  1774. split("axaby", "ab?") --> {'','x','y'}
  1775. split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'}
  1776. split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
  1777. <
  1778. Parameters: ~
  1779. • {s} (`string`) String to split
  1780. • {sep} (`string`) Separator or pattern
  1781. • {opts} (`table?`) Keyword arguments |kwargs|:
  1782. • {plain}? (`boolean`) Use `sep` literally (as in
  1783. string.find).
  1784. • {trimempty}? (`boolean`) Discard empty segments at start and
  1785. end of the sequence.
  1786. Return: ~
  1787. (`string[]`) List of split components
  1788. See also: ~
  1789. • |vim.gsplit()|
  1790. • |string.gmatch()|
  1791. vim.startswith({s}, {prefix}) *vim.startswith()*
  1792. Tests if `s` starts with `prefix`.
  1793. Parameters: ~
  1794. • {s} (`string`) String
  1795. • {prefix} (`string`) Prefix to match
  1796. Return: ~
  1797. (`boolean`) `true` if `prefix` is a prefix of `s`
  1798. vim.tbl_contains({t}, {value}, {opts}) *vim.tbl_contains()*
  1799. Checks if a table contains a given value, specified either directly or via
  1800. a predicate that is checked for each value.
  1801. Example: >lua
  1802. vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
  1803. return vim.deep_equal(v, { 'b', 'c' })
  1804. end, { predicate = true })
  1805. -- true
  1806. <
  1807. Parameters: ~
  1808. • {t} (`table`) Table to check
  1809. • {value} (`any`) Value to compare or predicate function reference
  1810. • {opts} (`table?`) Keyword arguments |kwargs|:
  1811. • {predicate}? (`boolean`) `value` is a function reference to
  1812. be checked (default false)
  1813. Return: ~
  1814. (`boolean`) `true` if `t` contains `value`
  1815. See also: ~
  1816. • |vim.list_contains()| for checking values in list-like tables
  1817. vim.tbl_count({t}) *vim.tbl_count()*
  1818. Counts the number of non-nil values in table `t`. >lua
  1819. vim.tbl_count({ a=1, b=2 }) --> 2
  1820. vim.tbl_count({ 1, 2 }) --> 2
  1821. <
  1822. Parameters: ~
  1823. • {t} (`table`) Table
  1824. Return: ~
  1825. (`integer`) Number of non-nil values in table
  1826. See also: ~
  1827. • https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
  1828. vim.tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()*
  1829. Merges recursively two or more tables.
  1830. Only values that are empty tables or tables that are not |lua-list|s
  1831. (indexed by consecutive integers starting from 1) are merged recursively.
  1832. This is useful for merging nested tables like default and user
  1833. configurations where lists should be treated as literals (i.e., are
  1834. overwritten instead of merged).
  1835. Parameters: ~
  1836. • {behavior} (`'error'|'keep'|'force'`) Decides what to do if a key is
  1837. found in more than one map:
  1838. • "error": raise an error
  1839. • "keep": use value from the leftmost map
  1840. • "force": use value from the rightmost map
  1841. • {...} (`table`) Two or more tables
  1842. Return: ~
  1843. (`table`) Merged table
  1844. See also: ~
  1845. • |vim.tbl_extend()|
  1846. vim.tbl_extend({behavior}, {...}) *vim.tbl_extend()*
  1847. Merges two or more tables.
  1848. Parameters: ~
  1849. • {behavior} (`'error'|'keep'|'force'`) Decides what to do if a key is
  1850. found in more than one map:
  1851. • "error": raise an error
  1852. • "keep": use value from the leftmost map
  1853. • "force": use value from the rightmost map
  1854. • {...} (`table`) Two or more tables
  1855. Return: ~
  1856. (`table`) Merged table
  1857. See also: ~
  1858. • |extend()|
  1859. vim.tbl_filter({func}, {t}) *vim.tbl_filter()*
  1860. Filter a table using a predicate function
  1861. Parameters: ~
  1862. • {func} (`function`) Function
  1863. • {t} (`table`) Table
  1864. Return: ~
  1865. (`any[]`) Table of filtered values
  1866. vim.tbl_get({o}, {...}) *vim.tbl_get()*
  1867. Index into a table (first argument) via string keys passed as subsequent
  1868. arguments. Return `nil` if the key does not exist.
  1869. Examples: >lua
  1870. vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
  1871. vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
  1872. <
  1873. Parameters: ~
  1874. • {o} (`table`) Table to index
  1875. • {...} (`any`) Optional keys (0 or more, variadic) via which to index
  1876. the table
  1877. Return: ~
  1878. (`any`) Nested value indexed by key (if it exists), else nil
  1879. vim.tbl_isempty({t}) *vim.tbl_isempty()*
  1880. Checks if a table is empty.
  1881. Parameters: ~
  1882. • {t} (`table`) Table to check
  1883. Return: ~
  1884. (`boolean`) `true` if `t` is empty
  1885. See also: ~
  1886. • https://github.com/premake/premake-core/blob/master/src/base/table.lua
  1887. vim.tbl_keys({t}) *vim.tbl_keys()*
  1888. Return a list of all keys used in a table. However, the order of the
  1889. return table of keys is not guaranteed.
  1890. Parameters: ~
  1891. • {t} (`table`) Table
  1892. Return: ~
  1893. (`any[]`) List of keys
  1894. See also: ~
  1895. • From
  1896. https://github.com/premake/premake-core/blob/master/src/base/table.lua
  1897. vim.tbl_map({func}, {t}) *vim.tbl_map()*
  1898. Apply a function to all values of a table.
  1899. Parameters: ~
  1900. • {func} (`fun(value: T): any`) Function
  1901. • {t} (`table<any, T>`) Table
  1902. Return: ~
  1903. (`table`) Table of transformed values
  1904. vim.tbl_values({t}) *vim.tbl_values()*
  1905. Return a list of all values used in a table. However, the order of the
  1906. return table of values is not guaranteed.
  1907. Parameters: ~
  1908. • {t} (`table`) Table
  1909. Return: ~
  1910. (`any[]`) List of values
  1911. vim.trim({s}) *vim.trim()*
  1912. Trim whitespace (Lua pattern "%s") from both sides of a string.
  1913. Parameters: ~
  1914. • {s} (`string`) String to trim
  1915. Return: ~
  1916. (`string`) String with whitespace removed from its beginning and end
  1917. See also: ~
  1918. • |lua-patterns|
  1919. • https://www.lua.org/pil/20.2.html
  1920. *vim.validate()*
  1921. vim.validate({name}, {value}, {validator}, {optional}, {message})
  1922. Validate function arguments.
  1923. This function has two valid forms:
  1924. 1. `vim.validate(name, value, validator[, optional][, message])`
  1925. Validates that argument {name} with value {value} satisfies
  1926. {validator}. If {optional} is given and is `true`, then {value} may be
  1927. `nil`. If {message} is given, then it is used as the expected type in
  1928. the error message.
  1929. Example: >lua
  1930. function vim.startswith(s, prefix)
  1931. vim.validate('s', s, 'string')
  1932. vim.validate('prefix', prefix, 'string')
  1933. -- ...
  1934. end
  1935. <
  1936. 2. `vim.validate(spec)` (deprecated) where `spec` is of type
  1937. `table<string,[value:any, validator: vim.validate.Validator, optional_or_msg? : boolean|string]>)`
  1938. Validates a argument specification. Specs are evaluated in alphanumeric
  1939. order, until the first failure.
  1940. Example: >lua
  1941. function user.new(name, age, hobbies)
  1942. vim.validate{
  1943. name={name, 'string'},
  1944. age={age, 'number'},
  1945. hobbies={hobbies, 'table'},
  1946. }
  1947. -- ...
  1948. end
  1949. <
  1950. Examples with explicit argument values (can be run directly): >lua
  1951. vim.validate('arg1', {'foo'}, 'table')
  1952. --> NOP (success)
  1953. vim.validate('arg2', 'foo', 'string')
  1954. --> NOP (success)
  1955. vim.validate('arg1', 1, 'table')
  1956. --> error('arg1: expected table, got number')
  1957. vim.validate('arg1', 3, function(a) return (a % 2) == 0 end, 'even number')
  1958. --> error('arg1: expected even number, got 3')
  1959. <
  1960. If multiple types are valid they can be given as a list. >lua
  1961. vim.validate('arg1', {'foo'}, {'table', 'string'})
  1962. vim.validate('arg2', 'foo', {'table', 'string'})
  1963. -- NOP (success)
  1964. vim.validate('arg1', 1, {'string', 'table'})
  1965. -- error('arg1: expected string|table, got number')
  1966. <
  1967. Note: ~
  1968. • `validator` set to a value returned by |lua-type()| provides the best
  1969. performance.
  1970. Parameters: ~
  1971. • {name} (`string`) Argument name
  1972. • {value} (`any`) Argument value
  1973. • {validator} (`vim.validate.Validator`)
  1974. • (`string|string[]`): Any value that can be returned
  1975. from |lua-type()| in addition to `'callable'`:
  1976. `'boolean'`, `'callable'`, `'function'`, `'nil'`,
  1977. `'number'`, `'string'`, `'table'`, `'thread'`,
  1978. `'userdata'`.
  1979. • (`fun(val:any): boolean, string?`) A function that
  1980. returns a boolean and an optional string message.
  1981. • {optional} (`boolean?`) Argument is optional (may be omitted)
  1982. • {message} (`string?`) message when validation fails
  1983. ==============================================================================
  1984. Lua module: vim.loader *vim.loader*
  1985. vim.loader.enable({enable}) *vim.loader.enable()*
  1986. WARNING: This feature is experimental/unstable.
  1987. Enables or disables the experimental Lua module loader:
  1988. Enable (`enable=true`):
  1989. • overrides |loadfile()|
  1990. • adds the Lua loader using the byte-compilation cache
  1991. • adds the libs loader
  1992. • removes the default Nvim loader
  1993. Disable (`enable=false`):
  1994. • removes the loaders
  1995. • adds the default Nvim loader
  1996. Parameters: ~
  1997. • {enable} (`boolean?`) true/nil to enable, false to disable
  1998. vim.loader.find({modname}, {opts}) *vim.loader.find()*
  1999. WARNING: This feature is experimental/unstable.
  2000. Finds Lua modules for the given module name.
  2001. Parameters: ~
  2002. • {modname} (`string`) Module name, or `"*"` to find the top-level
  2003. modules instead
  2004. • {opts} (`table?`) Options for finding a module:
  2005. • {rtp}? (`boolean`, default: `true`) Search for modname in
  2006. the runtime path.
  2007. • {paths}? (`string[]`, default: `{}`) Extra paths to
  2008. search for modname
  2009. • {patterns}? (`string[]`, default:
  2010. `{"/init.lua", ".lua"}`) List of patterns to use when
  2011. searching for modules. A pattern is a string added to the
  2012. basename of the Lua module being searched.
  2013. • {all}? (`boolean`, default: `false`) Search for all
  2014. matches.
  2015. Return: ~
  2016. (`table[]`) A list of objects with the following fields:
  2017. • {modpath} (`string`) Path of the module
  2018. • {modname} (`string`) Name of the module
  2019. • {stat}? (`uv.fs_stat.result`) The fs_stat of the module path. Won't
  2020. be returned for `modname="*"`
  2021. vim.loader.reset({path}) *vim.loader.reset()*
  2022. WARNING: This feature is experimental/unstable.
  2023. Resets the cache for the path, or all the paths if path is nil.
  2024. Parameters: ~
  2025. • {path} (`string?`) path to reset
  2026. ==============================================================================
  2027. Lua module: vim.uri *vim.uri*
  2028. vim.uri_decode({str}) *vim.uri_decode()*
  2029. URI-decodes a string containing percent escapes.
  2030. Parameters: ~
  2031. • {str} (`string`) string to decode
  2032. Return: ~
  2033. (`string`) decoded string
  2034. vim.uri_encode({str}, {rfc}) *vim.uri_encode()*
  2035. URI-encodes a string using percent escapes.
  2036. Parameters: ~
  2037. • {str} (`string`) string to encode
  2038. • {rfc} (`"rfc2396"|"rfc2732"|"rfc3986"?`)
  2039. Return: ~
  2040. (`string`) encoded string
  2041. vim.uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()*
  2042. Gets a URI from a bufnr.
  2043. Parameters: ~
  2044. • {bufnr} (`integer`)
  2045. Return: ~
  2046. (`string`) URI
  2047. vim.uri_from_fname({path}) *vim.uri_from_fname()*
  2048. Gets a URI from a file path.
  2049. Parameters: ~
  2050. • {path} (`string`) Path to file
  2051. Return: ~
  2052. (`string`) URI
  2053. vim.uri_to_bufnr({uri}) *vim.uri_to_bufnr()*
  2054. Gets the buffer for a uri. Creates a new unloaded buffer if no buffer for
  2055. the uri already exists.
  2056. Parameters: ~
  2057. • {uri} (`string`)
  2058. Return: ~
  2059. (`integer`) bufnr
  2060. vim.uri_to_fname({uri}) *vim.uri_to_fname()*
  2061. Gets a filename from a URI.
  2062. Parameters: ~
  2063. • {uri} (`string`)
  2064. Return: ~
  2065. (`string`) filename or unchanged URI for non-file URIs
  2066. ==============================================================================
  2067. Lua module: vim.ui *vim.ui*
  2068. vim.ui.input({opts}, {on_confirm}) *vim.ui.input()*
  2069. Prompts the user for input, allowing arbitrary (potentially asynchronous)
  2070. work until `on_confirm`.
  2071. Example: >lua
  2072. vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
  2073. vim.o.shiftwidth = tonumber(input)
  2074. end)
  2075. <
  2076. Parameters: ~
  2077. • {opts} (`table?`) Additional options. See |input()|
  2078. • prompt (string|nil) Text of the prompt
  2079. • default (string|nil) Default reply to the input
  2080. • completion (string|nil) Specifies type of completion
  2081. supported for input. Supported types are the same that
  2082. can be supplied to a user-defined command using the
  2083. "-complete=" argument. See |:command-completion|
  2084. • highlight (function) Function that will be used for
  2085. highlighting user inputs.
  2086. • {on_confirm} (`function`) ((input|nil) -> ()) Called once the user
  2087. confirms or abort the input. `input` is what the user
  2088. typed (it might be an empty string if nothing was
  2089. entered), or `nil` if the user aborted the dialog.
  2090. vim.ui.open({path}, {opt}) *vim.ui.open()*
  2091. Opens `path` with the system default handler (macOS `open`, Windows
  2092. `explorer.exe`, Linux `xdg-open`, …), or returns (but does not show) an
  2093. error message on failure.
  2094. Expands "~/" and environment variables in filesystem paths.
  2095. Examples: >lua
  2096. -- Asynchronous.
  2097. vim.ui.open("https://neovim.io/")
  2098. vim.ui.open("~/path/to/file")
  2099. -- Use the "osurl" command to handle the path or URL.
  2100. vim.ui.open("gh#neovim/neovim!29490", { cmd = { 'osurl' } })
  2101. -- Synchronous (wait until the process exits).
  2102. local cmd, err = vim.ui.open("$VIMRUNTIME")
  2103. if cmd then
  2104. cmd:wait()
  2105. end
  2106. <
  2107. Parameters: ~
  2108. • {path} (`string`) Path or URL to open
  2109. • {opt} (`{ cmd?: string[] }?`) Options
  2110. • cmd string[]|nil Command used to open the path or URL.
  2111. Return (multiple): ~
  2112. (`vim.SystemObj?`) Command object, or nil if not found.
  2113. (`string?`) Error message on failure, or nil on success.
  2114. See also: ~
  2115. • |vim.system()|
  2116. vim.ui.select({items}, {opts}, {on_choice}) *vim.ui.select()*
  2117. Prompts the user to pick from a list of items, allowing arbitrary
  2118. (potentially asynchronous) work until `on_choice`.
  2119. Example: >lua
  2120. vim.ui.select({ 'tabs', 'spaces' }, {
  2121. prompt = 'Select tabs or spaces:',
  2122. format_item = function(item)
  2123. return "I'd like to choose " .. item
  2124. end,
  2125. }, function(choice)
  2126. if choice == 'spaces' then
  2127. vim.o.expandtab = true
  2128. else
  2129. vim.o.expandtab = false
  2130. end
  2131. end)
  2132. <
  2133. Parameters: ~
  2134. • {items} (`any[]`) Arbitrary items
  2135. • {opts} (`table`) Additional options
  2136. • prompt (string|nil) Text of the prompt. Defaults to
  2137. `Select one of:`
  2138. • format_item (function item -> text) Function to format
  2139. an individual item from `items`. Defaults to
  2140. `tostring`.
  2141. • kind (string|nil) Arbitrary hint string indicating the
  2142. item shape. Plugins reimplementing `vim.ui.select` may
  2143. wish to use this to infer the structure or semantics of
  2144. `items`, or the context in which select() was called.
  2145. • {on_choice} (`fun(item: T?, idx: integer?)`) Called once the user
  2146. made a choice. `idx` is the 1-based index of `item`
  2147. within `items`. `nil` if the user aborted the dialog.
  2148. ==============================================================================
  2149. Lua module: vim.filetype *vim.filetype*
  2150. vim.filetype.add({filetypes}) *vim.filetype.add()*
  2151. Add new filetype mappings.
  2152. Filetype mappings can be added either by extension or by filename (either
  2153. the "tail" or the full file path). The full file path is checked first,
  2154. followed by the file name. If a match is not found using the filename,
  2155. then the filename is matched against the list of |lua-patterns| (sorted by
  2156. priority) until a match is found. Lastly, if pattern matching does not
  2157. find a filetype, then the file extension is used.
  2158. The filetype can be either a string (in which case it is used as the
  2159. filetype directly) or a function. If a function, it takes the full path
  2160. and buffer number of the file as arguments (along with captures from the
  2161. matched pattern, if any) and should return a string that will be used as
  2162. the buffer's filetype. Optionally, the function can return a second
  2163. function value which, when called, modifies the state of the buffer. This
  2164. can be used to, for example, set filetype-specific buffer variables. This
  2165. function will be called by Nvim before setting the buffer's filetype.
  2166. Filename patterns can specify an optional priority to resolve cases when a
  2167. file path matches multiple patterns. Higher priorities are matched first.
  2168. When omitted, the priority defaults to 0. A pattern can contain
  2169. environment variables of the form "${SOME_VAR}" that will be automatically
  2170. expanded. If the environment variable is not set, the pattern won't be
  2171. matched.
  2172. See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
  2173. Example: >lua
  2174. vim.filetype.add({
  2175. extension = {
  2176. foo = 'fooscript',
  2177. bar = function(path, bufnr)
  2178. if some_condition() then
  2179. return 'barscript', function(bufnr)
  2180. -- Set a buffer variable
  2181. vim.b[bufnr].barscript_version = 2
  2182. end
  2183. end
  2184. return 'bar'
  2185. end,
  2186. },
  2187. filename = {
  2188. ['.foorc'] = 'toml',
  2189. ['/etc/foo/config'] = 'toml',
  2190. },
  2191. pattern = {
  2192. ['.*/etc/foo/.*'] = 'fooscript',
  2193. -- Using an optional priority
  2194. ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } },
  2195. -- A pattern containing an environment variable
  2196. ['${XDG_CONFIG_HOME}/foo/git'] = 'git',
  2197. ['.*README.(%a+)'] = function(path, bufnr, ext)
  2198. if ext == 'md' then
  2199. return 'markdown'
  2200. elseif ext == 'rst' then
  2201. return 'rst'
  2202. end
  2203. end,
  2204. },
  2205. })
  2206. <
  2207. To add a fallback match on contents, use >lua
  2208. vim.filetype.add {
  2209. pattern = {
  2210. ['.*'] = {
  2211. function(path, bufnr)
  2212. local content = vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] or ''
  2213. if vim.regex([[^#!.*\\<mine\\>]]):match_str(content) ~= nil then
  2214. return 'mine'
  2215. elseif vim.regex([[\\<drawing\\>]]):match_str(content) ~= nil then
  2216. return 'drawing'
  2217. end
  2218. end,
  2219. { priority = -math.huge },
  2220. },
  2221. },
  2222. }
  2223. <
  2224. Parameters: ~
  2225. • {filetypes} (`table`) A table containing new filetype maps (see
  2226. example).
  2227. • {pattern}? (`vim.filetype.mapping`)
  2228. • {extension}? (`vim.filetype.mapping`)
  2229. • {filename}? (`vim.filetype.mapping`)
  2230. *vim.filetype.get_option()*
  2231. vim.filetype.get_option({filetype}, {option})
  2232. Get the default option value for a {filetype}.
  2233. The returned value is what would be set in a new buffer after 'filetype'
  2234. is set, meaning it should respect all FileType autocmds and ftplugin
  2235. files.
  2236. Example: >lua
  2237. vim.filetype.get_option('vim', 'commentstring')
  2238. <
  2239. Note: this uses |nvim_get_option_value()| but caches the result. This
  2240. means |ftplugin| and |FileType| autocommands are only triggered once and
  2241. may not reflect later changes.
  2242. Attributes: ~
  2243. Since: 0.9.0
  2244. Parameters: ~
  2245. • {filetype} (`string`) Filetype
  2246. • {option} (`string`) Option name
  2247. Return: ~
  2248. (`string|boolean|integer`) Option value
  2249. vim.filetype.match({args}) *vim.filetype.match()*
  2250. Perform filetype detection.
  2251. The filetype can be detected using one of three methods:
  2252. 1. Using an existing buffer
  2253. 2. Using only a file name
  2254. 3. Using only file contents
  2255. Of these, option 1 provides the most accurate result as it uses both the
  2256. buffer's filename and (optionally) the buffer contents. Options 2 and 3
  2257. can be used without an existing buffer, but may not always provide a match
  2258. in cases where the filename (or contents) cannot unambiguously determine
  2259. the filetype.
  2260. Each of the three options is specified using a key to the single argument
  2261. of this function. Example: >lua
  2262. -- Using a buffer number
  2263. vim.filetype.match({ buf = 42 })
  2264. -- Override the filename of the given buffer
  2265. vim.filetype.match({ buf = 42, filename = 'foo.c' })
  2266. -- Using a filename without a buffer
  2267. vim.filetype.match({ filename = 'main.lua' })
  2268. -- Using file contents
  2269. vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
  2270. <
  2271. Parameters: ~
  2272. • {args} (`table`) Table specifying which matching strategy to use.
  2273. Accepted keys are:
  2274. • {buf}? (`integer`) Buffer number to use for matching.
  2275. Mutually exclusive with {contents}
  2276. • {filename}? (`string`) Filename to use for matching. When
  2277. {buf} is given, defaults to the filename of the given buffer
  2278. number. The file need not actually exist in the filesystem.
  2279. When used without {buf} only the name of the file is used
  2280. for filetype matching. This may result in failure to detect
  2281. the filetype in cases where the filename alone is not enough
  2282. to disambiguate the filetype.
  2283. • {contents}? (`string[]`) An array of lines representing file
  2284. contents to use for matching. Can be used with {filename}.
  2285. Mutually exclusive with {buf}.
  2286. Return (multiple): ~
  2287. (`string?`) If a match was found, the matched filetype.
  2288. (`function?`) A function that modifies buffer state when called (for
  2289. example, to set some filetype specific buffer variables). The function
  2290. accepts a buffer number as its only argument.
  2291. ==============================================================================
  2292. Lua module: vim.keymap *vim.keymap*
  2293. vim.keymap.del({modes}, {lhs}, {opts}) *vim.keymap.del()*
  2294. Remove an existing mapping. Examples: >lua
  2295. vim.keymap.del('n', 'lhs')
  2296. vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
  2297. <
  2298. Parameters: ~
  2299. • {modes} (`string|string[]`)
  2300. • {lhs} (`string`)
  2301. • {opts} (`table?`) A table with the following fields:
  2302. • {buffer}? (`integer|boolean`) Remove a mapping from the
  2303. given buffer. When `0` or `true`, use the current buffer.
  2304. See also: ~
  2305. • |vim.keymap.set()|
  2306. vim.keymap.set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
  2307. Defines a |mapping| of |keycodes| to a function or keycodes.
  2308. Examples: >lua
  2309. -- Map "x" to a Lua function:
  2310. vim.keymap.set('n', 'x', function() print("real lua function") end)
  2311. -- Map "<leader>x" to multiple modes for the current buffer:
  2312. vim.keymap.set({'n', 'v'}, '<leader>x', vim.lsp.buf.references, { buffer = true })
  2313. -- Map <Tab> to an expression (|:map-<expr>|):
  2314. vim.keymap.set('i', '<Tab>', function()
  2315. return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
  2316. end, { expr = true })
  2317. -- Map "[%%" to a <Plug> mapping:
  2318. vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)')
  2319. <
  2320. Parameters: ~
  2321. • {mode} (`string|string[]`) Mode "short-name" (see
  2322. |nvim_set_keymap()|), or a list thereof.
  2323. • {lhs} (`string`) Left-hand side |{lhs}| of the mapping.
  2324. • {rhs} (`string|function`) Right-hand side |{rhs}| of the mapping,
  2325. can be a Lua function.
  2326. • {opts} (`table?`) Table of |:map-arguments|. Same as
  2327. |nvim_set_keymap()| {opts}, except:
  2328. • {replace_keycodes} defaults to `true` if "expr" is `true`.
  2329. Also accepts:
  2330. • {buffer}? (`integer|boolean`) Creates buffer-local mapping,
  2331. `0` or `true` for current buffer.
  2332. • {remap}? (`boolean`, default: `false`) Make the mapping
  2333. recursive. Inverse of {noremap}.
  2334. See also: ~
  2335. • |nvim_set_keymap()|
  2336. • |maparg()|
  2337. • |mapcheck()|
  2338. • |mapset()|
  2339. ==============================================================================
  2340. Lua module: vim.fs *vim.fs*
  2341. *vim.fs.exists()*
  2342. Use |uv.fs_stat()| to check a file's type, and whether it exists.
  2343. Example: >lua
  2344. if vim.uv.fs_stat(file) then
  2345. vim.print("file exists")
  2346. end
  2347. <
  2348. vim.fs.abspath({path}) *vim.fs.abspath()*
  2349. Convert path to an absolute path. A tilde (~) character at the beginning
  2350. of the path is expanded to the user's home directory. Does not check if
  2351. the path exists, normalize the path, resolve symlinks or hardlinks
  2352. (including `.` and `..`), or expand environment variables. If the path is
  2353. already absolute, it is returned unchanged. Also converts `\` path
  2354. separators to `/`.
  2355. Parameters: ~
  2356. • {path} (`string`) Path
  2357. Return: ~
  2358. (`string`) Absolute path
  2359. vim.fs.basename({file}) *vim.fs.basename()*
  2360. Return the basename of the given path
  2361. Attributes: ~
  2362. Since: 0.8.0
  2363. Parameters: ~
  2364. • {file} (`string?`) Path
  2365. Return: ~
  2366. (`string?`) Basename of {file}
  2367. vim.fs.dir({path}, {opts}) *vim.fs.dir()*
  2368. Return an iterator over the items located in {path}
  2369. Attributes: ~
  2370. Since: 0.8.0
  2371. Parameters: ~
  2372. • {path} (`string`) An absolute or relative path to the directory to
  2373. iterate over. The path is first normalized
  2374. |vim.fs.normalize()|.
  2375. • {opts} (`table?`) Optional keyword arguments:
  2376. • depth: integer|nil How deep the traverse (default 1)
  2377. • skip: (fun(dir_name: string): boolean)|nil Predicate to
  2378. control traversal. Return false to stop searching the
  2379. current directory. Only useful when depth > 1
  2380. • follow: boolean|nil Follow symbolic links. (default: true)
  2381. Return: ~
  2382. (`Iterator`) over items in {path}. Each iteration yields two values:
  2383. "name" and "type". "name" is the basename of the item relative to
  2384. {path}. "type" is one of the following: "file", "directory", "link",
  2385. "fifo", "socket", "char", "block", "unknown".
  2386. vim.fs.dirname({file}) *vim.fs.dirname()*
  2387. Return the parent directory of the given path
  2388. Attributes: ~
  2389. Since: 0.8.0
  2390. Parameters: ~
  2391. • {file} (`string?`) Path
  2392. Return: ~
  2393. (`string?`) Parent directory of {file}
  2394. vim.fs.find({names}, {opts}) *vim.fs.find()*
  2395. Find files or directories (or other items as specified by `opts.type`) in
  2396. the given path.
  2397. Finds items given in {names} starting from {path}. If {upward} is "true"
  2398. then the search traverses upward through parent directories; otherwise,
  2399. the search traverses downward. Note that downward searches are recursive
  2400. and may search through many directories! If {stop} is non-nil, then the
  2401. search stops when the directory given in {stop} is reached. The search
  2402. terminates when {limit} (default 1) matches are found. You can set {type}
  2403. to "file", "directory", "link", "socket", "char", "block", or "fifo" to
  2404. narrow the search to find only that type.
  2405. Examples: >lua
  2406. -- list all test directories under the runtime directory
  2407. local test_dirs = vim.fs.find(
  2408. {'test', 'tst', 'testdir'},
  2409. {limit = math.huge, type = 'directory', path = './runtime/'}
  2410. )
  2411. -- get all files ending with .cpp or .hpp inside lib/
  2412. local cpp_hpp = vim.fs.find(function(name, path)
  2413. return name:match('.*%.[ch]pp$') and path:match('[/\\]lib$')
  2414. end, {limit = math.huge, type = 'file'})
  2415. <
  2416. Attributes: ~
  2417. Since: 0.8.0
  2418. Parameters: ~
  2419. • {names} (`string|string[]|fun(name: string, path: string): boolean`)
  2420. Names of the items to find. Must be base names, paths and
  2421. globs are not supported when {names} is a string or a table.
  2422. If {names} is a function, it is called for each traversed
  2423. item with args:
  2424. • name: base name of the current item
  2425. • path: full path of the current item
  2426. The function should return `true` if the given item is
  2427. considered a match.
  2428. • {opts} (`table`) Optional keyword arguments:
  2429. • {path}? (`string`) Path to begin searching from. If
  2430. omitted, the |current-directory| is used.
  2431. • {upward}? (`boolean`, default: `false`) Search upward
  2432. through parent directories. Otherwise, search through child
  2433. directories (recursively).
  2434. • {stop}? (`string`) Stop searching when this directory is
  2435. reached. The directory itself is not searched.
  2436. • {type}? (`string`) Find only items of the given type. If
  2437. omitted, all items that match {names} are included.
  2438. • {limit}? (`number`, default: `1`) Stop the search after
  2439. finding this many matches. Use `math.huge` to place no
  2440. limit on the number of matches.
  2441. • {follow}? (`boolean`, default: `true`) Follow symbolic
  2442. links.
  2443. Return: ~
  2444. (`string[]`) Normalized paths |vim.fs.normalize()| of all matching
  2445. items
  2446. vim.fs.joinpath({...}) *vim.fs.joinpath()*
  2447. Concatenates partial paths (one absolute or relative path followed by zero
  2448. or more relative paths). Slashes are normalized: redundant slashes are
  2449. removed, and (on Windows) backslashes are replaced with forward-slashes.
  2450. Examples:
  2451. • "foo/", "/bar" => "foo/bar"
  2452. • Windows: "a\foo\", "\bar" => "a/foo/bar"
  2453. Attributes: ~
  2454. Since: 0.10.0
  2455. Parameters: ~
  2456. • {...} (`string`)
  2457. Return: ~
  2458. (`string`)
  2459. vim.fs.normalize({path}, {opts}) *vim.fs.normalize()*
  2460. Normalize a path to a standard format. A tilde (~) character at the
  2461. beginning of the path is expanded to the user's home directory and
  2462. environment variables are also expanded. "." and ".." components are also
  2463. resolved, except when the path is relative and trying to resolve it would
  2464. result in an absolute path.
  2465. • "." as the only part in a relative path:
  2466. • "." => "."
  2467. • "././" => "."
  2468. • ".." when it leads outside the current directory
  2469. • "foo/../../bar" => "../bar"
  2470. • "../../foo" => "../../foo"
  2471. • ".." in the root directory returns the root directory.
  2472. • "/../../" => "/"
  2473. On Windows, backslash (\) characters are converted to forward slashes (/).
  2474. Examples: >lua
  2475. [[C:\Users\jdoe]] => "C:/Users/jdoe"
  2476. "~/src/neovim" => "/home/jdoe/src/neovim"
  2477. "$XDG_CONFIG_HOME/nvim/init.vim" => "/Users/jdoe/.config/nvim/init.vim"
  2478. "~/src/nvim/api/../tui/./tui.c" => "/home/jdoe/src/nvim/tui/tui.c"
  2479. "./foo/bar" => "foo/bar"
  2480. "foo/../../../bar" => "../../bar"
  2481. "/home/jdoe/../../../bar" => "/bar"
  2482. "C:foo/../../baz" => "C:../baz"
  2483. "C:/foo/../../baz" => "C:/baz"
  2484. [[\\?\UNC\server\share\foo\..\..\..\bar]] => "//?/UNC/server/share/bar"
  2485. <
  2486. Attributes: ~
  2487. Since: 0.8.0
  2488. Parameters: ~
  2489. • {path} (`string`) Path to normalize
  2490. • {opts} (`table?`) A table with the following fields:
  2491. • {expand_env}? (`boolean`, default: `true`) Expand
  2492. environment variables.
  2493. • {win}? (`boolean`, default: `true` in Windows, `false`
  2494. otherwise) Path is a Windows path.
  2495. Return: ~
  2496. (`string`) Normalized path
  2497. vim.fs.parents({start}) *vim.fs.parents()*
  2498. Iterate over all the parents of the given path.
  2499. Example: >lua
  2500. local root_dir
  2501. for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
  2502. if vim.fn.isdirectory(dir .. "/.git") == 1 then
  2503. root_dir = dir
  2504. break
  2505. end
  2506. end
  2507. if root_dir then
  2508. print("Found git repository at", root_dir)
  2509. end
  2510. <
  2511. Attributes: ~
  2512. Since: 0.8.0
  2513. Parameters: ~
  2514. • {start} (`string`) Initial path.
  2515. Return (multiple): ~
  2516. (`fun(_, dir: string): string?`) Iterator
  2517. (`nil`)
  2518. (`string?`)
  2519. vim.fs.relpath({base}, {target}, {opts}) *vim.fs.relpath()*
  2520. Gets `target` path relative to `base`, or `nil` if `base` is not an
  2521. ancestor.
  2522. Example: >lua
  2523. vim.fs.relpath('/var', '/var/lib') -- 'lib'
  2524. vim.fs.relpath('/var', '/usr/bin') -- nil
  2525. <
  2526. Parameters: ~
  2527. • {base} (`string`)
  2528. • {target} (`string`)
  2529. • {opts} (`table?`) Reserved for future use
  2530. Return: ~
  2531. (`string?`)
  2532. vim.fs.rm({path}, {opts}) *vim.fs.rm()*
  2533. WARNING: This feature is experimental/unstable.
  2534. Remove files or directories
  2535. Parameters: ~
  2536. • {path} (`string`) Path to remove
  2537. • {opts} (`table?`) A table with the following fields:
  2538. • {recursive}? (`boolean`) Remove directories and their
  2539. contents recursively
  2540. • {force}? (`boolean`) Ignore nonexistent files and arguments
  2541. vim.fs.root({source}, {marker}) *vim.fs.root()*
  2542. Find the first parent directory containing a specific "marker", relative
  2543. to a file path or buffer.
  2544. If the buffer is unnamed (has no backing file) or has a non-empty
  2545. 'buftype' then the search begins from Nvim's |current-directory|.
  2546. Example: >lua
  2547. -- Find the root of a Python project, starting from file 'main.py'
  2548. vim.fs.root(vim.fs.joinpath(vim.env.PWD, 'main.py'), {'pyproject.toml', 'setup.py' })
  2549. -- Find the root of a git repository
  2550. vim.fs.root(0, '.git')
  2551. -- Find the parent directory containing any file with a .csproj extension
  2552. vim.fs.root(0, function(name, path)
  2553. return name:match('%.csproj$') ~= nil
  2554. end)
  2555. <
  2556. Attributes: ~
  2557. Since: 0.10.0
  2558. Parameters: ~
  2559. • {source} (`integer|string`) Buffer number (0 for current buffer) or
  2560. file path (absolute or relative to the |current-directory|)
  2561. to begin the search from.
  2562. • {marker} (`string|string[]|fun(name: string, path: string): boolean`)
  2563. A marker, or list of markers, to search for. If a function,
  2564. the function is called for each evaluated item and should
  2565. return true if {name} and {path} are a match.
  2566. Return: ~
  2567. (`string?`) Directory path containing one of the given markers, or nil
  2568. if no directory was found.
  2569. ==============================================================================
  2570. Lua module: vim.glob *vim.glob*
  2571. vim.glob.to_lpeg({pattern}) *vim.glob.to_lpeg()*
  2572. Parses a raw glob into an |lua-lpeg| pattern.
  2573. This uses glob semantics from LSP 3.17.0:
  2574. https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern
  2575. Glob patterns can have the following syntax:
  2576. • `*` to match one or more characters in a path segment
  2577. • `?` to match on one character in a path segment
  2578. • `**` to match any number of path segments, including none
  2579. • `{}` to group conditions (e.g. `*.{ts,js}` matches TypeScript and
  2580. JavaScript files)
  2581. • `[]` to declare a range of characters to match in a path segment (e.g.,
  2582. `example.[0-9]` to match on `example.0`, `example.1`, …)
  2583. • `[!...]` to negate a range of characters to match in a path segment
  2584. (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not
  2585. `example.0`)
  2586. Parameters: ~
  2587. • {pattern} (`string`) The raw glob pattern
  2588. Return: ~
  2589. (`vim.lpeg.Pattern`) pattern An |lua-lpeg| representation of the
  2590. pattern
  2591. ==============================================================================
  2592. VIM.LPEG *vim.lpeg*
  2593. LPeg is a pattern-matching library for Lua, based on Parsing Expression
  2594. Grammars (PEGs). https://bford.info/packrat/
  2595. *lua-lpeg* *vim.lpeg.Pattern*
  2596. The LPeg library for parsing expression grammars is included as `vim.lpeg`
  2597. (https://www.inf.puc-rio.br/~roberto/lpeg/).
  2598. In addition, its regex-like interface is available as |vim.re|
  2599. (https://www.inf.puc-rio.br/~roberto/lpeg/re.html).
  2600. Pattern:match({subject}, {init}, {...}) *Pattern:match()*
  2601. Matches the given `pattern` against the `subject` string. If the match
  2602. succeeds, returns the index in the subject of the first character after
  2603. the match, or the captured values (if the pattern captured any value). An
  2604. optional numeric argument `init` makes the match start at that position in
  2605. the subject string. As usual in Lua libraries, a negative value counts
  2606. from the end. Unlike typical pattern-matching functions, `match` works
  2607. only in anchored mode; that is, it tries to match the pattern with a
  2608. prefix of the given subject string (at position `init`), not with an
  2609. arbitrary substring of the subject. So, if we want to find a pattern
  2610. anywhere in a string, we must either write a loop in Lua or write a
  2611. pattern that matches anywhere.
  2612. Example: >lua
  2613. local pattern = lpeg.R('az') ^ 1 * -1
  2614. assert(pattern:match('hello') == 6)
  2615. assert(lpeg.match(pattern, 'hello') == 6)
  2616. assert(pattern:match('1 hello') == nil)
  2617. <
  2618. Parameters: ~
  2619. • {subject} (`string`)
  2620. • {init} (`integer?`)
  2621. • {...} (`any`)
  2622. Return: ~
  2623. (`any`) ...
  2624. vim.lpeg.B({pattern}) *vim.lpeg.B()*
  2625. Returns a pattern that matches only if the input string at the current
  2626. position is preceded by `patt`. Pattern `patt` must match only strings
  2627. with some fixed length, and it cannot contain captures. Like the `and`
  2628. predicate, this pattern never consumes any input, independently of success
  2629. or failure.
  2630. Parameters: ~
  2631. • {pattern} (`vim.lpeg.Pattern|string|integer|boolean|table`)
  2632. Return: ~
  2633. (`vim.lpeg.Pattern`)
  2634. vim.lpeg.C({patt}) *vim.lpeg.C()*
  2635. Creates a simple capture, which captures the substring of the subject that
  2636. matches `patt`. The captured value is a string. If `patt` has other
  2637. captures, their values are returned after this one.
  2638. Example: >lua
  2639. local function split (s, sep)
  2640. sep = lpeg.P(sep)
  2641. local elem = lpeg.C((1 - sep) ^ 0)
  2642. local p = elem * (sep * elem) ^ 0
  2643. return lpeg.match(p, s)
  2644. end
  2645. local a, b, c = split('a,b,c', ',')
  2646. assert(a == 'a')
  2647. assert(b == 'b')
  2648. assert(c == 'c')
  2649. <
  2650. Parameters: ~
  2651. • {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
  2652. Return: ~
  2653. (`vim.lpeg.Capture`)
  2654. vim.lpeg.Carg({n}) *vim.lpeg.Carg()*
  2655. Creates an argument capture. This pattern matches the empty string and
  2656. produces the value given as the nth extra argument given in the call to
  2657. `lpeg.match`.
  2658. Parameters: ~
  2659. • {n} (`integer`)
  2660. Return: ~
  2661. (`vim.lpeg.Capture`)
  2662. vim.lpeg.Cb({name}) *vim.lpeg.Cb()*
  2663. Creates a back capture. This pattern matches the empty string and produces
  2664. the values produced by the most recent group capture named `name` (where
  2665. `name` can be any Lua value). Most recent means the last complete
  2666. outermost group capture with the given name. A Complete capture means that
  2667. the entire pattern corresponding to the capture has matched. An Outermost
  2668. capture means that the capture is not inside another complete capture. In
  2669. the same way that LPeg does not specify when it evaluates captures, it
  2670. does not specify whether it reuses values previously produced by the group
  2671. or re-evaluates them.
  2672. Parameters: ~
  2673. • {name} (`any`)
  2674. Return: ~
  2675. (`vim.lpeg.Capture`)
  2676. vim.lpeg.Cc({...}) *vim.lpeg.Cc()*
  2677. Creates a constant capture. This pattern matches the empty string and
  2678. produces all given values as its captured values.
  2679. Parameters: ~
  2680. • {...} (`any`)
  2681. Return: ~
  2682. (`vim.lpeg.Capture`)
  2683. vim.lpeg.Cf({patt}, {func}) *vim.lpeg.Cf()*
  2684. Creates a fold capture. If `patt` produces a list of captures C1 C2 ...
  2685. Cn, this capture will produce the value
  2686. `func(...func(func(C1, C2), C3)...,Cn)`, that is, it will fold (or
  2687. accumulate, or reduce) the captures from `patt` using function `func`.
  2688. This capture assumes that `patt` should produce at least one capture with
  2689. at least one value (of any type), which becomes the initial value of an
  2690. accumulator. (If you need a specific initial value, you may prefix a
  2691. constant capture to `patt`.) For each subsequent capture, LPeg calls
  2692. `func` with this accumulator as the first argument and all values produced
  2693. by the capture as extra arguments; the first result from this call becomes
  2694. the new value for the accumulator. The final value of the accumulator
  2695. becomes the captured value.
  2696. Example: >lua
  2697. local number = lpeg.R('09') ^ 1 / tonumber
  2698. local list = number * (',' * number) ^ 0
  2699. local function add(acc, newvalue) return acc + newvalue end
  2700. local sum = lpeg.Cf(list, add)
  2701. assert(sum:match('10,30,43') == 83)
  2702. <
  2703. Parameters: ~
  2704. • {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
  2705. • {func} (`fun(acc, newvalue)`)
  2706. Return: ~
  2707. (`vim.lpeg.Capture`)
  2708. vim.lpeg.Cg({patt}, {name}) *vim.lpeg.Cg()*
  2709. Creates a group capture. It groups all values returned by `patt` into a
  2710. single capture. The group may be anonymous (if no name is given) or named
  2711. with the given name (which can be any non-nil Lua value).
  2712. Parameters: ~
  2713. • {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
  2714. • {name} (`string?`)
  2715. Return: ~
  2716. (`vim.lpeg.Capture`)
  2717. vim.lpeg.Cmt({patt}, {fn}) *vim.lpeg.Cmt()*
  2718. Creates a match-time capture. Unlike all other captures, this one is
  2719. evaluated immediately when a match occurs (even if it is part of a larger
  2720. pattern that fails later). It forces the immediate evaluation of all its
  2721. nested captures and then calls `function`. The given function gets as
  2722. arguments the entire subject, the current position (after the match of
  2723. `patt`), plus any capture values produced by `patt`. The first value
  2724. returned by `function` defines how the match happens. If the call returns
  2725. a number, the match succeeds and the returned number becomes the new
  2726. current position. (Assuming a subject sand current position `i`, the
  2727. returned number must be in the range `[i, len(s) + 1]`.) If the call
  2728. returns `true`, the match succeeds without consuming any input (so, to
  2729. return true is equivalent to return `i`). If the call returns `false`,
  2730. `nil`, or no value, the match fails. Any extra values returned by the
  2731. function become the values produced by the capture.
  2732. Parameters: ~
  2733. • {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
  2734. • {fn} (`fun(s: string, i: integer, ...: any)`) (position:
  2735. boolean|integer, ...: any)
  2736. Return: ~
  2737. (`vim.lpeg.Capture`)
  2738. vim.lpeg.Cp() *vim.lpeg.Cp()*
  2739. Creates a position capture. It matches the empty string and captures the
  2740. position in the subject where the match occurs. The captured value is a
  2741. number.
  2742. Example: >lua
  2743. local I = lpeg.Cp()
  2744. local function anywhere(p) return lpeg.P({I * p * I + 1 * lpeg.V(1)}) end
  2745. local match_start, match_end = anywhere('world'):match('hello world!')
  2746. assert(match_start == 7)
  2747. assert(match_end == 12)
  2748. <
  2749. Return: ~
  2750. (`vim.lpeg.Capture`)
  2751. vim.lpeg.Cs({patt}) *vim.lpeg.Cs()*
  2752. Creates a substitution capture. This function creates a substitution
  2753. capture, which captures the substring of the subject that matches `patt`,
  2754. with substitutions. For any capture inside `patt` with a value, the
  2755. substring that matched the capture is replaced by the capture value (which
  2756. should be a string). The final captured value is the string resulting from
  2757. all replacements.
  2758. Example: >lua
  2759. local function gsub (s, patt, repl)
  2760. patt = lpeg.P(patt)
  2761. patt = lpeg.Cs((patt / repl + 1) ^ 0)
  2762. return lpeg.match(patt, s)
  2763. end
  2764. assert(gsub('Hello, xxx!', 'xxx', 'World') == 'Hello, World!')
  2765. <
  2766. Parameters: ~
  2767. • {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
  2768. Return: ~
  2769. (`vim.lpeg.Capture`)
  2770. vim.lpeg.Ct({patt}) *vim.lpeg.Ct()*
  2771. Creates a table capture. This capture returns a table with all values from
  2772. all anonymous captures made by `patt` inside this table in successive
  2773. integer keys, starting at 1. Moreover, for each named capture group
  2774. created by `patt`, the first value of the group is put into the table with
  2775. the group name as its key. The captured value is only the table.
  2776. Parameters: ~
  2777. • {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
  2778. Return: ~
  2779. (`vim.lpeg.Capture`)
  2780. vim.lpeg.locale({tab}) *vim.lpeg.locale()*
  2781. Returns a table with patterns for matching some character classes
  2782. according to the current locale. The table has fields named `alnum`,
  2783. `alpha`, `cntrl`, `digit`, `graph`, `lower`, `print`, `punct`, `space`,
  2784. `upper`, and `xdigit`, each one containing a correspondent pattern. Each
  2785. pattern matches any single character that belongs to its class. If called
  2786. with an argument `table`, then it creates those fields inside the given
  2787. table and returns that table.
  2788. Example: >lua
  2789. lpeg.locale(lpeg)
  2790. local space = lpeg.space ^ 0
  2791. local name = lpeg.C(lpeg.alpha ^ 1) * space
  2792. local sep = lpeg.S(',;') * space
  2793. local pair = lpeg.Cg(name * '=' * space * name) * sep ^ -1
  2794. local list = lpeg.Cf(lpeg.Ct('') * pair ^ 0, rawset)
  2795. local t = list:match('a=b, c = hi; next = pi')
  2796. assert(t.a == 'b')
  2797. assert(t.c == 'hi')
  2798. assert(t.next == 'pi')
  2799. local locale = lpeg.locale()
  2800. assert(type(locale.digit) == 'userdata')
  2801. <
  2802. Parameters: ~
  2803. • {tab} (`table?`)
  2804. Return: ~
  2805. (`vim.lpeg.Locale`)
  2806. vim.lpeg.match({pattern}, {subject}, {init}, {...}) *vim.lpeg.match()*
  2807. Matches the given `pattern` against the `subject` string. If the match
  2808. succeeds, returns the index in the subject of the first character after
  2809. the match, or the captured values (if the pattern captured any value). An
  2810. optional numeric argument `init` makes the match start at that position in
  2811. the subject string. As usual in Lua libraries, a negative value counts
  2812. from the end. Unlike typical pattern-matching functions, `match` works
  2813. only in anchored mode; that is, it tries to match the pattern with a
  2814. prefix of the given subject string (at position `init`), not with an
  2815. arbitrary substring of the subject. So, if we want to find a pattern
  2816. anywhere in a string, we must either write a loop in Lua or write a
  2817. pattern that matches anywhere.
  2818. Example: >lua
  2819. local pattern = lpeg.R('az') ^ 1 * -1
  2820. assert(pattern:match('hello') == 6)
  2821. assert(lpeg.match(pattern, 'hello') == 6)
  2822. assert(pattern:match('1 hello') == nil)
  2823. <
  2824. Parameters: ~
  2825. • {pattern} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
  2826. • {subject} (`string`)
  2827. • {init} (`integer?`)
  2828. • {...} (`any`)
  2829. Return: ~
  2830. (`any`) ...
  2831. vim.lpeg.P({value}) *vim.lpeg.P()*
  2832. Converts the given value into a proper pattern. The following rules are
  2833. applied:
  2834. • If the argument is a pattern, it is returned unmodified.
  2835. • If the argument is a string, it is translated to a pattern that matches
  2836. the string literally.
  2837. • If the argument is a non-negative number `n`, the result is a pattern
  2838. that matches exactly `n` characters.
  2839. • If the argument is a negative number `-n`, the result is a pattern that
  2840. succeeds only if the input string has less than `n` characters left:
  2841. `lpeg.P(-n)` is equivalent to `-lpeg.P(n)` (see the unary minus
  2842. operation).
  2843. • If the argument is a boolean, the result is a pattern that always
  2844. succeeds or always fails (according to the boolean value), without
  2845. consuming any input.
  2846. • If the argument is a table, it is interpreted as a grammar (see
  2847. Grammars).
  2848. • If the argument is a function, returns a pattern equivalent to a
  2849. match-time capture over the empty string.
  2850. Parameters: ~
  2851. • {value} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
  2852. Return: ~
  2853. (`vim.lpeg.Pattern`)
  2854. vim.lpeg.R({...}) *vim.lpeg.R()*
  2855. Returns a pattern that matches any single character belonging to one of
  2856. the given ranges. Each `range` is a string `xy` of length 2, representing
  2857. all characters with code between the codes of `x` and `y` (both
  2858. inclusive). As an example, the pattern `lpeg.R('09')` matches any digit,
  2859. and `lpeg.R('az', 'AZ')` matches any ASCII letter.
  2860. Example: >lua
  2861. local pattern = lpeg.R('az') ^ 1 * -1
  2862. assert(pattern:match('hello') == 6)
  2863. <
  2864. Parameters: ~
  2865. • {...} (`string`)
  2866. Return: ~
  2867. (`vim.lpeg.Pattern`)
  2868. vim.lpeg.S({string}) *vim.lpeg.S()*
  2869. Returns a pattern that matches any single character that appears in the
  2870. given string (the `S` stands for Set). As an example, the pattern
  2871. `lpeg.S('+-*/')` matches any arithmetic operator. Note that, if `s` is a
  2872. character (that is, a string of length 1), then `lpeg.P(s)` is equivalent
  2873. to `lpeg.S(s)` which is equivalent to `lpeg.R(s..s)`. Note also that both
  2874. `lpeg.S('')` and `lpeg.R()` are patterns that always fail.
  2875. Parameters: ~
  2876. • {string} (`string`)
  2877. Return: ~
  2878. (`vim.lpeg.Pattern`)
  2879. vim.lpeg.setmaxstack({max}) *vim.lpeg.setmaxstack()*
  2880. Sets a limit for the size of the backtrack stack used by LPeg to track
  2881. calls and choices. The default limit is `400`. Most well-written patterns
  2882. need little backtrack levels and therefore you seldom need to change this
  2883. limit; before changing it you should try to rewrite your pattern to avoid
  2884. the need for extra space. Nevertheless, a few useful patterns may
  2885. overflow. Also, with recursive grammars, subjects with deep recursion may
  2886. also need larger limits.
  2887. Parameters: ~
  2888. • {max} (`integer`)
  2889. vim.lpeg.type({value}) *vim.lpeg.type()*
  2890. Returns the string `"pattern"` if the given value is a pattern, otherwise
  2891. `nil`.
  2892. Parameters: ~
  2893. • {value} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
  2894. Return: ~
  2895. (`"pattern"?`)
  2896. vim.lpeg.V({v}) *vim.lpeg.V()*
  2897. Creates a non-terminal (a variable) for a grammar. This operation creates
  2898. a non-terminal (a variable) for a grammar. The created non-terminal refers
  2899. to the rule indexed by `v` in the enclosing grammar.
  2900. Example: >lua
  2901. local b = lpeg.P({'(' * ((1 - lpeg.S '()') + lpeg.V(1)) ^ 0 * ')'})
  2902. assert(b:match('((string))') == 11)
  2903. assert(b:match('(') == nil)
  2904. <
  2905. Parameters: ~
  2906. • {v} (`boolean|string|number|function|table|thread|userdata|lightuserdata`)
  2907. Return: ~
  2908. (`vim.lpeg.Pattern`)
  2909. vim.lpeg.version() *vim.lpeg.version()*
  2910. Returns a string with the running version of LPeg.
  2911. Return: ~
  2912. (`string`)
  2913. ==============================================================================
  2914. VIM.RE *vim.re*
  2915. The `vim.re` module provides a conventional regex-like syntax for pattern
  2916. usage within LPeg |vim.lpeg|. (Unrelated to |vim.regex| which provides Vim
  2917. |regexp| from Lua.)
  2918. See https://www.inf.puc-rio.br/~roberto/lpeg/re.html for the original
  2919. documentation including regex syntax and examples.
  2920. vim.re.compile({string}, {defs}) *vim.re.compile()*
  2921. Compiles the given {string} and returns an equivalent LPeg pattern. The
  2922. given string may define either an expression or a grammar. The optional
  2923. {defs} table provides extra Lua values to be used by the pattern.
  2924. Parameters: ~
  2925. • {string} (`string`)
  2926. • {defs} (`table?`)
  2927. Return: ~
  2928. (`vim.lpeg.Pattern`)
  2929. vim.re.find({subject}, {pattern}, {init}) *vim.re.find()*
  2930. Searches the given {pattern} in the given {subject}. If it finds a match,
  2931. returns the index where this occurrence starts and the index where it
  2932. ends. Otherwise, returns nil.
  2933. An optional numeric argument {init} makes the search starts at that
  2934. position in the subject string. As usual in Lua libraries, a negative
  2935. value counts from the end.
  2936. Parameters: ~
  2937. • {subject} (`string`)
  2938. • {pattern} (`vim.lpeg.Pattern|string`)
  2939. • {init} (`integer?`)
  2940. Return (multiple): ~
  2941. (`integer?`) the index where the occurrence starts, nil if no match
  2942. (`integer?`) the index where the occurrence ends, nil if no match
  2943. vim.re.gsub({subject}, {pattern}, {replacement}) *vim.re.gsub()*
  2944. Does a global substitution, replacing all occurrences of {pattern} in the
  2945. given {subject} by {replacement}.
  2946. Parameters: ~
  2947. • {subject} (`string`)
  2948. • {pattern} (`vim.lpeg.Pattern|string`)
  2949. • {replacement} (`string`)
  2950. Return: ~
  2951. (`string`)
  2952. vim.re.match({subject}, {pattern}, {init}) *vim.re.match()*
  2953. Matches the given {pattern} against the given {subject}, returning all
  2954. captures.
  2955. Parameters: ~
  2956. • {subject} (`string`)
  2957. • {pattern} (`vim.lpeg.Pattern|string`)
  2958. • {init} (`integer?`)
  2959. Return: ~
  2960. (`integer|vim.lpeg.Capture?`)
  2961. See also: ~
  2962. • vim.lpeg.match()
  2963. vim.re.updatelocale() *vim.re.updatelocale()*
  2964. Updates the pre-defined character classes to the current locale.
  2965. ==============================================================================
  2966. VIM.REGEX *vim.regex*
  2967. Vim regexes can be used directly from Lua. Currently they only allow matching
  2968. within a single line.
  2969. *regex:match_line()*
  2970. regex:match_line({bufnr}, {line_idx}, {start}, {end_})
  2971. Matches line at `line_idx` (zero-based) in buffer `bufnr`. Match is
  2972. restricted to byte index range `start` and `end_` if given, otherwise see
  2973. |regex:match_str()|. Returned byte indices are relative to `start` if
  2974. given.
  2975. Parameters: ~
  2976. • {bufnr} (`integer`)
  2977. • {line_idx} (`integer`)
  2978. • {start} (`integer?`)
  2979. • {end_} (`integer?`)
  2980. Return (multiple): ~
  2981. (`integer?`) match start (byte index) relative to `start`, or `nil` if
  2982. no match
  2983. (`integer?`) match end (byte index) relative to `start`, or `nil` if
  2984. no match
  2985. regex:match_str({str}) *regex:match_str()*
  2986. Matches string `str` against this regex. To match the string precisely,
  2987. surround the regex with "^" and "$". Returns the byte indices for the
  2988. start and end of the match, or `nil` if there is no match. Because any
  2989. integer is "truthy", `regex:match_str()` can be directly used as a
  2990. condition in an if-statement.
  2991. Parameters: ~
  2992. • {str} (`string`)
  2993. Return (multiple): ~
  2994. (`integer?`) match start (byte index), or `nil` if no match
  2995. (`integer?`) match end (byte index), or `nil` if no match
  2996. vim.regex({re}) *vim.regex()*
  2997. Parses the Vim regex `re` and returns a regex object. Regexes are "magic"
  2998. and case-sensitive by default, regardless of 'magic' and 'ignorecase'.
  2999. They can be controlled with flags, see |/magic| and |/ignorecase|.
  3000. Parameters: ~
  3001. • {re} (`string`)
  3002. Return: ~
  3003. (`vim.regex`)
  3004. ==============================================================================
  3005. Lua module: vim.secure *vim.secure*
  3006. vim.secure.read({path}) *vim.secure.read()*
  3007. Attempt to read the file at {path} prompting the user if the file should
  3008. be trusted. The user's choice is persisted in a trust database at
  3009. $XDG_STATE_HOME/nvim/trust.
  3010. Attributes: ~
  3011. Since: 0.9.0
  3012. Parameters: ~
  3013. • {path} (`string`) Path to a file to read.
  3014. Return: ~
  3015. (`string?`) The contents of the given file if it exists and is
  3016. trusted, or nil otherwise.
  3017. See also: ~
  3018. • |:trust|
  3019. vim.secure.trust({opts}) *vim.secure.trust()*
  3020. Manage the trust database.
  3021. The trust database is located at |$XDG_STATE_HOME|/nvim/trust.
  3022. Attributes: ~
  3023. Since: 0.9.0
  3024. Parameters: ~
  3025. • {opts} (`table`) A table with the following fields:
  3026. • {action} (`'allow'|'deny'|'remove'`) - `'allow'` to add a
  3027. file to the trust database and trust it,
  3028. • `'deny'` to add a file to the trust database and deny it,
  3029. • `'remove'` to remove file from the trust database
  3030. • {path}? (`string`) Path to a file to update. Mutually
  3031. exclusive with {bufnr}. Cannot be used when {action} is
  3032. "allow".
  3033. • {bufnr}? (`integer`) Buffer number to update. Mutually
  3034. exclusive with {path}.
  3035. Return (multiple): ~
  3036. (`boolean`) success true if operation was successful
  3037. (`string`) msg full path if operation was successful, else error
  3038. message
  3039. ==============================================================================
  3040. Lua module: vim.version *vim.version*
  3041. The `vim.version` module provides functions for comparing versions and ranges
  3042. conforming to the https://semver.org spec. Plugins, and plugin managers, can
  3043. use this to check available tools and dependencies on the current system.
  3044. Example: >lua
  3045. local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false})
  3046. if vim.version.gt(v, {3, 2, 0}) then
  3047. -- ...
  3048. end
  3049. <
  3050. *vim.version()* returns the version of the current Nvim process.
  3051. VERSION RANGE SPEC *version-range*
  3052. A version "range spec" defines a semantic version range which can be tested
  3053. against a version, using |vim.version.range()|.
  3054. Supported range specs are shown in the following table. Note: suffixed
  3055. versions (1.2.3-rc1) are not matched. >
  3056. 1.2.3 is 1.2.3
  3057. =1.2.3 is 1.2.3
  3058. >1.2.3 greater than 1.2.3
  3059. <1.2.3 before 1.2.3
  3060. >=1.2.3 at least 1.2.3
  3061. ~1.2.3 is >=1.2.3 <1.3.0 "reasonably close to 1.2.3"
  3062. ^1.2.3 is >=1.2.3 <2.0.0 "compatible with 1.2.3"
  3063. ^0.2.3 is >=0.2.3 <0.3.0 (0.x.x is special)
  3064. ^0.0.1 is =0.0.1 (0.0.x is special)
  3065. ^1.2 is >=1.2.0 <2.0.0 (like ^1.2.0)
  3066. ~1.2 is >=1.2.0 <1.3.0 (like ~1.2.0)
  3067. ^1 is >=1.0.0 <2.0.0 "compatible with 1"
  3068. ~1 same "reasonably close to 1"
  3069. 1.x same
  3070. 1.* same
  3071. 1 same
  3072. * any version
  3073. x same
  3074. 1.2.3 - 2.3.4 is >=1.2.3 <=2.3.4
  3075. Partial right: missing pieces treated as x (2.3 => 2.3.x).
  3076. 1.2.3 - 2.3 is >=1.2.3 <2.4.0
  3077. 1.2.3 - 2 is >=1.2.3 <3.0.0
  3078. Partial left: missing pieces treated as 0 (1.2 => 1.2.0).
  3079. 1.2 - 2.3.0 is 1.2.0 - 2.3.0
  3080. <
  3081. vim.version.cmp({v1}, {v2}) *vim.version.cmp()*
  3082. Parses and compares two version objects (the result of
  3083. |vim.version.parse()|, or specified literally as a `{major, minor, patch}`
  3084. tuple, e.g. `{1, 0, 3}`).
  3085. Example: >lua
  3086. if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then
  3087. -- ...
  3088. end
  3089. local v1 = vim.version.parse('1.0.3-pre')
  3090. local v2 = vim.version.parse('0.2.1')
  3091. if vim.version.cmp(v1, v2) == 0 then
  3092. -- ...
  3093. end
  3094. <
  3095. Note: ~
  3096. • Per semver, build metadata is ignored when comparing two
  3097. otherwise-equivalent versions.
  3098. Attributes: ~
  3099. Since: 0.9.0
  3100. Parameters: ~
  3101. • {v1} (`vim.Version|number[]|string`) Version object.
  3102. • {v2} (`vim.Version|number[]|string`) Version to compare with `v1`.
  3103. Return: ~
  3104. (`integer`) -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`.
  3105. vim.version.eq({v1}, {v2}) *vim.version.eq()*
  3106. Returns `true` if the given versions are equal. See |vim.version.cmp()|
  3107. for usage.
  3108. Attributes: ~
  3109. Since: 0.9.0
  3110. Parameters: ~
  3111. • {v1} (`vim.Version|number[]|string`)
  3112. • {v2} (`vim.Version|number[]|string`)
  3113. Return: ~
  3114. (`boolean`)
  3115. vim.version.ge({v1}, {v2}) *vim.version.ge()*
  3116. Returns `true` if `v1 >= v2`. See |vim.version.cmp()| for usage.
  3117. Attributes: ~
  3118. Since: 0.10.0
  3119. Parameters: ~
  3120. • {v1} (`vim.Version|number[]|string`)
  3121. • {v2} (`vim.Version|number[]|string`)
  3122. Return: ~
  3123. (`boolean`)
  3124. vim.version.gt({v1}, {v2}) *vim.version.gt()*
  3125. Returns `true` if `v1 > v2`. See |vim.version.cmp()| for usage.
  3126. Attributes: ~
  3127. Since: 0.9.0
  3128. Parameters: ~
  3129. • {v1} (`vim.Version|number[]|string`)
  3130. • {v2} (`vim.Version|number[]|string`)
  3131. Return: ~
  3132. (`boolean`)
  3133. vim.version.last({versions}) *vim.version.last()*
  3134. TODO: generalize this, move to func.lua
  3135. Parameters: ~
  3136. • {versions} (`vim.Version[]`)
  3137. Return: ~
  3138. (`vim.Version?`)
  3139. vim.version.le({v1}, {v2}) *vim.version.le()*
  3140. Returns `true` if `v1 <= v2`. See |vim.version.cmp()| for usage.
  3141. Attributes: ~
  3142. Since: 0.10.0
  3143. Parameters: ~
  3144. • {v1} (`vim.Version|number[]|string`)
  3145. • {v2} (`vim.Version|number[]|string`)
  3146. Return: ~
  3147. (`boolean`)
  3148. vim.version.lt({v1}, {v2}) *vim.version.lt()*
  3149. Returns `true` if `v1 < v2`. See |vim.version.cmp()| for usage.
  3150. Attributes: ~
  3151. Since: 0.9.0
  3152. Parameters: ~
  3153. • {v1} (`vim.Version|number[]|string`)
  3154. • {v2} (`vim.Version|number[]|string`)
  3155. Return: ~
  3156. (`boolean`)
  3157. vim.version.parse({version}, {opts}) *vim.version.parse()*
  3158. Parses a semantic version string and returns a version object which can be
  3159. used with other `vim.version` functions. For example "1.0.1-rc1+build.2"
  3160. returns: >
  3161. { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
  3162. <
  3163. Attributes: ~
  3164. Since: 0.9.0
  3165. Parameters: ~
  3166. • {version} (`string`) Version string to parse.
  3167. • {opts} (`table?`) Optional keyword arguments:
  3168. • strict (boolean): Default false. If `true`, no coercion
  3169. is attempted on input not conforming to semver v2.0.0. If
  3170. `false`, `parse()` attempts to coerce input such as
  3171. "1.0", "0-x", "tmux 3.2a" into valid versions.
  3172. Return: ~
  3173. (`vim.Version?`) parsed_version Version object or `nil` if input is
  3174. invalid.
  3175. See also: ~
  3176. • https://semver.org/spec/v2.0.0.html
  3177. vim.version.range({spec}) *vim.version.range()*
  3178. Parses a semver |version-range| "spec" and returns a range object: >
  3179. {
  3180. from: Version
  3181. to: Version
  3182. has(v: string|Version)
  3183. }
  3184. <
  3185. `:has()` checks if a version is in the range (inclusive `from`, exclusive
  3186. `to`).
  3187. Example: >lua
  3188. local r = vim.version.range('1.0.0 - 2.0.0')
  3189. print(r:has('1.9.9')) -- true
  3190. print(r:has('2.0.0')) -- false
  3191. print(r:has(vim.version())) -- check against current Nvim version
  3192. <
  3193. Or use cmp(), le(), lt(), ge(), gt(), and/or eq() to compare a version
  3194. against `.to` and `.from` directly: >lua
  3195. local r = vim.version.range('1.0.0 - 2.0.0') -- >=1.0, <2.0
  3196. print(vim.version.ge({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to))
  3197. <
  3198. Attributes: ~
  3199. Since: 0.9.0
  3200. Parameters: ~
  3201. • {spec} (`string`) Version range "spec"
  3202. Return: ~
  3203. (`table?`) A table with the following fields:
  3204. • {from} (`vim.Version`)
  3205. • {to}? (`vim.Version`)
  3206. • {has} (`fun(self: vim.VersionRange, version: string|vim.Version)`)
  3207. See also: ~
  3208. • https://github.com/npm/node-semver#ranges
  3209. ==============================================================================
  3210. Lua module: vim.iter *vim.iter*
  3211. *vim.iter()* is an interface for |iterable|s: it wraps a table or function
  3212. argument into an *Iter* object with methods (such as |Iter:filter()| and
  3213. |Iter:map()|) that transform the underlying source data. These methods can be
  3214. chained to create iterator "pipelines": the output of each pipeline stage is
  3215. input to the next stage. The first stage depends on the type passed to
  3216. `vim.iter()`:
  3217. • Lists or arrays (|lua-list|) yield only the value of each element.
  3218. • Holes (nil values) are allowed (but discarded).
  3219. • Use pairs() to treat array/list tables as dicts (preserve holes and
  3220. non-contiguous integer keys): `vim.iter(pairs(…))`.
  3221. • Use |Iter:enumerate()| to also pass the index to the next stage.
  3222. • Or initialize with ipairs(): `vim.iter(ipairs(…))`.
  3223. • Non-list tables (|lua-dict|) yield both the key and value of each element.
  3224. • Function |iterator|s yield all values returned by the underlying function.
  3225. • Tables with a |__call()| metamethod are treated as function iterators.
  3226. The iterator pipeline terminates when the underlying |iterable| is exhausted
  3227. (for function iterators this means it returned nil).
  3228. Note: `vim.iter()` scans table input to decide if it is a list or a dict; to
  3229. avoid this cost you can wrap the table with an iterator e.g.
  3230. `vim.iter(ipairs({…}))`, but that precludes the use of |list-iterator|
  3231. operations such as |Iter:rev()|).
  3232. Examples: >lua
  3233. local it = vim.iter({ 1, 2, 3, 4, 5 })
  3234. it:map(function(v)
  3235. return v * 3
  3236. end)
  3237. it:rev()
  3238. it:skip(2)
  3239. it:totable()
  3240. -- { 9, 6, 3 }
  3241. -- ipairs() is a function iterator which returns both the index (i) and the value (v)
  3242. vim.iter(ipairs({ 1, 2, 3, 4, 5 })):map(function(i, v)
  3243. if i > 2 then return v end
  3244. end):totable()
  3245. -- { 3, 4, 5 }
  3246. local it = vim.iter(vim.gsplit('1,2,3,4,5', ','))
  3247. it:map(function(s) return tonumber(s) end)
  3248. for i, d in it:enumerate() do
  3249. print(string.format("Column %d is %d", i, d))
  3250. end
  3251. -- Column 1 is 1
  3252. -- Column 2 is 2
  3253. -- Column 3 is 3
  3254. -- Column 4 is 4
  3255. -- Column 5 is 5
  3256. vim.iter({ a = 1, b = 2, c = 3, z = 26 }):any(function(k, v)
  3257. return k == 'z'
  3258. end)
  3259. -- true
  3260. local rb = vim.ringbuf(3)
  3261. rb:push("a")
  3262. rb:push("b")
  3263. vim.iter(rb):totable()
  3264. -- { "a", "b" }
  3265. <
  3266. Iter:all({pred}) *Iter:all()*
  3267. Returns true if all items in the iterator match the given predicate.
  3268. Parameters: ~
  3269. • {pred} (`fun(...):boolean`) Predicate function. Takes all values
  3270. returned from the previous stage in the pipeline as arguments
  3271. and returns true if the predicate matches.
  3272. Iter:any({pred}) *Iter:any()*
  3273. Returns true if any of the items in the iterator match the given
  3274. predicate.
  3275. Parameters: ~
  3276. • {pred} (`fun(...):boolean`) Predicate function. Takes all values
  3277. returned from the previous stage in the pipeline as arguments
  3278. and returns true if the predicate matches.
  3279. Iter:each({f}) *Iter:each()*
  3280. Calls a function once for each item in the pipeline, draining the
  3281. iterator.
  3282. For functions with side effects. To modify the values in the iterator, use
  3283. |Iter:map()|.
  3284. Parameters: ~
  3285. • {f} (`fun(...)`) Function to execute for each item in the pipeline.
  3286. Takes all of the values returned by the previous stage in the
  3287. pipeline as arguments.
  3288. Iter:enumerate() *Iter:enumerate()*
  3289. Yields the item index (count) and value for each item of an iterator
  3290. pipeline.
  3291. For list tables, this is more efficient: >lua
  3292. vim.iter(ipairs(t))
  3293. <
  3294. instead of: >lua
  3295. vim.iter(t):enumerate()
  3296. <
  3297. Example: >lua
  3298. local it = vim.iter(vim.gsplit('abc', '')):enumerate()
  3299. it:next()
  3300. -- 1 'a'
  3301. it:next()
  3302. -- 2 'b'
  3303. it:next()
  3304. -- 3 'c'
  3305. <
  3306. Return: ~
  3307. (`Iter`)
  3308. Iter:filter({f}) *Iter:filter()*
  3309. Filters an iterator pipeline.
  3310. Example: >lua
  3311. local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
  3312. <
  3313. Parameters: ~
  3314. • {f} (`fun(...):boolean`) Takes all values returned from the previous
  3315. stage in the pipeline and returns false or nil if the current
  3316. iterator element should be removed.
  3317. Return: ~
  3318. (`Iter`)
  3319. Iter:find({f}) *Iter:find()*
  3320. Find the first value in the iterator that satisfies the given predicate.
  3321. Advances the iterator. Returns nil and drains the iterator if no value is
  3322. found.
  3323. Examples: >lua
  3324. local it = vim.iter({ 3, 6, 9, 12 })
  3325. it:find(12)
  3326. -- 12
  3327. local it = vim.iter({ 3, 6, 9, 12 })
  3328. it:find(20)
  3329. -- nil
  3330. local it = vim.iter({ 3, 6, 9, 12 })
  3331. it:find(function(v) return v % 4 == 0 end)
  3332. -- 12
  3333. <
  3334. Parameters: ~
  3335. • {f} (`any`)
  3336. Return: ~
  3337. (`any`)
  3338. Iter:flatten({depth}) *Iter:flatten()*
  3339. Flattens a |list-iterator|, un-nesting nested values up to the given
  3340. {depth}. Errors if it attempts to flatten a dict-like value.
  3341. Examples: >lua
  3342. vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable()
  3343. -- { 1, 2, { 3 } }
  3344. vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable()
  3345. -- { 1, { a = 2 }, 3 }
  3346. vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable()
  3347. -- error: attempt to flatten a dict-like table
  3348. <
  3349. Parameters: ~
  3350. • {depth} (`number?`) Depth to which |list-iterator| should be
  3351. flattened (defaults to 1)
  3352. Return: ~
  3353. (`Iter`)
  3354. Iter:fold({init}, {f}) *Iter:fold()*
  3355. Folds ("reduces") an iterator into a single value. *Iter:reduce()*
  3356. Examples: >lua
  3357. -- Create a new table with only even values
  3358. vim.iter({ a = 1, b = 2, c = 3, d = 4 })
  3359. :filter(function(k, v) return v % 2 == 0 end)
  3360. :fold({}, function(acc, k, v)
  3361. acc[k] = v
  3362. return acc
  3363. end) --> { b = 2, d = 4 }
  3364. -- Get the "maximum" item of an iterable.
  3365. vim.iter({ -99, -4, 3, 42, 0, 0, 7 })
  3366. :fold({}, function(acc, v)
  3367. acc.max = math.max(v, acc.max or v)
  3368. return acc
  3369. end) --> { max = 42 }
  3370. <
  3371. Parameters: ~
  3372. • {init} (`any`) Initial value of the accumulator.
  3373. • {f} (`fun(acc:A, ...):A`) Accumulation function.
  3374. Return: ~
  3375. (`any`)
  3376. Iter:join({delim}) *Iter:join()*
  3377. Collect the iterator into a delimited string.
  3378. Each element in the iterator is joined into a string separated by {delim}.
  3379. Consumes the iterator.
  3380. Parameters: ~
  3381. • {delim} (`string`) Delimiter
  3382. Return: ~
  3383. (`string`)
  3384. Iter:last() *Iter:last()*
  3385. Drains the iterator and returns the last item.
  3386. Example: >lua
  3387. local it = vim.iter(vim.gsplit('abcdefg', ''))
  3388. it:last()
  3389. -- 'g'
  3390. local it = vim.iter({ 3, 6, 9, 12, 15 })
  3391. it:last()
  3392. -- 15
  3393. <
  3394. Return: ~
  3395. (`any`)
  3396. See also: ~
  3397. • Iter.rpeek
  3398. Iter:map({f}) *Iter:map()*
  3399. Maps the items of an iterator pipeline to the values returned by `f`.
  3400. If the map function returns nil, the value is filtered from the iterator.
  3401. Example: >lua
  3402. local it = vim.iter({ 1, 2, 3, 4 }):map(function(v)
  3403. if v % 2 == 0 then
  3404. return v * 3
  3405. end
  3406. end)
  3407. it:totable()
  3408. -- { 6, 12 }
  3409. <
  3410. Parameters: ~
  3411. • {f} (`fun(...):...:any`) Mapping function. Takes all values returned
  3412. from the previous stage in the pipeline as arguments and returns
  3413. one or more new values, which are used in the next pipeline
  3414. stage. Nil return values are filtered from the output.
  3415. Return: ~
  3416. (`Iter`)
  3417. Iter:next() *Iter:next()*
  3418. Gets the next value from the iterator.
  3419. Example: >lua
  3420. local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber)
  3421. it:next()
  3422. -- 1
  3423. it:next()
  3424. -- 2
  3425. it:next()
  3426. -- 3
  3427. <
  3428. Return: ~
  3429. (`any`)
  3430. Iter:nth({n}) *Iter:nth()*
  3431. Gets the nth value of an iterator (and advances to it).
  3432. If `n` is negative, offsets from the end of a |list-iterator|.
  3433. Example: >lua
  3434. local it = vim.iter({ 3, 6, 9, 12 })
  3435. it:nth(2)
  3436. -- 6
  3437. it:nth(2)
  3438. -- 12
  3439. local it2 = vim.iter({ 3, 6, 9, 12 })
  3440. it2:nth(-2)
  3441. -- 9
  3442. it2:nth(-2)
  3443. -- 3
  3444. <
  3445. Parameters: ~
  3446. • {n} (`number`) Index of the value to return. May be negative if the
  3447. source is a |list-iterator|.
  3448. Return: ~
  3449. (`any`)
  3450. Iter:peek() *Iter:peek()*
  3451. Gets the next value in a |list-iterator| without consuming it.
  3452. Example: >lua
  3453. local it = vim.iter({ 3, 6, 9, 12 })
  3454. it:peek()
  3455. -- 3
  3456. it:peek()
  3457. -- 3
  3458. it:next()
  3459. -- 3
  3460. <
  3461. Return: ~
  3462. (`any`)
  3463. Iter:pop() *Iter:pop()*
  3464. "Pops" a value from a |list-iterator| (gets the last value and decrements
  3465. the tail).
  3466. Example: >lua
  3467. local it = vim.iter({1, 2, 3, 4})
  3468. it:pop()
  3469. -- 4
  3470. it:pop()
  3471. -- 3
  3472. <
  3473. Return: ~
  3474. (`any`)
  3475. Iter:rev() *Iter:rev()*
  3476. Reverses a |list-iterator| pipeline.
  3477. Example: >lua
  3478. local it = vim.iter({ 3, 6, 9, 12 }):rev()
  3479. it:totable()
  3480. -- { 12, 9, 6, 3 }
  3481. <
  3482. Return: ~
  3483. (`Iter`)
  3484. Iter:rfind({f}) *Iter:rfind()*
  3485. Gets the first value satisfying a predicate, from the end of a
  3486. |list-iterator|.
  3487. Advances the iterator. Returns nil and drains the iterator if no value is
  3488. found.
  3489. Examples: >lua
  3490. local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
  3491. it:rfind(1)
  3492. -- 5 1
  3493. it:rfind(1)
  3494. -- 1 1
  3495. <
  3496. Parameters: ~
  3497. • {f} (`any`)
  3498. Return: ~
  3499. (`any`)
  3500. See also: ~
  3501. • Iter.find
  3502. Iter:rpeek() *Iter:rpeek()*
  3503. Gets the last value of a |list-iterator| without consuming it.
  3504. Example: >lua
  3505. local it = vim.iter({1, 2, 3, 4})
  3506. it:rpeek()
  3507. -- 4
  3508. it:rpeek()
  3509. -- 4
  3510. it:pop()
  3511. -- 4
  3512. <
  3513. Return: ~
  3514. (`any`)
  3515. See also: ~
  3516. • Iter.last
  3517. Iter:rskip({n}) *Iter:rskip()*
  3518. Discards `n` values from the end of a |list-iterator| pipeline.
  3519. Example: >lua
  3520. local it = vim.iter({ 1, 2, 3, 4, 5 }):rskip(2)
  3521. it:next()
  3522. -- 1
  3523. it:pop()
  3524. -- 3
  3525. <
  3526. Parameters: ~
  3527. • {n} (`number`) Number of values to skip.
  3528. Return: ~
  3529. (`Iter`)
  3530. Iter:skip({n}) *Iter:skip()*
  3531. Skips `n` values of an iterator pipeline.
  3532. Example: >lua
  3533. local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
  3534. it:next()
  3535. -- 9
  3536. <
  3537. Parameters: ~
  3538. • {n} (`number`) Number of values to skip.
  3539. Return: ~
  3540. (`Iter`)
  3541. Iter:slice({first}, {last}) *Iter:slice()*
  3542. Sets the start and end of a |list-iterator| pipeline.
  3543. Equivalent to `:skip(first - 1):rskip(len - last + 1)`.
  3544. Parameters: ~
  3545. • {first} (`number`)
  3546. • {last} (`number`)
  3547. Return: ~
  3548. (`Iter`)
  3549. Iter:take({n}) *Iter:take()*
  3550. Transforms an iterator to yield only the first n values.
  3551. Example: >lua
  3552. local it = vim.iter({ 1, 2, 3, 4 }):take(2)
  3553. it:next()
  3554. -- 1
  3555. it:next()
  3556. -- 2
  3557. it:next()
  3558. -- nil
  3559. <
  3560. Parameters: ~
  3561. • {n} (`integer`)
  3562. Return: ~
  3563. (`Iter`)
  3564. Iter:totable() *Iter:totable()*
  3565. Collect the iterator into a table.
  3566. The resulting table depends on the initial source in the iterator
  3567. pipeline. Array-like tables and function iterators will be collected into
  3568. an array-like table. If multiple values are returned from the final stage
  3569. in the iterator pipeline, each value will be included in a table.
  3570. Examples: >lua
  3571. vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable()
  3572. -- { 100, 20, 50 }
  3573. vim.iter({ 1, 2, 3 }):map(function(v) return v, 2 * v end):totable()
  3574. -- { { 1, 2 }, { 2, 4 }, { 3, 6 } }
  3575. vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable()
  3576. -- { { 'a', 1 }, { 'c', 3 } }
  3577. <
  3578. The generated table is an array-like table with consecutive, numeric
  3579. indices. To create a map-like table with arbitrary keys, use
  3580. |Iter:fold()|.
  3581. Return: ~
  3582. (`table`)
  3583. ==============================================================================
  3584. Lua module: vim.snippet *vim.snippet*
  3585. *vim.snippet.ActiveFilter*
  3586. Fields: ~
  3587. • {direction} (`vim.snippet.Direction`) Navigation direction. -1 for
  3588. previous, 1 for next.
  3589. vim.snippet.active({filter}) *vim.snippet.active()*
  3590. Returns `true` if there's an active snippet in the current buffer,
  3591. applying the given filter if provided.
  3592. You can use this function to navigate a snippet as follows: >lua
  3593. vim.keymap.set({ 'i', 's' }, '<Tab>', function()
  3594. if vim.snippet.active({ direction = 1 }) then
  3595. return '<Cmd>lua vim.snippet.jump(1)<CR>'
  3596. else
  3597. return '<Tab>'
  3598. end
  3599. end, { expr = true })
  3600. <
  3601. Parameters: ~
  3602. • {filter} (`vim.snippet.ActiveFilter?`) Filter to constrain the search
  3603. with:
  3604. • `direction` (vim.snippet.Direction): Navigation direction.
  3605. Will return `true` if the snippet can be jumped in the
  3606. given direction. See |vim.snippet.ActiveFilter|.
  3607. Return: ~
  3608. (`boolean`)
  3609. vim.snippet.expand({input}) *vim.snippet.expand()*
  3610. Expands the given snippet text. Refer to
  3611. https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax
  3612. for the specification of valid input.
  3613. Tabstops are highlighted with |hl-SnippetTabstop|.
  3614. Parameters: ~
  3615. • {input} (`string`)
  3616. vim.snippet.jump({direction}) *vim.snippet.jump()*
  3617. Jumps to the next (or previous) placeholder in the current snippet, if
  3618. possible.
  3619. For example, map `<Tab>` to jump while a snippet is active: >lua
  3620. vim.keymap.set({ 'i', 's' }, '<Tab>', function()
  3621. if vim.snippet.active({ direction = 1 }) then
  3622. return '<Cmd>lua vim.snippet.jump(1)<CR>'
  3623. else
  3624. return '<Tab>'
  3625. end
  3626. end, { expr = true })
  3627. <
  3628. Parameters: ~
  3629. • {direction} (`vim.snippet.Direction`) Navigation direction. -1 for
  3630. previous, 1 for next.
  3631. vim.snippet.stop() *vim.snippet.stop()*
  3632. Exits the current snippet.
  3633. ==============================================================================
  3634. Lua module: vim.text *vim.text*
  3635. vim.text.hexdecode({enc}) *vim.text.hexdecode()*
  3636. Hex decode a string.
  3637. Parameters: ~
  3638. • {enc} (`string`) String to decode
  3639. Return (multiple): ~
  3640. (`string?`) Decoded string
  3641. (`string?`) Error message, if any
  3642. vim.text.hexencode({str}) *vim.text.hexencode()*
  3643. Hex encode a string.
  3644. Parameters: ~
  3645. • {str} (`string`) String to encode
  3646. Return: ~
  3647. (`string`) Hex encoded string
  3648. ==============================================================================
  3649. Lua module: tohtml *vim.tohtml*
  3650. :[range]TOhtml {file} *:TOhtml*
  3651. Converts the buffer shown in the current window to HTML, opens the generated
  3652. HTML in a new split window, and saves its contents to {file}. If {file} is not
  3653. given, a temporary file (created by |tempname()|) is used.
  3654. tohtml.tohtml({winid}, {opt}) *tohtml.tohtml.tohtml()*
  3655. Converts the buffer shown in the window {winid} to HTML and returns the
  3656. output as a list of string.
  3657. Parameters: ~
  3658. • {winid} (`integer?`) Window to convert (defaults to current window)
  3659. • {opt} (`table?`) Optional parameters.
  3660. • {title}? (`string|false`, default: buffer name) Title tag
  3661. to set in the generated HTML code.
  3662. • {number_lines}? (`boolean`, default: `false`) Show line
  3663. numbers.
  3664. • {font}? (`string[]|string`, default: `guifont`) Fonts to
  3665. use.
  3666. • {width}? (`integer`, default: 'textwidth' if non-zero or
  3667. window width otherwise) Width used for items which are
  3668. either right aligned or repeat a character infinitely.
  3669. • {range}? (`integer[]`, default: entire buffer) Range of
  3670. rows to use.
  3671. Return: ~
  3672. (`string[]`)
  3673. vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: