lua.txt 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341
  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: >
  9. :lua print(vim.inspect(package.loaded))
  10. Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the
  11. "editor stdlib" (|builtin-functions| and |Ex-commands|) and the |API|, all of
  12. which can be used from Lua code (|lua-vimscript| |vim.api|). Together these
  13. "namespaces" form the Nvim programming interface.
  14. See the |lua-guide| for an introduction to using Lua in Neovim.
  15. *lua-compat*
  16. Lua 5.1 is the permanent interface for Nvim Lua. Plugins need only consider
  17. Lua 5.1, not worry about forward-compatibility with future Lua versions. If
  18. Nvim ever ships with Lua 5.4+, a Lua 5.1 compatibility shim will be provided
  19. so that old plugins continue to work transparently.
  20. ------------------------------------------------------------------------------
  21. LUA CONCEPTS AND IDIOMS *lua-concepts*
  22. Lua is very simple: this means that, while there are some quirks, once you
  23. internalize those quirks, everything works the same everywhere. Scopes
  24. (closures) in particular are very consistent, unlike JavaScript or most other
  25. languages.
  26. Lua has three fundamental mechanisms—one for "each major aspect of
  27. programming": tables, closures, and coroutines.
  28. https://www.lua.org/doc/cacm2018.pdf
  29. - Tables are the "object" or container datastructure: they represent both
  30. lists and maps, you can extend them to represent your own datatypes and
  31. change their behavior using |luaref-metatable| (like Python's "datamodel").
  32. - EVERY scope in Lua is a closure: a function is a closure, a module is
  33. a closure, a `do` block (|luaref-do|) is a closure--and they all work the
  34. same. A Lua module is literally just a big closure discovered on the "path"
  35. (where your modules are found: |package.cpath|).
  36. - Stackful coroutines enable cooperative multithreading, generators, and
  37. versatile control for both Lua and its host (Nvim).
  38. *lua-call-function*
  39. Lua functions can be called in multiple ways. Consider the function: >
  40. local foo = function(a, b)
  41. print("A: ", a)
  42. print("B: ", b)
  43. end
  44. The first way to call this function is: >
  45. foo(1, 2)
  46. -- ==== Result ====
  47. -- A: 1
  48. -- B: 2
  49. This way of calling a function is familiar from most scripting languages.
  50. In Lua, any missing arguments are passed as `nil`. Example: >
  51. foo(1)
  52. -- ==== Result ====
  53. -- A: 1
  54. -- B: nil
  55. Furthermore it is not an error if extra parameters are passed, they are just
  56. discarded.
  57. It is also allowed to omit the parentheses (only) if the function takes
  58. exactly one string (`"foo"`) or table literal (`{1,2,3}`). The latter is often
  59. used to approximate the "named parameters" feature of languages like Python
  60. ("kwargs" or "keyword args"). Example: >
  61. local func_with_opts = function(opts)
  62. local will_do_foo = opts.foo
  63. local filename = opts.filename
  64. ...
  65. end
  66. func_with_opts { foo = true, filename = "hello.world" }
  67. <
  68. There is nothing special going on here except that parentheses are treated as
  69. whitespace. But visually, this small bit of sugar gets reasonably close to
  70. a "keyword args" interface.
  71. It is of course also valid to call the function with parentheses: >
  72. func_with_opts({ foo = true, filename = "hello.world" })
  73. <
  74. Nvim tends to prefer the keyword args style.
  75. ------------------------------------------------------------------------------
  76. LUA PATTERNS *lua-patterns*
  77. Lua intentionally does not support regular expressions, instead it has limited
  78. "patterns" which avoid the performance pitfalls of extended regex.
  79. |luaref-patterns|
  80. Examples using |string.match()|: >
  81. print(string.match("foo123bar123", "%d+"))
  82. -- 123
  83. print(string.match("foo123bar123", "[^%d]+"))
  84. -- foo
  85. print(string.match("foo123bar123", "[abc]+"))
  86. -- ba
  87. print(string.match("foo.bar", "%.bar"))
  88. -- .bar
  89. For more complex matching you can use Vim regex from Lua via |vim.regex()|.
  90. ==============================================================================
  91. IMPORTING LUA MODULES *require()* *lua-require*
  92. Modules are searched for under the directories specified in 'runtimepath', in
  93. the order they appear. Any "." in the module name is treated as a directory
  94. separator when searching. For a module `foo.bar`, each directory is searched
  95. for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found,
  96. the directories are searched again for a shared library with a name matching
  97. `lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`) derived from
  98. the initial value of |package.cpath|. If still no files are found, Nvim falls
  99. back to Lua's default search mechanism. The first script found is run and
  100. `require()` returns the value returned by the script if any, else `true`.
  101. The return value is cached after the first call to `require()` for each module,
  102. with subsequent calls returning the cached value without searching for, or
  103. executing any script. For further details on `require()`, see the Lua
  104. documentation at https://www.lua.org/manual/5.1/manual.html#pdf-require.
  105. For example, if 'runtimepath' is `foo,bar` and |package.cpath| was
  106. `./?.so;./?.dll` at startup, `require('mod')` searches these paths in order
  107. and loads the first module found ("first wins"): >
  108. foo/lua/mod.lua
  109. foo/lua/mod/init.lua
  110. bar/lua/mod.lua
  111. bar/lua/mod/init.lua
  112. foo/lua/mod.so
  113. foo/lua/mod.dll
  114. bar/lua/mod.so
  115. bar/lua/mod.dll
  116. <
  117. *lua-package-path*
  118. Nvim automatically adjusts |package.path| and |package.cpath| according to the
  119. effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is
  120. changed. `package.path` is adjusted by simply appending `/lua/?.lua` and
  121. `/lua/?/init.lua` to each directory from 'runtimepath' (`/` is actually the
  122. first character of `package.config`).
  123. Similarly to |package.path|, modified directories from 'runtimepath' are also
  124. added to |package.cpath|. In this case, instead of appending `/lua/?.lua` and
  125. `/lua/?/init.lua` to each runtimepath, all unique `?`-containing suffixes of
  126. the existing |package.cpath| are used. Example:
  127. - 1. Given that
  128. - 'runtimepath' contains `/foo/bar,/xxx;yyy/baz,/abc`;
  129. - initial |package.cpath| (defined at compile-time or derived from
  130. `$LUA_CPATH` / `$LUA_INIT`) contains `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`.
  131. - 2. It finds `?`-containing suffixes `/?.so`, `/a?d/j/g.elf` and `/?.so`, in
  132. order: parts of the path starting from the first path component containing
  133. question mark and preceding path separator.
  134. - 3. The suffix of `/def/?.so`, namely `/?.so` is not unique, as it’s the same
  135. as the suffix of the first path from |package.path| (i.e. `./?.so`). Which
  136. leaves `/?.so` and `/a?d/j/g.elf`, in this order.
  137. - 4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The
  138. second one contains a semicolon which is a paths separator so it is out,
  139. leaving only `/foo/bar` and `/abc`, in order.
  140. - 5. The cartesian product of paths from 4. and suffixes from 3. is taken,
  141. giving four variants. In each variant a `/lua` path segment is inserted
  142. between path and suffix, leaving:
  143. - `/foo/bar/lua/?.so`
  144. - `/foo/bar/lua/a?d/j/g.elf`
  145. - `/abc/lua/?.so`
  146. - `/abc/lua/a?d/j/g.elf`
  147. - 6. New paths are prepended to the original |package.cpath|.
  148. The result will look like this: >
  149. /foo/bar,/xxx;yyy/baz,/abc ('runtimepath')
  150. × ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so (package.cpath)
  151. = /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
  152. Note:
  153. - To track 'runtimepath' updates, paths added at previous update are
  154. remembered and removed at the next update, while all paths derived from the
  155. new 'runtimepath' are prepended as described above. This allows removing
  156. paths when path is removed from 'runtimepath', adding paths when they are
  157. added and reordering |package.path|/|package.cpath| content if 'runtimepath'
  158. was reordered.
  159. - Although adjustments happen automatically, Nvim does not track current
  160. values of |package.path| or |package.cpath|. If you happen to delete some
  161. paths from there you can set 'runtimepath' to trigger an update: >
  162. let &runtimepath = &runtimepath
  163. - Skipping paths from 'runtimepath' which contain semicolons applies both to
  164. |package.path| and |package.cpath|. Given that there are some badly written
  165. plugins using shell, which will not work with paths containing semicolons,
  166. it is better to not have them in 'runtimepath' at all.
  167. ==============================================================================
  168. COMMANDS *lua-commands*
  169. These commands execute a Lua chunk from either the command line (:lua, :luado)
  170. or a file (:luafile) on the given line [range]. As always in Lua, each chunk
  171. has its own scope (closure), so only global variables are shared between
  172. command calls. The |lua-stdlib| modules, user modules, and anything else on
  173. |package.path| are available.
  174. The Lua print() function redirects its output to the Nvim message area, with
  175. arguments separated by " " (space) instead of "\t" (tab).
  176. *:lua*
  177. :lua {chunk}
  178. Executes Lua chunk {chunk}. If {chunk} starts with "=" the rest of the
  179. chunk is evaluated as an expression and printed. `:lua =expr` is
  180. equivalent to `:lua print(vim.inspect(expr))`
  181. Examples: >
  182. :lua vim.api.nvim_command('echo "Hello, Nvim!"')
  183. < To see the Lua version: >
  184. :lua print(_VERSION)
  185. < To see the LuaJIT version: >
  186. :lua =jit.version
  187. <
  188. *:lua-heredoc*
  189. :lua << [endmarker]
  190. {script}
  191. {endmarker}
  192. Executes Lua script {script} from within Vimscript. {endmarker} must NOT
  193. be preceded by whitespace. You can omit [endmarker] after the "<<" and use
  194. a dot "." after {script} (similar to |:append|, |:insert|).
  195. Example: >
  196. function! CurrentLineInfo()
  197. lua << EOF
  198. local linenr = vim.api.nvim_win_get_cursor(0)[1]
  199. local curline = vim.api.nvim_buf_get_lines(
  200. 0, linenr - 1, linenr, false)[1]
  201. print(string.format("Current line [%d] has %d bytes",
  202. linenr, #curline))
  203. EOF
  204. endfunction
  205. <
  206. Note that the `local` variables will disappear when the block finishes.
  207. But not globals.
  208. *:luado*
  209. :[range]luado {body}
  210. Executes Lua chunk "function(line, linenr) {body} end" for each buffer
  211. line in [range], where `line` is the current line text (without <EOL>),
  212. and `linenr` is the current line number. If the function returns a string
  213. that becomes the text of the corresponding buffer line. Default [range] is
  214. the whole file: "1,$".
  215. Examples: >
  216. :luado return string.format("%s\t%d", line:reverse(), #line)
  217. :lua require"lpeg"
  218. :lua -- balanced parenthesis grammar:
  219. :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
  220. :luado if bp:match(line) then return "=>\t" .. line end
  221. <
  222. *:luafile*
  223. :luafile {file}
  224. Execute Lua script in {file}.
  225. The whole argument is used as the filename (like |:edit|), spaces do not
  226. need to be escaped. Alternatively you can |:source| Lua files.
  227. Examples: >
  228. :luafile script.lua
  229. :luafile %
  230. <
  231. ==============================================================================
  232. luaeval() *lua-eval* *luaeval()*
  233. The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is
  234. "luaeval". "luaeval" takes an expression string and an optional argument used
  235. for _A inside expression and returns the result of the expression. It is
  236. semantically equivalent in Lua to: >
  237. local chunkheader = "local _A = select(1, ...) return "
  238. function luaeval (expstr, arg)
  239. local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
  240. return chunk(arg) -- return typval
  241. end
  242. <
  243. Lua nils, numbers, strings, tables and booleans are converted to their
  244. respective Vimscript types. If a Lua string contains a NUL byte, it will be
  245. converted to a |Blob|. Conversion of other Lua types is an error.
  246. The magic global "_A" contains the second argument to luaeval().
  247. Example: >
  248. :echo luaeval('_A[1] + _A[2]', [40, 2])
  249. 42
  250. :echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123')
  251. foo
  252. <
  253. Lua tables are used as both dictionaries and lists, so it is impossible to
  254. determine whether empty table is meant to be empty list or empty dictionary.
  255. Additionally Lua does not have integer numbers. To distinguish between these
  256. cases there is the following agreement:
  257. 0. Empty table is empty list.
  258. 1. Table with N incrementally growing integral numbers, starting from 1 and
  259. ending with N is considered to be a list.
  260. 2. Table with string keys, none of which contains NUL byte, is considered to
  261. be a dictionary.
  262. 3. Table with string keys, at least one of which contains NUL byte, is also
  263. considered to be a dictionary, but this time it is converted to
  264. a |msgpack-special-map|.
  265. *lua-special-tbl*
  266. 4. Table with `vim.type_idx` key may be a dictionary, a list or floating-point
  267. value:
  268. - `{[vim.type_idx]=vim.types.float, [vim.val_idx]=1}` is converted to
  269. a floating-point 1.0. Note that by default integral Lua numbers are
  270. converted to |Number|s, non-integral are converted to |Float|s. This
  271. variant allows integral |Float|s.
  272. - `{[vim.type_idx]=vim.types.dictionary}` is converted to an empty
  273. dictionary, `{[vim.type_idx]=vim.types.dictionary, [42]=1, a=2}` is
  274. converted to a dictionary `{'a': 42}`: non-string keys are ignored.
  275. Without `vim.type_idx` key tables with keys not fitting in 1., 2. or 3.
  276. are errors.
  277. - `{[vim.type_idx]=vim.types.array}` is converted to an empty list. As well
  278. as `{[vim.type_idx]=vim.types.array, [42]=1}`: integral keys that do not
  279. form a 1-step sequence from 1 to N are ignored, as well as all
  280. non-integral keys.
  281. Examples: >
  282. :echo luaeval('math.pi')
  283. :function Rand(x,y) " random uniform between x and y
  284. : return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
  285. : endfunction
  286. :echo Rand(1,10)
  287. <
  288. Note: Second argument to `luaeval` is converted ("marshalled") from Vimscript
  289. to Lua, so changes to Lua containers do not affect values in Vimscript. Return
  290. value is also always converted. When converting, |msgpack-special-dict|s are
  291. treated specially.
  292. ==============================================================================
  293. Vimscript v:lua interface *v:lua-call*
  294. From Vimscript the special `v:lua` prefix can be used to call Lua functions
  295. which are global or accessible from global tables. The expression >
  296. v:lua.func(arg1, arg2)
  297. is equivalent to the Lua chunk >
  298. return func(...)
  299. where the args are converted to Lua values. The expression >
  300. v:lua.somemod.func(args)
  301. is equivalent to the Lua chunk >
  302. return somemod.func(...)
  303. In addition, functions of packages can be accessed like >
  304. v:lua.require'mypack'.func(arg1, arg2)
  305. v:lua.require'mypack.submod'.func(arg1, arg2)
  306. Note: Only single quote form without parens is allowed. Using
  307. `require"mypack"` or `require('mypack')` as prefixes do NOT work (the latter
  308. is still valid as a function call of itself, in case require returns a useful
  309. value).
  310. The `v:lua` prefix may be used to call Lua functions as |method|s. For
  311. example: >
  312. arg1->v:lua.somemod.func(arg2)
  313. <
  314. You can use `v:lua` in "func" options like 'tagfunc', 'omnifunc', etc.
  315. For example consider the following Lua omnifunc handler: >
  316. function mymod.omnifunc(findstart, base)
  317. if findstart == 1 then
  318. return 0
  319. else
  320. return {'stuff', 'steam', 'strange things'}
  321. end
  322. end
  323. vim.api.nvim_buf_set_option(0, 'omnifunc', 'v:lua.mymod.omnifunc')
  324. Note: The module ("mymod" in the above example) must either be a Lua global,
  325. or use the require syntax as specified above to access it from a package.
  326. Note: `v:lua` without a call is not allowed in a Vimscript expression:
  327. |Funcref|s cannot represent Lua functions. The following are errors: >
  328. let g:Myvar = v:lua.myfunc " Error
  329. call SomeFunc(v:lua.mycallback) " Error
  330. let g:foo = v:lua " Error
  331. let g:foo = v:['lua'] " Error
  332. <
  333. ==============================================================================
  334. Lua standard modules *lua-stdlib*
  335. The Nvim Lua "standard library" (stdlib) is the `vim` module, which exposes
  336. various functions and sub-modules. It is always loaded, thus `require("vim")`
  337. is unnecessary.
  338. You can peek at the module properties: >
  339. :lua print(vim.inspect(vim))
  340. Result is something like this: >
  341. {
  342. _os_proc_children = <function 1>,
  343. _os_proc_info = <function 2>,
  344. ...
  345. api = {
  346. nvim__id = <function 5>,
  347. nvim__id_array = <function 6>,
  348. ...
  349. },
  350. deepcopy = <function 106>,
  351. gsplit = <function 107>,
  352. ...
  353. }
  354. To find documentation on e.g. the "deepcopy" function: >
  355. :help vim.deepcopy()
  356. Note that underscore-prefixed functions (e.g. "_os_proc_children") are
  357. internal/private and must not be used by plugins.
  358. ------------------------------------------------------------------------------
  359. VIM.LOOP *lua-loop* *vim.loop*
  360. `vim.loop` exposes all features of the Nvim event-loop. This is a low-level
  361. API that provides functionality for networking, filesystem, and process
  362. management. Try this command to see available functions: >
  363. :lua print(vim.inspect(vim.loop))
  364. <
  365. Internally, `vim.loop` wraps the "luv" Lua bindings for the LibUV library;
  366. see |luv-intro| for a full reference manual.
  367. *E5560* *lua-loop-callbacks*
  368. It is an error to directly invoke `vim.api` functions (except |api-fast|) in
  369. `vim.loop` callbacks. For example, this is an error: >
  370. local timer = vim.loop.new_timer()
  371. timer:start(1000, 0, function()
  372. vim.api.nvim_command('echomsg "test"')
  373. end)
  374. <
  375. To avoid the error use |vim.schedule_wrap()| to defer the callback: >
  376. local timer = vim.loop.new_timer()
  377. timer:start(1000, 0, vim.schedule_wrap(function()
  378. vim.api.nvim_command('echomsg "test"')
  379. end))
  380. <
  381. (For one-shot timers, see |vim.defer_fn()|, which automatically adds the
  382. wrapping.)
  383. Example: repeating timer
  384. 1. Save this code to a file.
  385. 2. Execute it with ":luafile %". >
  386. -- Create a timer handle (implementation detail: uv_timer_t).
  387. local timer = vim.loop.new_timer()
  388. local i = 0
  389. -- Waits 1000ms, then repeats every 750ms until timer:close().
  390. timer:start(1000, 750, function()
  391. print('timer invoked! i='..tostring(i))
  392. if i > 4 then
  393. timer:close() -- Always close handles to avoid leaks.
  394. end
  395. i = i + 1
  396. end)
  397. print('sleeping');
  398. <
  399. Example: File-change detection *watch-file*
  400. 1. Save this code to a file.
  401. 2. Execute it with ":luafile %".
  402. 3. Use ":Watch %" to watch any file.
  403. 4. Try editing the file from another text editor.
  404. 5. Observe that the file reloads in Nvim (because on_change() calls
  405. |:checktime|). >
  406. local w = vim.loop.new_fs_event()
  407. local function on_change(err, fname, status)
  408. -- Do work...
  409. vim.api.nvim_command('checktime')
  410. -- Debounce: stop/start.
  411. w:stop()
  412. watch_file(fname)
  413. end
  414. function watch_file(fname)
  415. local fullpath = vim.api.nvim_call_function(
  416. 'fnamemodify', {fname, ':p'})
  417. w:start(fullpath, {}, vim.schedule_wrap(function(...)
  418. on_change(...) end))
  419. end
  420. vim.api.nvim_command(
  421. "command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))")
  422. <
  423. Example: TCP echo-server *tcp-server*
  424. 1. Save this code to a file.
  425. 2. Execute it with ":luafile %".
  426. 3. Note the port number.
  427. 4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): >
  428. local function create_server(host, port, on_connect)
  429. local server = vim.loop.new_tcp()
  430. server:bind(host, port)
  431. server:listen(128, function(err)
  432. assert(not err, err) -- Check for errors.
  433. local sock = vim.loop.new_tcp()
  434. server:accept(sock) -- Accept client connection.
  435. on_connect(sock) -- Start reading messages.
  436. end)
  437. return server
  438. end
  439. local server = create_server('0.0.0.0', 0, function(sock)
  440. sock:read_start(function(err, chunk)
  441. assert(not err, err) -- Check for errors.
  442. if chunk then
  443. sock:write(chunk) -- Echo received messages to the channel.
  444. else -- EOF (stream closed).
  445. sock:close() -- Always close handles to avoid leaks.
  446. end
  447. end)
  448. end)
  449. print('TCP echo-server listening on port: '..server:getsockname().port)
  450. <
  451. Multithreading *lua-loop-threading*
  452. Plugins can perform work in separate (os-level) threads using the threading
  453. APIs in luv, for instance `vim.loop.new_thread`. Note that every thread
  454. gets its own separate lua interpreter state, with no access to lua globals
  455. in the main thread. Neither can the state of the editor (buffers, windows,
  456. etc) be directly accessed from threads.
  457. A subset of the `vim.*` API is available in threads. This includes:
  458. - `vim.loop` with a separate event loop per thread.
  459. - `vim.mpack` and `vim.json` (useful for serializing messages between threads)
  460. - `require` in threads can use lua packages from the global |package.path|
  461. - `print()` and `vim.inspect`
  462. - `vim.diff`
  463. - most utility functions in `vim.*` for working with pure lua values
  464. like `vim.split`, `vim.tbl_*`, `vim.list_*`, and so on.
  465. - `vim.is_thread()` returns true from a non-main thread.
  466. ------------------------------------------------------------------------------
  467. VIM.HIGHLIGHT *lua-highlight*
  468. Nvim includes a function for highlighting a selection on yank (see for example
  469. https://github.com/machakann/vim-highlightedyank). To enable it, add
  470. >
  471. au TextYankPost * silent! lua vim.highlight.on_yank()
  472. <
  473. to your `init.vim`. You can customize the highlight group and the duration of
  474. the highlight via
  475. >
  476. au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150}
  477. <
  478. If you want to exclude visual selections from highlighting on yank, use
  479. >
  480. au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false}
  481. <
  482. vim.highlight.on_yank({opts}) *vim.highlight.on_yank()*
  483. Highlights the yanked text. The fields of the optional dict {opts}
  484. control the highlight:
  485. - {higroup} highlight group for yanked region (default |hl-IncSearch|)
  486. - {timeout} time in ms before highlight is cleared (default `150`)
  487. - {on_macro} highlight when executing macro (default `false`)
  488. - {on_visual} highlight when yanking visual selection (default `true`)
  489. - {event} event structure (default |v:event|)
  490. vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts})
  491. *vim.highlight.range()*
  492. Apply highlight group to range of text.
  493. Parameters: ~
  494. • {bufnr} buffer number
  495. • {ns} namespace for highlights
  496. • {hlgroup} highlight group name
  497. • {start} starting position (tuple {line,col})
  498. • {finish} finish position (tuple {line,col})
  499. • {opts} optional parameters:
  500. • `regtype`: type of range (characterwise, linewise,
  501. or blockwise, see |setreg()|), default `'v'`
  502. • `inclusive`: range includes end position,
  503. default `false`
  504. • `priority`: priority of highlight, default
  505. `vim.highlight.user` (see below)
  506. vim.highlight.priorities *vim.highlight.priorities*
  507. Table with default priorities used for highlighting:
  508. • `syntax`: `50`, used for standard syntax highlighting
  509. • `treesitter`: `100`, used for tree-sitter-based highlighting
  510. • `diagnostics`: `150`, used for code analysis such as diagnostics
  511. • `user`: `200`, used for user-triggered highlights such as LSP document
  512. symbols or `on_yank` autocommands
  513. ------------------------------------------------------------------------------
  514. VIM.REGEX *lua-regex*
  515. Vim regexes can be used directly from lua. Currently they only allow
  516. matching within a single line.
  517. vim.regex({re}) *vim.regex()*
  518. Parse the Vim regex {re} and return a regex object. Regexes are "magic"
  519. and case-sensitive by default, regardless of 'magic' and 'ignorecase'.
  520. They can be controlled with flags, see |/magic| and |/ignorecase|.
  521. Methods on the regex object:
  522. regex:match_str({str}) *regex:match_str()*
  523. Match the string against the regex. If the string should match the regex
  524. precisely, surround the regex with `^` and `$`. If the was a match, the
  525. byte indices for the beginning and end of the match is returned. When
  526. there is no match, `nil` is returned. As any integer is truth-y,
  527. `regex:match()` can be directly used as a condition in an if-statement.
  528. regex:match_line({bufnr}, {line_idx} [, {start}, {end}]) *regex:match_line()*
  529. Match line {line_idx} (zero-based) in buffer {bufnr}. If {start} and {end}
  530. are supplied, match only this byte index range. Otherwise see
  531. |regex:match_str()|. If {start} is used, then the returned byte indices
  532. will be relative {start}.
  533. ------------------------------------------------------------------------------
  534. VIM.DIFF *lua-diff*
  535. vim.diff({a}, {b}, {opts}) *vim.diff()*
  536. Run diff on strings {a} and {b}. Any indices returned by this function,
  537. either directly or via callback arguments, are 1-based.
  538. Examples: >
  539. vim.diff('a\n', 'b\nc\n')
  540. =>
  541. @@ -1 +1,2 @@
  542. -a
  543. +b
  544. +c
  545. vim.diff('a\n', 'b\nc\n', {result_type = 'indices'})
  546. =>
  547. {
  548. {1, 1, 1, 2}
  549. }
  550. <
  551. Parameters: ~
  552. • {a} First string to compare
  553. • {b} Second string to compare
  554. • {opts} Optional parameters:
  555. • `on_hunk` (callback):
  556. Invoked for each hunk in the diff. Return a negative number
  557. to cancel the callback for any remaining hunks.
  558. Args:
  559. • `start_a` (integer): Start line of hunk in {a}.
  560. • `count_a` (integer): Hunk size in {a}.
  561. • `start_b` (integer): Start line of hunk in {b}.
  562. • `count_b` (integer): Hunk size in {b}.
  563. • `result_type` (string): Form of the returned diff:
  564. • "unified": (default) String in unified format.
  565. • "indices": Array of hunk locations.
  566. Note: This option is ignored if `on_hunk` is used.
  567. • `algorithm` (string):
  568. Diff algorithm to use. Values:
  569. • "myers" the default algorithm
  570. • "minimal" spend extra time to generate the
  571. smallest possible diff
  572. • "patience" patience diff algorithm
  573. • "histogram" histogram diff algorithm
  574. • `ctxlen` (integer): Context length
  575. • `interhunkctxlen` (integer):
  576. Inter hunk context length
  577. • `ignore_whitespace` (boolean):
  578. Ignore whitespace
  579. • `ignore_whitespace_change` (boolean):
  580. Ignore whitespace change
  581. • `ignore_whitespace_change_at_eol` (boolean)
  582. Ignore whitespace change at end-of-line.
  583. • `ignore_cr_at_eol` (boolean)
  584. Ignore carriage return at end-of-line
  585. • `ignore_blank_lines` (boolean)
  586. Ignore blank lines
  587. • `indent_heuristic` (boolean):
  588. Use the indent heuristic for the internal
  589. diff library.
  590. Return: ~
  591. See {opts.result_type}. nil if {opts.on_hunk} is given.
  592. ------------------------------------------------------------------------------
  593. VIM.MPACK *lua-mpack*
  594. The *vim.mpack* module provides encoding and decoding of Lua objects to and
  595. from msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
  596. vim.mpack.encode({obj}) *vim.mpack.encode*
  597. Encodes (or "packs") Lua object {obj} as msgpack in a Lua string.
  598. vim.mpack.decode({str}) *vim.mpack.decode*
  599. Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object.
  600. ------------------------------------------------------------------------------
  601. VIM.SPELL *lua-spell*
  602. vim.spell.check({str}) *vim.spell.check()*
  603. Check {str} for spelling errors. Similar to the Vimscript function
  604. |spellbadword()|.
  605. Note: The behaviour of this function is dependent on: 'spelllang',
  606. 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to
  607. the buffer. Consider calling this with |nvim_buf_call()|.
  608. Example: >
  609. vim.spell.check("the quik brown fox")
  610. =>
  611. {
  612. {'quik', 'bad', 4}
  613. }
  614. <
  615. Parameters: ~
  616. • {str} String to spell check.
  617. Return: ~
  618. List of tuples with three items:
  619. - The badly spelled word.
  620. - The type of the spelling error:
  621. "bad" spelling mistake
  622. "rare" rare word
  623. "local" word only valid in another region
  624. "caps" word should start with Capital
  625. - The position in {str} where the word begins.
  626. ------------------------------------------------------------------------------
  627. VIM *lua-builtin*
  628. vim.api.{func}({...}) *vim.api*
  629. Invokes Nvim |API| function {func} with arguments {...}.
  630. Example: call the "nvim_get_current_line()" API function: >
  631. print(tostring(vim.api.nvim_get_current_line()))
  632. vim.version() *vim.version*
  633. Gets the version of the current Nvim build.
  634. vim.in_fast_event() *vim.in_fast_event()*
  635. Returns true if the code is executing as part of a "fast" event handler,
  636. where most of the API is disabled. These are low-level events (e.g.
  637. |lua-loop-callbacks|) which can be invoked whenever Nvim polls for input.
  638. When this is `false` most API functions are callable (but may be subject
  639. to other restrictions such as |textlock|).
  640. vim.NIL *vim.NIL*
  641. Special value representing NIL in |RPC| and |v:null| in Vimscript
  642. conversion, and similar cases. Lua `nil` cannot be used as part of a Lua
  643. table representing a Dictionary or Array, because it is treated as
  644. missing: `{"foo", nil}` is the same as `{"foo"}`.
  645. vim.empty_dict() *vim.empty_dict()*
  646. Creates a special empty table (marked with a metatable), which Nvim to an
  647. empty dictionary when translating Lua values to Vimscript or API types.
  648. Nvim by default converts an empty table `{}` without this metatable to an
  649. list/array.
  650. Note: If numeric keys are present in the table, Nvim ignores the metatable
  651. marker and converts the dict to a list/array anyway.
  652. vim.rpcnotify({channel}, {method} [, {args}...]) *vim.rpcnotify()*
  653. Sends {event} to {channel} via |RPC| and returns immediately. If {channel}
  654. is 0, the event is broadcast to all channels.
  655. This function also works in a fast callback |lua-loop-callbacks|.
  656. vim.rpcrequest({channel}, {method} [, {args}...]) *vim.rpcrequest()*
  657. Sends a request to {channel} to invoke {method} via |RPC| and blocks until
  658. a response is received.
  659. Note: NIL values as part of the return value is represented as |vim.NIL|
  660. special value
  661. vim.stricmp({a}, {b}) *vim.stricmp()*
  662. Compares strings case-insensitively. Returns 0, 1 or -1 if strings are
  663. equal, {a} is greater than {b} or {a} is lesser than {b}, respectively.
  664. vim.str_utfindex({str} [, {index}]) *vim.str_utfindex()*
  665. Convert byte index to UTF-32 and UTF-16 indices. If {index} is not
  666. supplied, the length of the string is used. All indices are zero-based.
  667. Returns two values: the UTF-32 and UTF-16 indices respectively.
  668. Embedded NUL bytes are treated as terminating the string. Invalid UTF-8
  669. bytes, and embedded surrogates are counted as one code point each. An
  670. {index} in the middle of a UTF-8 sequence is rounded upwards to the end of
  671. that sequence.
  672. vim.str_byteindex({str}, {index} [, {use_utf16}]) *vim.str_byteindex()*
  673. Convert UTF-32 or UTF-16 {index} to byte index. If {use_utf16} is not
  674. supplied, it defaults to false (use UTF-32). Returns the byte index.
  675. Invalid UTF-8 and NUL is treated like by |vim.str_byteindex()|.
  676. An {index} in the middle of a UTF-16 sequence is rounded upwards to
  677. the end of that sequence.
  678. vim.iconv({str}, {from}, {to}[, {opts}]) *vim.iconv()*
  679. The result is a String, which is the text {str} converted from
  680. encoding {from} to encoding {to}. When the conversion fails `nil` is
  681. returned. When some characters could not be converted they
  682. are replaced with "?".
  683. The encoding names are whatever the iconv() library function
  684. can accept, see ":Man 3 iconv".
  685. Parameters: ~
  686. • {str} (string) Text to convert
  687. • {from} (string) Encoding of {str}
  688. • {to} (string) Target encoding
  689. Returns: ~
  690. Converted string if conversion succeeds, `nil` otherwise.
  691. vim.schedule({callback}) *vim.schedule()*
  692. Schedules {callback} to be invoked soon by the main event-loop. Useful
  693. to avoid |textlock| or other temporary restrictions.
  694. vim.defer_fn({fn}, {timeout}) *vim.defer_fn*
  695. Defers calling {fn} until {timeout} ms passes. Use to do a one-shot timer
  696. that calls {fn}.
  697. Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are
  698. safe to call.
  699. Parameters: ~
  700. • {fn} Callback to call once {timeout} expires
  701. • {timeout} Time in ms to wait before calling {fn}
  702. Returns: ~
  703. |vim.loop|.new_timer() object
  704. vim.wait({time} [, {callback}, {interval}, {fast_only}]) *vim.wait()*
  705. Wait for {time} in milliseconds until {callback} returns `true`.
  706. Executes {callback} immediately and at approximately {interval}
  707. milliseconds (default 200). Nvim still processes other events during
  708. this time.
  709. Parameters: ~
  710. • {time} Number of milliseconds to wait
  711. • {callback} Optional callback. Waits until {callback} returns true
  712. • {interval} (Approximate) number of milliseconds to wait between polls
  713. • {fast_only} If true, only |api-fast| events will be processed.
  714. If called from while in an |api-fast| event, will
  715. automatically be set to `true`.
  716. Returns: ~
  717. If {callback} returns `true` during the {time}:
  718. `true, nil`
  719. If {callback} never returns `true` during the {time}:
  720. `false, -1`
  721. If {callback} is interrupted during the {time}:
  722. `false, -2`
  723. If {callback} errors, the error is raised.
  724. Examples: >
  725. ---
  726. -- Wait for 100 ms, allowing other events to process
  727. vim.wait(100, function() end)
  728. ---
  729. -- Wait for 100 ms or until global variable set.
  730. vim.wait(100, function() return vim.g.waiting_for_var end)
  731. ---
  732. -- Wait for 1 second or until global variable set, checking every ~500 ms
  733. vim.wait(1000, function() return vim.g.waiting_for_var end, 500)
  734. ---
  735. -- Schedule a function to set a value in 100ms
  736. vim.defer_fn(function() vim.g.timer_result = true end, 100)
  737. -- Would wait ten seconds if results blocked. Actually only waits 100 ms
  738. if vim.wait(10000, function() return vim.g.timer_result end) then
  739. print('Only waiting a little bit of time!')
  740. end
  741. <
  742. vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()*
  743. Attach to ui events, similar to |nvim_ui_attach()| but receive events
  744. as lua callback. Can be used to implement screen elements like
  745. popupmenu or message handling in lua.
  746. {options} should be a dictionary-like table, where `ext_...` options should
  747. be set to true to receive events for the respective external element.
  748. {callback} receives event name plus additional parameters. See |ui-popupmenu|
  749. and the sections below for event format for respective events.
  750. WARNING: This api is considered experimental. Usability will vary for
  751. different screen elements. In particular `ext_messages` behavior is subject
  752. to further changes and usability improvements. This is expected to be
  753. used to handle messages when setting 'cmdheight' to zero (which is
  754. likewise experimental).
  755. Example (stub for a |ui-popupmenu| implementation): >
  756. ns = vim.api.nvim_create_namespace('my_fancy_pum')
  757. vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...)
  758. if event == "popupmenu_show" then
  759. local items, selected, row, col, grid = ...
  760. print("display pum ", #items)
  761. elseif event == "popupmenu_select" then
  762. local selected = ...
  763. print("selected", selected)
  764. elseif event == "popupmenu_hide" then
  765. print("FIN")
  766. end
  767. end)
  768. vim.ui_detach({ns}) *vim.ui_detach()*
  769. Detach a callback previously attached with |vim.ui_attach()| for the
  770. given namespace {ns}.
  771. vim.type_idx *vim.type_idx*
  772. Type index for use in |lua-special-tbl|. Specifying one of the values from
  773. |vim.types| allows typing the empty table (it is unclear whether empty Lua
  774. table represents empty list or empty array) and forcing integral numbers
  775. to be |Float|. See |lua-special-tbl| for more details.
  776. vim.val_idx *vim.val_idx*
  777. Value index for tables representing |Float|s. A table representing
  778. floating-point value 1.0 looks like this: >
  779. {
  780. [vim.type_idx] = vim.types.float,
  781. [vim.val_idx] = 1.0,
  782. }
  783. < See also |vim.type_idx| and |lua-special-tbl|.
  784. vim.types *vim.types*
  785. Table with possible values for |vim.type_idx|. Contains two sets of
  786. key-value pairs: first maps possible values for |vim.type_idx| to
  787. human-readable strings, second maps human-readable type names to values
  788. for |vim.type_idx|. Currently contains pairs for `float`, `array` and
  789. `dictionary` types.
  790. Note: One must expect that values corresponding to `vim.types.float`,
  791. `vim.types.array` and `vim.types.dictionary` fall under only two following
  792. assumptions:
  793. 1. Value may serve both as a key and as a value in a table. Given the
  794. properties of Lua tables this basically means “value is not `nil`”.
  795. 2. For each value in `vim.types` table `vim.types[vim.types[value]]` is the
  796. same as `value`.
  797. No other restrictions are put on types, and it is not guaranteed that
  798. values corresponding to `vim.types.float`, `vim.types.array` and
  799. `vim.types.dictionary` will not change or that `vim.types` table will only
  800. contain values for these three types.
  801. *log_levels* *vim.log.levels*
  802. Log levels are one of the values defined in `vim.log.levels`:
  803. vim.log.levels.DEBUG
  804. vim.log.levels.ERROR
  805. vim.log.levels.INFO
  806. vim.log.levels.TRACE
  807. vim.log.levels.WARN
  808. vim.log.levels.OFF
  809. ------------------------------------------------------------------------------
  810. LUA-VIMSCRIPT BRIDGE *lua-vimscript*
  811. Nvim Lua provides an interface to Vimscript variables and functions, and
  812. editor commands and options.
  813. See also https://github.com/nanotee/nvim-lua-guide.
  814. vim.call({func}, {...}) *vim.call()*
  815. Invokes |vim-function| or |user-function| {func} with arguments {...}.
  816. See also |vim.fn|.
  817. Equivalent to: >
  818. vim.fn[func]({...})
  819. vim.cmd({command})
  820. See |vim.cmd()|.
  821. vim.fn.{func}({...}) *vim.fn*
  822. Invokes |vim-function| or |user-function| {func} with arguments {...}.
  823. To call autoload functions, use the syntax: >
  824. vim.fn['some#function']({...})
  825. <
  826. Unlike vim.api.|nvim_call_function()| this converts directly between Vim
  827. objects and Lua objects. If the Vim function returns a float, it will be
  828. represented directly as a Lua number. Empty lists and dictionaries both
  829. are represented by an empty table.
  830. Note: |v:null| values as part of the return value is represented as
  831. |vim.NIL| special value
  832. Note: vim.fn keys are generated lazily, thus `pairs(vim.fn)` only
  833. enumerates functions that were called at least once.
  834. Note: The majority of functions cannot run in |api-fast| callbacks with some
  835. undocumented exceptions which are allowed.
  836. *lua-vim-variables*
  837. The Vim editor global dictionaries |g:| |w:| |b:| |t:| |v:| can be accessed
  838. from Lua conveniently and idiomatically by referencing the `vim.*` Lua tables
  839. described below. In this way you can easily read and modify global Vimscript
  840. variables from Lua.
  841. Example: >
  842. vim.g.foo = 5 -- Set the g:foo Vimscript variable.
  843. print(vim.g.foo) -- Get and print the g:foo Vimscript variable.
  844. vim.g.foo = nil -- Delete (:unlet) the Vimscript variable.
  845. vim.b[2].foo = 6 -- Set b:foo for buffer 2
  846. <
  847. Note that setting dictionary fields directly will not write them back into
  848. Nvim. This is because the index into the namespace simply returns a copy.
  849. Instead the whole dictionary must be written as one. This can be achieved by
  850. creating a short-lived temporary.
  851. Example: >
  852. vim.g.my_dict.field1 = 'value' -- Does not work
  853. local my_dict = vim.g.my_dict --
  854. my_dict.field1 = 'value' -- Instead do
  855. vim.g.my_dict = my_dict --
  856. vim.g *vim.g*
  857. Global (|g:|) editor variables.
  858. Key with no value returns `nil`.
  859. vim.b *vim.b*
  860. Buffer-scoped (|b:|) variables for the current buffer.
  861. Invalid or unset key returns `nil`. Can be indexed with
  862. an integer to access variables for a specific buffer.
  863. vim.w *vim.w*
  864. Window-scoped (|w:|) variables for the current window.
  865. Invalid or unset key returns `nil`. Can be indexed with
  866. an integer to access variables for a specific window.
  867. vim.t *vim.t*
  868. Tabpage-scoped (|t:|) variables for the current tabpage.
  869. Invalid or unset key returns `nil`. Can be indexed with
  870. an integer to access variables for a specific tabpage.
  871. vim.v *vim.v*
  872. |v:| variables.
  873. Invalid or unset key returns `nil`.
  874. vim.env *vim.env*
  875. Environment variables defined in the editor session.
  876. See |expand-env| and |:let-environment| for the Vimscript behavior.
  877. Invalid or unset key returns `nil`.
  878. Example: >
  879. vim.env.FOO = 'bar'
  880. print(vim.env.TERM)
  881. <
  882. *lua-options*
  883. *lua-vim-options*
  884. *lua-vim-set*
  885. *lua-vim-setlocal*
  886. Vim options can be accessed through |vim.o|, which behaves like Vimscript
  887. |:set|.
  888. Examples: ~
  889. To set a boolean toggle:
  890. Vimscript: `set number`
  891. Lua: `vim.o.number = true`
  892. To set a string value:
  893. Vimscript: `set wildignore=*.o,*.a,__pycache__`
  894. Lua: `vim.o.wildignore = '*.o,*.a,__pycache__'`
  895. Similarly, there is |vim.bo| and |vim.wo| for setting buffer-scoped and
  896. window-scoped options. Note that this must NOT be confused with
  897. |local-options| and |:setlocal|. There is also |vim.go| that only accesses the
  898. global value of a |global-local| option, see |:setglobal|.
  899. vim.o *vim.o*
  900. Get or set |options|. Like `:set`. Invalid key is an error.
  901. Note: this works on both buffer-scoped and window-scoped options using the
  902. current buffer and window.
  903. Example: >
  904. vim.o.cmdheight = 4
  905. print(vim.o.columns)
  906. print(vim.o.foo) -- error: invalid key
  907. <
  908. vim.go *vim.go*
  909. Get or set global |options|. Like `:setglobal`. Invalid key is
  910. an error.
  911. Note: this is different from |vim.o| because this accesses the global
  912. option value and thus is mostly useful for use with |global-local|
  913. options.
  914. Example: >
  915. vim.go.cmdheight = 4
  916. print(vim.go.columns)
  917. print(vim.go.bar) -- error: invalid key
  918. <
  919. vim.bo[{bufnr}] *vim.bo*
  920. Get or set buffer-scoped |options| for the buffer with number {bufnr}.
  921. Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current
  922. buffer is used. Invalid {bufnr} or key is an error.
  923. Note: this is equivalent to both `:set` and `:setlocal`.
  924. Example: >
  925. local bufnr = vim.api.nvim_get_current_buf()
  926. vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
  927. print(vim.bo.comments)
  928. print(vim.bo.baz) -- error: invalid key
  929. <
  930. vim.wo[{winid}] *vim.wo*
  931. Get or set window-scoped |options| for the window with handle {winid}.
  932. Like `:set`. If [{winid}] is omitted then the current window is used.
  933. Invalid {winid} or key is an error.
  934. Note: this does not access |local-options| (`:setlocal`) instead use: >
  935. nvim_get_option_value(OPTION, { scope = 'local', win = winid })
  936. nvim_set_option_value(OPTION, VALUE, { scope = 'local', win = winid }
  937. <
  938. Example: >
  939. local winid = vim.api.nvim_get_current_win()
  940. vim.wo[winid].number = true -- same as vim.wo.number = true
  941. print(vim.wo.foldmarker)
  942. print(vim.wo.quux) -- error: invalid key
  943. <
  944. *vim.opt_local*
  945. *vim.opt_global*
  946. *vim.opt*
  947. A special interface |vim.opt| exists for conveniently interacting with list-
  948. and map-style option from Lua: It allows accessing them as Lua tables and
  949. offers object-oriented method for adding and removing entries.
  950. Examples: ~
  951. The following methods of setting a list-style option are equivalent:
  952. In Vimscript:
  953. `set wildignore=*.o,*.a,__pycache__`
  954. In Lua using `vim.o`:
  955. `vim.o.wildignore = '*.o,*.a,__pycache__'`
  956. In Lua using `vim.opt`:
  957. `vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }`
  958. To replicate the behavior of |:set+=|, use: >
  959. vim.opt.wildignore:append { "*.pyc", "node_modules" }
  960. <
  961. To replicate the behavior of |:set^=|, use: >
  962. vim.opt.wildignore:prepend { "new_first_value" }
  963. <
  964. To replicate the behavior of |:set-=|, use: >
  965. vim.opt.wildignore:remove { "node_modules" }
  966. <
  967. The following methods of setting a map-style option are equivalent:
  968. In Vimscript:
  969. `set listchars=space:_,tab:>~`
  970. In Lua using `vim.o`:
  971. `vim.o.listchars = 'space:_,tab:>~'`
  972. In Lua using `vim.opt`:
  973. `vim.opt.listchars = { space = '_', tab = '>~' }`
  974. Note that |vim.opt| returns an `Option` object, not the value of the option,
  975. which is accessed through |vim.opt:get()|:
  976. Examples: ~
  977. The following methods of getting a list-style option are equivalent:
  978. In Vimscript:
  979. `echo wildignore`
  980. In Lua using `vim.o`:
  981. `print(vim.o.wildignore)`
  982. In Lua using `vim.opt`:
  983. `vim.pretty_print(vim.opt.wildignore:get())`
  984. In any of the above examples, to replicate the behavior |:setlocal|, use
  985. `vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use
  986. `vim.opt_global`.
  987. *vim.opt:get()*
  988. Option:get()
  989. Returns a lua-representation of the option. Boolean, number and string
  990. values will be returned in exactly the same fashion.
  991. For values that are comma-separated lists, an array will be returned with
  992. the values as entries in the array: >
  993. vim.cmd [[set wildignore=*.pyc,*.o]]
  994. vim.pretty_print(vim.opt.wildignore:get())
  995. -- { "*.pyc", "*.o", }
  996. for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
  997. print("Will ignore:", ignore_pattern)
  998. end
  999. -- Will ignore: *.pyc
  1000. -- Will ignore: *.o
  1001. <
  1002. For values that are comma-separated maps, a table will be returned with
  1003. the names as keys and the values as entries: >
  1004. vim.cmd [[set listchars=space:_,tab:>~]]
  1005. vim.pretty_print(vim.opt.listchars:get())
  1006. -- { space = "_", tab = ">~", }
  1007. for char, representation in pairs(vim.opt.listchars:get()) do
  1008. print(char, "=>", representation)
  1009. end
  1010. <
  1011. For values that are lists of flags, a set will be returned with the flags
  1012. as keys and `true` as entries. >
  1013. vim.cmd [[set formatoptions=njtcroql]]
  1014. vim.pretty_print(vim.opt.formatoptions:get())
  1015. -- { n = true, j = true, c = true, ... }
  1016. local format_opts = vim.opt.formatoptions:get()
  1017. if format_opts.j then
  1018. print("J is enabled!")
  1019. end
  1020. <
  1021. *vim.opt:append()*
  1022. Option:append(value)
  1023. Append a value to string-style options. See |:set+=|
  1024. These are equivalent:
  1025. `vim.opt.formatoptions:append('j')`
  1026. `vim.opt.formatoptions = vim.opt.formatoptions + 'j'`
  1027. *vim.opt:prepend()*
  1028. Option:prepend(value)
  1029. Prepend a value to string-style options. See |:set^=|
  1030. These are equivalent:
  1031. `vim.opt.wildignore:prepend('*.o')`
  1032. `vim.opt.wildignore = vim.opt.wildignore ^ '*.o'`
  1033. *vim.opt:remove()*
  1034. Option:remove(value)
  1035. Remove a value from string-style options. See |:set-=|
  1036. These are equivalent:
  1037. `vim.opt.wildignore:remove('*.pyc')`
  1038. `vim.opt.wildignore = vim.opt.wildignore - '*.pyc'`
  1039. ==============================================================================
  1040. Lua module: vim *lua-vim*
  1041. cmd({command}) *vim.cmd()*
  1042. Execute Vim script commands.
  1043. Note that `vim.cmd` can be indexed with a command name to return a
  1044. callable function to the command.
  1045. Example: >
  1046. vim.cmd('echo 42')
  1047. vim.cmd([[
  1048. augroup My_group
  1049. autocmd!
  1050. autocmd FileType c setlocal cindent
  1051. augroup END
  1052. ]])
  1053. -- Ex command :echo "foo"
  1054. -- Note string literals need to be double quoted.
  1055. vim.cmd('echo "foo"')
  1056. vim.cmd { cmd = 'echo', args = { '"foo"' } }
  1057. vim.cmd.echo({ args = { '"foo"' } })
  1058. vim.cmd.echo('"foo"')
  1059. -- Ex command :write! myfile.txt
  1060. vim.cmd('write! myfile.txt')
  1061. vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true }
  1062. vim.cmd.write { args = { "myfile.txt" }, bang = true }
  1063. vim.cmd.write { "myfile.txt", bang = true }
  1064. -- Ex command :colorscheme blue
  1065. vim.cmd('colorscheme blue')
  1066. vim.cmd.colorscheme('blue')
  1067. <
  1068. Parameters: ~
  1069. • {command} string|table Command(s) to execute. If a string, executes
  1070. multiple lines of Vim script at once. In this case, it is
  1071. an alias to |nvim_exec()|, where `output` is set to false.
  1072. Thus it works identical to |:source|. If a table, executes
  1073. a single command. In this case, it is an alias to
  1074. |nvim_cmd()| where `opts` is empty.
  1075. See also: ~
  1076. |ex-cmd-index|
  1077. *vim.connection_failure_errmsg()*
  1078. connection_failure_errmsg({consequence})
  1079. TODO: Documentation
  1080. defer_fn({fn}, {timeout}) *vim.defer_fn()*
  1081. Defers calling `fn` until `timeout` ms passes.
  1082. Use to do a one-shot timer that calls `fn` Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions
  1083. are safe to call.
  1084. Parameters: ~
  1085. • {fn} Callback to call once `timeout` expires
  1086. • {timeout} Number of milliseconds to wait before calling `fn`
  1087. Return: ~
  1088. timer luv timer object
  1089. *vim.deprecate()*
  1090. deprecate({name}, {alternative}, {version}, {plugin}, {backtrace})
  1091. Display a deprecation notification to the user.
  1092. Parameters: ~
  1093. • {name} string Deprecated function.
  1094. • {alternative} (string|nil) Preferred alternative function.
  1095. • {version} string Version in which the deprecated function will be
  1096. removed.
  1097. • {plugin} string|nil Plugin name that the function will be
  1098. removed from. Defaults to "Nvim".
  1099. • {backtrace} boolean|nil Prints backtrace. Defaults to true.
  1100. inspect({object}, {options}) *vim.inspect()*
  1101. Gets a human-readable representation of the given object.
  1102. See also: ~
  1103. https://github.com/kikito/inspect.lua
  1104. https://github.com/mpeterv/vinspect
  1105. notify({msg}, {level}, {opts}) *vim.notify()*
  1106. Display a notification to the user.
  1107. This function can be overridden by plugins to display notifications using
  1108. a custom provider (such as the system notification provider). By default,
  1109. writes to |:messages|.
  1110. Parameters: ~
  1111. • {msg} (string) Content of the notification to show to the user.
  1112. • {level} (number|nil) One of the values from |vim.log.levels|.
  1113. • {opts} (table|nil) Optional parameters. Unused by default.
  1114. notify_once({msg}, {level}, {opts}) *vim.notify_once()*
  1115. Display a notification only one time.
  1116. Like |vim.notify()|, but subsequent calls with the same message will not
  1117. display a notification.
  1118. Parameters: ~
  1119. • {msg} (string) Content of the notification to show to the user.
  1120. • {level} (number|nil) One of the values from |vim.log.levels|.
  1121. • {opts} (table|nil) Optional parameters. Unused by default.
  1122. Return: ~
  1123. (boolean) true if message was displayed, else false
  1124. on_key({fn}, {ns_id}) *vim.on_key()*
  1125. Adds Lua function {fn} with namespace id {ns_id} as a listener to every,
  1126. yes every, input key.
  1127. The Nvim command-line option |-w| is related but does not support
  1128. callbacks and cannot be toggled dynamically.
  1129. Note:
  1130. {fn} will not be cleared by |nvim_buf_clear_namespace()|
  1131. Note:
  1132. {fn} will receive the keys after mappings have been evaluated
  1133. Parameters: ~
  1134. • {fn} function: Callback function. It should take one string
  1135. argument. On each key press, Nvim passes the key char to
  1136. fn(). |i_CTRL-V| If {fn} is nil, it removes the callback for
  1137. the associated {ns_id}
  1138. • {ns_id} number? Namespace ID. If nil or 0, generates and returns a
  1139. new |nvim_create_namespace()| id.
  1140. Return: ~
  1141. (number) Namespace id associated with {fn}. Or count of all callbacks
  1142. if on_key() is called without arguments.
  1143. Note:
  1144. {fn} will be removed if an error occurs while calling.
  1145. paste({lines}, {phase}) *vim.paste()*
  1146. Paste handler, invoked by |nvim_paste()| when a conforming UI (such as the
  1147. |TUI|) pastes text into the editor.
  1148. Example: To remove ANSI color codes when pasting: >
  1149. vim.paste = (function(overridden)
  1150. return function(lines, phase)
  1151. for i,line in ipairs(lines) do
  1152. -- Scrub ANSI color codes from paste input.
  1153. lines[i] = line:gsub('\27%[[0-9;mK]+', '')
  1154. end
  1155. overridden(lines, phase)
  1156. end
  1157. end)(vim.paste)
  1158. <
  1159. Parameters: ~
  1160. • {lines} |readfile()|-style list of lines to paste. |channel-lines|
  1161. • {phase} -1: "non-streaming" paste: the call contains all lines. If
  1162. paste is "streamed", `phase` indicates the stream state:
  1163. • 1: starts the paste (exactly once)
  1164. • 2: continues the paste (zero or more times)
  1165. • 3: ends the paste (exactly once)
  1166. Return: ~
  1167. false if client should cancel the paste.
  1168. See also: ~
  1169. |paste|
  1170. pretty_print({...}) *vim.pretty_print()*
  1171. Prints given arguments in human-readable format. Example: >
  1172. -- Print highlight group Normal and store it's contents in a variable.
  1173. local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true))
  1174. <
  1175. Return: ~
  1176. given arguments.
  1177. See also: ~
  1178. |vim.inspect()|
  1179. region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) *vim.region()*
  1180. Get a table of lines with start, end columns for a region marked by two
  1181. points
  1182. Parameters: ~
  1183. • {bufnr} (number) of buffer
  1184. • {pos1} (line, column) tuple marking beginning of region
  1185. • {pos2} (line, column) tuple marking end of region
  1186. • {regtype} type of selection, see |setreg()|
  1187. • {inclusive} (boolean) indicating whether the selection is
  1188. end-inclusive
  1189. Return: ~
  1190. region lua table of the form {linenr = {startcol,endcol}}
  1191. schedule_wrap({cb}) *vim.schedule_wrap()*
  1192. Defers callback `cb` until the Nvim API is safe to call.
  1193. See also: ~
  1194. |lua-loop-callbacks|
  1195. |vim.schedule()|
  1196. |vim.in_fast_event()|
  1197. deep_equal({a}, {b}) *vim.deep_equal()*
  1198. Deep compare values for equality
  1199. Tables are compared recursively unless they both provide the `eq` metamethod. All other types are compared using the equality `==` operator.
  1200. Parameters: ~
  1201. • {a} any First value
  1202. • {b} any Second value
  1203. Return: ~
  1204. (boolean) `true` if values are equals, else `false`
  1205. deepcopy({orig}) *vim.deepcopy()*
  1206. Returns a deep copy of the given object. Non-table objects are copied as
  1207. in a typical Lua assignment, whereas table objects are copied recursively.
  1208. Functions are naively copied, so functions in the copied table point to
  1209. the same functions as those in the input table. Userdata and threads are
  1210. not copied and will throw an error.
  1211. Parameters: ~
  1212. • {orig} (table) Table to copy
  1213. Return: ~
  1214. (table) Table of copied keys and (nested) values.
  1215. defaulttable({create}) *vim.defaulttable()*
  1216. Creates a table whose members are automatically created when accessed, if
  1217. they don't already exist.
  1218. They mimic defaultdict in python.
  1219. If {create} is `nil`, this will create a defaulttable whose constructor
  1220. function is this function, effectively allowing to create nested tables on
  1221. the fly:
  1222. >
  1223. local a = vim.defaulttable()
  1224. a.b.c = 1
  1225. <
  1226. Parameters: ~
  1227. • {create} (function|nil) The function called to create a missing
  1228. value.
  1229. Return: ~
  1230. (table) Empty table with metamethod
  1231. endswith({s}, {suffix}) *vim.endswith()*
  1232. Tests if `s` ends with `suffix`.
  1233. Parameters: ~
  1234. • {s} (string) String
  1235. • {suffix} (string) Suffix to match
  1236. Return: ~
  1237. (boolean) `true` if `suffix` is a suffix of `s`
  1238. gsplit({s}, {sep}, {plain}) *vim.gsplit()*
  1239. Splits a string at each instance of a separator.
  1240. Parameters: ~
  1241. • {s} (string) String to split
  1242. • {sep} (string) Separator or pattern
  1243. • {plain} (boolean) If `true` use `sep` literally (passed to
  1244. string.find)
  1245. Return: ~
  1246. (function) Iterator over the split components
  1247. See also: ~
  1248. |vim.split()|
  1249. https://www.lua.org/pil/20.2.html
  1250. http://lua-users.org/wiki/StringLibraryTutorial
  1251. is_callable({f}) *vim.is_callable()*
  1252. Returns true if object `f` can be called as a function.
  1253. Parameters: ~
  1254. • {f} any Any object
  1255. Return: ~
  1256. (boolean) `true` if `f` is callable, else `false`
  1257. list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()*
  1258. Extends a list-like table with the values of another list-like table.
  1259. NOTE: This mutates dst!
  1260. Parameters: ~
  1261. • {dst} (table) List which will be modified and appended to
  1262. • {src} (table) List from which values will be inserted
  1263. • {start} (number) Start index on src. Defaults to 1
  1264. • {finish} (number) Final index on src. Defaults to `#src`
  1265. Return: ~
  1266. (table) dst
  1267. See also: ~
  1268. |vim.tbl_extend()|
  1269. list_slice({list}, {start}, {finish}) *vim.list_slice()*
  1270. Creates a copy of a table containing only elements from start to end
  1271. (inclusive)
  1272. Parameters: ~
  1273. • {list} (table) Table
  1274. • {start} (number) Start range of slice
  1275. • {finish} (number) End range of slice
  1276. Return: ~
  1277. (table) Copy of table sliced from start to finish (inclusive)
  1278. pesc({s}) *vim.pesc()*
  1279. Escapes magic chars in |lua-patterns|.
  1280. Parameters: ~
  1281. • {s} (string) String to escape
  1282. Return: ~
  1283. (string) %-escaped pattern string
  1284. See also: ~
  1285. https://github.com/rxi/lume
  1286. split({s}, {sep}, {kwargs}) *vim.split()*
  1287. Splits a string at each instance of a separator.
  1288. Examples: >
  1289. split(":aa::b:", ":") => {'','aa','','b',''}
  1290. split("axaby", "ab?") => {'','x','y'}
  1291. split("x*yz*o", "*", {plain=true}) => {'x','yz','o'}
  1292. split("|x|y|z|", "|", {trimempty=true}) => {'x', 'y', 'z'}
  1293. <
  1294. Parameters: ~
  1295. • {s} (string) String to split
  1296. • {sep} (string) Separator or pattern
  1297. • {kwargs} (table) Keyword arguments:
  1298. • plain: (boolean) If `true` use `sep` literally (passed to
  1299. string.find)
  1300. • trimempty: (boolean) If `true` remove empty items from the
  1301. front and back of the list
  1302. Return: ~
  1303. (table) List of split components
  1304. See also: ~
  1305. |vim.gsplit()|
  1306. startswith({s}, {prefix}) *vim.startswith()*
  1307. Tests if `s` starts with `prefix`.
  1308. Parameters: ~
  1309. • {s} (string) String
  1310. • {prefix} (string) Prefix to match
  1311. Return: ~
  1312. (boolean) `true` if `prefix` is a prefix of `s`
  1313. tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()*
  1314. Add the reverse lookup values to an existing table. For example:
  1315. `tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A = 1 }`
  1316. Note that this modifies the input.
  1317. Parameters: ~
  1318. • {o} (table) Table to add the reverse to
  1319. Return: ~
  1320. (table) o
  1321. tbl_contains({t}, {value}) *vim.tbl_contains()*
  1322. Checks if a list-like (vector) table contains `value`.
  1323. Parameters: ~
  1324. • {t} (table) Table to check
  1325. • {value} any Value to compare
  1326. Return: ~
  1327. (boolean) `true` if `t` contains `value`
  1328. tbl_count({t}) *vim.tbl_count()*
  1329. Counts the number of non-nil values in table `t`.
  1330. >
  1331. vim.tbl_count({ a=1, b=2 }) => 2
  1332. vim.tbl_count({ 1, 2 }) => 2
  1333. <
  1334. Parameters: ~
  1335. • {t} (table) Table
  1336. Return: ~
  1337. (number) Number of non-nil values in table
  1338. See also: ~
  1339. https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
  1340. tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()*
  1341. Merges recursively two or more map-like tables.
  1342. Parameters: ~
  1343. • {behavior} (string) Decides what to do if a key is found in more than
  1344. one map:
  1345. • "error": raise an error
  1346. • "keep": use value from the leftmost map
  1347. • "force": use value from the rightmost map
  1348. • {...} (table) Two or more map-like tables
  1349. Return: ~
  1350. (table) Merged table
  1351. See also: ~
  1352. |vim.tbl_extend()|
  1353. tbl_extend({behavior}, {...}) *vim.tbl_extend()*
  1354. Merges two or more map-like tables.
  1355. Parameters: ~
  1356. • {behavior} (string) Decides what to do if a key is found in more than
  1357. one map:
  1358. • "error": raise an error
  1359. • "keep": use value from the leftmost map
  1360. • "force": use value from the rightmost map
  1361. • {...} (table) Two or more map-like tables
  1362. Return: ~
  1363. (table) Merged table
  1364. See also: ~
  1365. |extend()|
  1366. tbl_filter({func}, {t}) *vim.tbl_filter()*
  1367. Filter a table using a predicate function
  1368. Parameters: ~
  1369. • {func} function|table Function or callable table
  1370. • {t} (table) Table
  1371. Return: ~
  1372. (table) Table of filtered values
  1373. tbl_flatten({t}) *vim.tbl_flatten()*
  1374. Creates a copy of a list-like table such that any nested tables are
  1375. "unrolled" and appended to the result.
  1376. Parameters: ~
  1377. • {t} (table) List-like table
  1378. Return: ~
  1379. (table) Flattened copy of the given list-like table
  1380. See also: ~
  1381. From https://github.com/premake/premake-core/blob/master/src/base/table.lua
  1382. tbl_get({o}, {...}) *vim.tbl_get()*
  1383. Index into a table (first argument) via string keys passed as subsequent
  1384. arguments. Return `nil` if the key does not exist.
  1385. Examples: >
  1386. vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
  1387. vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
  1388. <
  1389. Parameters: ~
  1390. • {o} (table) Table to index
  1391. • {...} (string) Optional strings (0 or more, variadic) via which to
  1392. index the table
  1393. Return: ~
  1394. any Nested value indexed by key (if it exists), else nil
  1395. tbl_isempty({t}) *vim.tbl_isempty()*
  1396. Checks if a table is empty.
  1397. Parameters: ~
  1398. • {t} (table) Table to check
  1399. Return: ~
  1400. (boolean) `true` if `t` is empty
  1401. See also: ~
  1402. https://github.com/premake/premake-core/blob/master/src/base/table.lua
  1403. tbl_islist({t}) *vim.tbl_islist()*
  1404. Tests if a Lua table can be treated as an array.
  1405. Empty table `{}` is assumed to be an array, unless it was created by
  1406. |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result,
  1407. for example from |rpcrequest()| or |vim.fn|.
  1408. Parameters: ~
  1409. • {t} (table) Table
  1410. Return: ~
  1411. (boolean) `true` if array-like table, else `false`
  1412. tbl_keys({t}) *vim.tbl_keys()*
  1413. Return a list of all keys used in a table. However, the order of the
  1414. return table of keys is not guaranteed.
  1415. Parameters: ~
  1416. • {t} (table) Table
  1417. Return: ~
  1418. (table) List of keys
  1419. See also: ~
  1420. From https://github.com/premake/premake-core/blob/master/src/base/table.lua
  1421. tbl_map({func}, {t}) *vim.tbl_map()*
  1422. Apply a function to all values of a table.
  1423. Parameters: ~
  1424. • {func} function|table Function or callable table
  1425. • {t} (table) Table
  1426. Return: ~
  1427. (table) Table of transformed values
  1428. tbl_values({t}) *vim.tbl_values()*
  1429. Return a list of all values used in a table. However, the order of the
  1430. return table of values is not guaranteed.
  1431. Parameters: ~
  1432. • {t} (table) Table
  1433. Return: ~
  1434. (table) List of values
  1435. trim({s}) *vim.trim()*
  1436. Trim whitespace (Lua pattern "%s") from both sides of a string.
  1437. Parameters: ~
  1438. • {s} (string) String to trim
  1439. Return: ~
  1440. (string) String with whitespace removed from its beginning and end
  1441. See also: ~
  1442. https://www.lua.org/pil/20.2.html
  1443. validate({opt}) *vim.validate()*
  1444. Validates a parameter specification (types and values).
  1445. Usage example: >
  1446. function user.new(name, age, hobbies)
  1447. vim.validate{
  1448. name={name, 'string'},
  1449. age={age, 'number'},
  1450. hobbies={hobbies, 'table'},
  1451. }
  1452. ...
  1453. end
  1454. <
  1455. Examples with explicit argument values (can be run directly): >
  1456. vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
  1457. => NOP (success)
  1458. vim.validate{arg1={1, 'table'}}
  1459. => error('arg1: expected table, got number')
  1460. vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}}
  1461. => error('arg1: expected even number, got 3')
  1462. <
  1463. If multiple types are valid they can be given as a list. >
  1464. vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
  1465. => NOP (success)
  1466. vim.validate{arg1={1, {'string', table'}}}
  1467. => error('arg1: expected string|table, got number')
  1468. <
  1469. Parameters: ~
  1470. • {opt} (table) Names of parameters to validate. Each key is a
  1471. parameter name; each value is a tuple in one of these forms:
  1472. 1. (arg_value, type_name, optional)
  1473. • arg_value: argument value
  1474. • type_name: string|table type name, one of: ("table", "t",
  1475. "string", "s", "number", "n", "boolean", "b", "function",
  1476. "f", "nil", "thread", "userdata") or list of them.
  1477. • optional: (optional) boolean, if true, `nil` is valid
  1478. 2. (arg_value, fn, msg)
  1479. • arg_value: argument value
  1480. • fn: any function accepting one argument, returns true if
  1481. and only if the argument is valid. Can optionally return
  1482. an additional informative error message as the second
  1483. returned value.
  1484. • msg: (optional) error string if validation fails
  1485. ==============================================================================
  1486. Lua module: uri *lua-uri*
  1487. uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()*
  1488. Get a URI from a bufnr
  1489. Parameters: ~
  1490. • {bufnr} (number)
  1491. Return: ~
  1492. (string) URI
  1493. uri_from_fname({path}) *vim.uri_from_fname()*
  1494. Get a URI from a file path.
  1495. Parameters: ~
  1496. • {path} (string) Path to file
  1497. Return: ~
  1498. (string) URI
  1499. uri_to_bufnr({uri}) *vim.uri_to_bufnr()*
  1500. Get the buffer for a uri. Creates a new unloaded buffer if no buffer for
  1501. the uri already exists.
  1502. Parameters: ~
  1503. • {uri} (string)
  1504. Return: ~
  1505. (number) bufnr
  1506. uri_to_fname({uri}) *vim.uri_to_fname()*
  1507. Get a filename from a URI
  1508. Parameters: ~
  1509. • {uri} (string)
  1510. Return: ~
  1511. (string) filename or unchanged URI for non-file URIs
  1512. ==============================================================================
  1513. Lua module: ui *lua-ui*
  1514. input({opts}, {on_confirm}) *vim.ui.input()*
  1515. Prompts the user for input
  1516. Example: >
  1517. vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
  1518. vim.o.shiftwidth = tonumber(input)
  1519. end)
  1520. <
  1521. Parameters: ~
  1522. • {opts} (table) Additional options. See |input()|
  1523. • prompt (string|nil) Text of the prompt
  1524. • default (string|nil) Default reply to the input
  1525. • completion (string|nil) Specifies type of completion
  1526. supported for input. Supported types are the same that
  1527. can be supplied to a user-defined command using the
  1528. "-complete=" argument. See |:command-completion|
  1529. • highlight (function) Function that will be used for
  1530. highlighting user inputs.
  1531. • {on_confirm} (function) ((input|nil) -> ()) Called once the user
  1532. confirms or abort the input. `input` is what the user
  1533. typed. `nil` if the user aborted the dialog.
  1534. select({items}, {opts}, {on_choice}) *vim.ui.select()*
  1535. Prompts the user to pick a single item from a collection of entries
  1536. Example: >
  1537. vim.ui.select({ 'tabs', 'spaces' }, {
  1538. prompt = 'Select tabs or spaces:',
  1539. format_item = function(item)
  1540. return "I'd like to choose " .. item
  1541. end,
  1542. }, function(choice)
  1543. if choice == 'spaces' then
  1544. vim.o.expandtab = true
  1545. else
  1546. vim.o.expandtab = false
  1547. end
  1548. end)
  1549. <
  1550. Parameters: ~
  1551. • {items} (table) Arbitrary items
  1552. • {opts} (table) Additional options
  1553. • prompt (string|nil) Text of the prompt. Defaults to
  1554. `Select one of:`
  1555. • format_item (function item -> text) Function to format
  1556. an individual item from `items`. Defaults to
  1557. `tostring`.
  1558. • kind (string|nil) Arbitrary hint string indicating the
  1559. item shape. Plugins reimplementing `vim.ui.select` may
  1560. wish to use this to infer the structure or semantics of
  1561. `items`, or the context in which select() was called.
  1562. • {on_choice} (function) ((item|nil, idx|nil) -> ()) Called once the
  1563. user made a choice. `idx` is the 1-based index of `item`
  1564. within `items`. `nil` if the user aborted the dialog.
  1565. ==============================================================================
  1566. Lua module: filetype *lua-filetype*
  1567. add({filetypes}) *vim.filetype.add()*
  1568. Add new filetype mappings.
  1569. Filetype mappings can be added either by extension or by filename (either
  1570. the "tail" or the full file path). The full file path is checked first,
  1571. followed by the file name. If a match is not found using the filename,
  1572. then the filename is matched against the list of |lua-patterns| (sorted by
  1573. priority) until a match is found. Lastly, if pattern matching does not
  1574. find a filetype, then the file extension is used.
  1575. The filetype can be either a string (in which case it is used as the
  1576. filetype directly) or a function. If a function, it takes the full path
  1577. and buffer number of the file as arguments (along with captures from the
  1578. matched pattern, if any) and should return a string that will be used as
  1579. the buffer's filetype. Optionally, the function can return a second
  1580. function value which, when called, modifies the state of the buffer. This
  1581. can be used to, for example, set filetype-specific buffer variables.
  1582. Filename patterns can specify an optional priority to resolve cases when a
  1583. file path matches multiple patterns. Higher priorities are matched first.
  1584. When omitted, the priority defaults to 0. A pattern can contain
  1585. environment variables of the form "${SOME_VAR}" that will be automatically
  1586. expanded. If the environment variable is not set, the pattern won't be
  1587. matched.
  1588. See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
  1589. Note that Lua filetype detection is disabled when |g:do_legacy_filetype|
  1590. is set.
  1591. Example: >
  1592. vim.filetype.add({
  1593. extension = {
  1594. foo = 'fooscript',
  1595. bar = function(path, bufnr)
  1596. if some_condition() then
  1597. return 'barscript', function(bufnr)
  1598. -- Set a buffer variable
  1599. vim.b[bufnr].barscript_version = 2
  1600. end
  1601. end
  1602. return 'bar'
  1603. end,
  1604. },
  1605. filename = {
  1606. ['.foorc'] = 'toml',
  1607. ['/etc/foo/config'] = 'toml',
  1608. },
  1609. pattern = {
  1610. ['.*/etc/foo/.*'] = 'fooscript',
  1611. -- Using an optional priority
  1612. ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } },
  1613. -- A pattern containing an environment variable
  1614. ['${XDG_CONFIG_HOME}/foo/git'] = 'git',
  1615. ['README.(a+)$'] = function(path, bufnr, ext)
  1616. if ext == 'md' then
  1617. return 'markdown'
  1618. elseif ext == 'rst' then
  1619. return 'rst'
  1620. end
  1621. end,
  1622. },
  1623. })
  1624. <
  1625. To add a fallback match on contents (see |new-filetype-scripts|), use >
  1626. vim.filetype.add {
  1627. pattern = {
  1628. ['.*'] = {
  1629. priority = -math.huge,
  1630. function(path, bufnr)
  1631. local content = vim.filetype.getlines(bufnr, 1)
  1632. if vim.filetype.matchregex(content, [[^#!.*\<mine\>]]) then
  1633. return 'mine'
  1634. elseif vim.filetype.matchregex(content, [[\<drawing\>]]) then
  1635. return 'drawing'
  1636. end
  1637. end,
  1638. },
  1639. },
  1640. }
  1641. <
  1642. Parameters: ~
  1643. • {filetypes} (table) A table containing new filetype maps (see
  1644. example).
  1645. match({args}) *vim.filetype.match()*
  1646. Perform filetype detection.
  1647. The filetype can be detected using one of three methods:
  1648. 1. Using an existing buffer
  1649. 2. Using only a file name
  1650. 3. Using only file contents
  1651. Of these, option 1 provides the most accurate result as it uses both the
  1652. buffer's filename and (optionally) the buffer contents. Options 2 and 3
  1653. can be used without an existing buffer, but may not always provide a match
  1654. in cases where the filename (or contents) cannot unambiguously determine
  1655. the filetype.
  1656. Each of the three options is specified using a key to the single argument
  1657. of this function. Example:
  1658. >
  1659. -- Using a buffer number
  1660. vim.filetype.match({ buf = 42 })
  1661. -- Override the filename of the given buffer
  1662. vim.filetype.match({ buf = 42, filename = 'foo.c' })
  1663. -- Using a filename without a buffer
  1664. vim.filetype.match({ filename = 'main.lua' })
  1665. -- Using file contents
  1666. vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
  1667. <
  1668. Parameters: ~
  1669. • {args} (table) Table specifying which matching strategy to use.
  1670. Accepted keys are:
  1671. • buf (number): Buffer number to use for matching. Mutually
  1672. exclusive with {contents}
  1673. • filename (string): Filename to use for matching. When {buf}
  1674. is given, defaults to the filename of the given buffer
  1675. number. The file need not actually exist in the filesystem.
  1676. When used without {buf} only the name of the file is used
  1677. for filetype matching. This may result in failure to detect
  1678. the filetype in cases where the filename alone is not enough
  1679. to disambiguate the filetype.
  1680. • contents (table): An array of lines representing file
  1681. contents to use for matching. Can be used with {filename}.
  1682. Mutually exclusive with {buf}.
  1683. Return: ~
  1684. (string|nil) If a match was found, the matched filetype.
  1685. (function|nil) A function that modifies buffer state when called (for
  1686. example, to set some filetype specific buffer variables). The function
  1687. accepts a buffer number as its only argument.
  1688. ==============================================================================
  1689. Lua module: keymap *lua-keymap*
  1690. del({modes}, {lhs}, {opts}) *vim.keymap.del()*
  1691. Remove an existing mapping. Examples: >
  1692. vim.keymap.del('n', 'lhs')
  1693. vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
  1694. <
  1695. Parameters: ~
  1696. • {opts} (table|nil) A table of optional arguments:
  1697. • buffer: (number or boolean) Remove a mapping from the given
  1698. buffer. When "true" or 0, use the current buffer.
  1699. See also: ~
  1700. |vim.keymap.set()|
  1701. set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
  1702. Add a new |mapping|. Examples: >
  1703. -- Can add mapping to Lua functions
  1704. vim.keymap.set('n', 'lhs', function() print("real lua function") end)
  1705. -- Can use it to map multiple modes
  1706. vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer=true })
  1707. -- Can add mapping for specific buffer
  1708. vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 })
  1709. -- Expr mappings
  1710. vim.keymap.set('i', '<Tab>', function()
  1711. return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
  1712. end, { expr = true })
  1713. -- <Plug> mappings
  1714. vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)')
  1715. <
  1716. Note that in a mapping like: >
  1717. vim.keymap.set('n', 'asdf', require('jkl').my_fun)
  1718. <
  1719. the `require('jkl')` gets evaluated during this call in order to access the function. If you
  1720. want to avoid this cost at startup you can wrap it in a function, for
  1721. example: >
  1722. vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end)
  1723. <
  1724. Parameters: ~
  1725. • {mode} string|table Same mode short names as |nvim_set_keymap()|. Can
  1726. also be list of modes to create mapping on multiple modes.
  1727. • {lhs} (string) Left-hand side |{lhs}| of the mapping.
  1728. • {rhs} string|function Right-hand side |{rhs}| of the mapping. Can
  1729. also be a Lua function.
  1730. • {opts} (table|nil) A table of |:map-arguments|.
  1731. • Accepts options accepted by the {opts} parameter in
  1732. |nvim_set_keymap()|, with the following notable differences:
  1733. • replace_keycodes: Defaults to `true` if "expr" is `true`.
  1734. • noremap: Always overridden with the inverse of "remap"
  1735. (see below).
  1736. • In addition to those options, the table accepts the
  1737. following keys:
  1738. • buffer: (number or boolean) Add a mapping to the given
  1739. buffer. When `0` or `true`, use the current buffer.
  1740. • remap: (boolean) Make the mapping recursive. This is the
  1741. inverse of the "noremap" option from |nvim_set_keymap()|.
  1742. Defaults to `false`.
  1743. See also: ~
  1744. |nvim_set_keymap()|
  1745. ==============================================================================
  1746. Lua module: fs *lua-fs*
  1747. basename({file}) *vim.fs.basename()*
  1748. Return the basename of the given file or directory
  1749. Parameters: ~
  1750. • {file} (string) File or directory
  1751. Return: ~
  1752. (string) Basename of {file}
  1753. dir({path}) *vim.fs.dir()*
  1754. Return an iterator over the files and directories located in {path}
  1755. Parameters: ~
  1756. • {path} (string) An absolute or relative path to the directory to
  1757. iterate over. The path is first normalized
  1758. |vim.fs.normalize()|.
  1759. Return: ~
  1760. Iterator over files and directories in {path}. Each iteration yields
  1761. two values: name and type. Each "name" is the basename of the file or
  1762. directory relative to {path}. Type is one of "file" or "directory".
  1763. dirname({file}) *vim.fs.dirname()*
  1764. Return the parent directory of the given file or directory
  1765. Parameters: ~
  1766. • {file} (string) File or directory
  1767. Return: ~
  1768. (string) Parent directory of {file}
  1769. find({names}, {opts}) *vim.fs.find()*
  1770. Find files or directories in the given path.
  1771. Finds any files or directories given in {names} starting from {path}. If
  1772. {upward} is "true" then the search traverses upward through parent
  1773. directories; otherwise, the search traverses downward. Note that downward
  1774. searches are recursive and may search through many directories! If {stop}
  1775. is non-nil, then the search stops when the directory given in {stop} is
  1776. reached. The search terminates when {limit} (default 1) matches are found.
  1777. The search can be narrowed to find only files or or only directories by
  1778. specifying {type} to be "file" or "directory", respectively.
  1779. Parameters: ~
  1780. • {names} (string|table|fun(name: string): boolean) Names of the files
  1781. and directories to find. Must be base names, paths and globs
  1782. are not supported. If a function it is called per file and
  1783. dir within the traversed directories to test if they match.
  1784. • {opts} (table) Optional keyword arguments:
  1785. • path (string): Path to begin searching from. If omitted,
  1786. the current working directory is used.
  1787. • upward (boolean, default false): If true, search upward
  1788. through parent directories. Otherwise, search through child
  1789. directories (recursively).
  1790. • stop (string): Stop searching when this directory is
  1791. reached. The directory itself is not searched.
  1792. • type (string): Find only files ("file") or directories
  1793. ("directory"). If omitted, both files and directories that
  1794. match {name} are included.
  1795. • limit (number, default 1): Stop the search after finding
  1796. this many matches. Use `math.huge` to place no limit on the
  1797. number of matches.
  1798. Return: ~
  1799. (table) The paths of all matching files or directories
  1800. normalize({path}) *vim.fs.normalize()*
  1801. Normalize a path to a standard format. A tilde (~) character at the
  1802. beginning of the path is expanded to the user's home directory and any
  1803. backslash (\) characters are converted to forward slashes (/). Environment
  1804. variables are also expanded.
  1805. Example: >
  1806. vim.fs.normalize('C:\Users\jdoe')
  1807. => 'C:/Users/jdoe'
  1808. vim.fs.normalize('~/src/neovim')
  1809. => '/home/jdoe/src/neovim'
  1810. vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim')
  1811. => '/Users/jdoe/.config/nvim/init.vim'
  1812. <
  1813. Parameters: ~
  1814. • {path} (string) Path to normalize
  1815. Return: ~
  1816. (string) Normalized path
  1817. parents({start}) *vim.fs.parents()*
  1818. Iterate over all the parents of the given file or directory.
  1819. Example: >
  1820. local root_dir
  1821. for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
  1822. if vim.fn.isdirectory(dir .. "/.git") == 1 then
  1823. root_dir = dir
  1824. break
  1825. end
  1826. end
  1827. if root_dir then
  1828. print("Found git repository at", root_dir)
  1829. end
  1830. <
  1831. Parameters: ~
  1832. • {start} (string) Initial file or directory.
  1833. Return: ~
  1834. (function) Iterator
  1835. vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: