lua.txt 171 KB

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