robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
225.0 KiB6169 linesraw
1*lua.txt*    Nvim
2
3
4                            NVIM REFERENCE MANUAL
5
6
7Lua engine                                                           *lua* *Lua*
8
9                                       Type |gO| to see the table of contents.
10
11==============================================================================
12INTRODUCTION                                                       *lua-intro*
13
14The Lua 5.1 script engine is builtin and always available. Try this command to
15get an idea of what lurks beneath: >vim
16
17    :lua vim.print(package.loaded)
18
19Nvim includes a "standard library" |lua-stdlib| for Lua.  It complements the
20"editor stdlib" (|vimscript-functions| + |Ex-command|s) and the |API|, all of
21which can be used from Lua code (|lua-vimscript| |vim.api|). These three
22namespaces form the Nvim programming interface.
23
24Lua plugins and user config are automatically discovered and loaded, just like
25Vimscript. See |lua-guide| for practical guidance.
26
27You can also run Lua scripts from your shell using the |-l| argument: >
28    nvim -l foo.lua [args...]
29<
30                                                                  *lua-compat*
31Lua 5.1 is the permanent interface for Nvim Lua. Plugins should target Lua 5.1
32as specified in |luaref|; later versions (which are essentially different,
33incompatible, dialects) are not supported. This includes extensions such as
34`goto` that some Lua 5.1 interpreters like LuaJIT may support.
35
36                                                                  *lua-luajit*
37While Nvim officially only requires Lua 5.1 support, it should be built with
38LuaJIT or a compatible fork on supported platforms for performance reasons.
39LuaJIT also comes with useful extensions such as `ffi`, |lua-profile|, and
40enhanced standard library functions; these cannot be assumed to be available,
41and Lua code in |init.lua| or plugins should check the `jit` global variable
42before using them: >lua
43  if jit then
44    -- code for luajit
45  else
46    -- code for plain lua 5.1
47  end
48<
49One exception is the LuaJIT `bit` extension, which is always available: when
50built with PUC Lua, Nvim includes a fallback implementation which provides
51`require("bit")`. See |lua-bit|.
52
53                                                                  *lua-profile*
54If Nvim is built with LuaJIT, Lua code can be profiled via >lua
55    -- Start a profiling session:
56    require('jit.p').start('ri1', '/tmp/profile')
57
58    -- Perform arbitrary tasks (use plugins, scripts, etc.) ...
59
60    -- Stop the session. Profile is written to /tmp/profile.
61    require('jit.p').stop()
62
63See https://luajit.org/ext_profiler.html or the `p.lua` source for details: >
64    :lua vim.cmd.edit(package.searchpath('jit.p', package.path))
65
66==============================================================================
67LUA CONCEPTS AND IDIOMS                                         *lua-concepts*
68
69Lua is very simple, and _consistent_: while there are some quirks, once you
70internalize those quirks, everything works the same everywhere. Scopes
71(closures) in particular are very consistent, unlike JavaScript or most other
72languages.
73
74Lua has three fundamental mechanisms—one for "each major aspect of
75programming": tables, closures, and coroutines.
76https://www.lua.org/doc/cacm2018.pdf
77- Tables are the "object" or container datastructure: they represent both
78  lists and maps, you can extend them to represent your own datatypes and
79  change their behavior using |metatable|s (like Python's "datamodel").
80- EVERY scope in Lua is a closure: a function is a closure, a module is
81  a closure, a `do` block (|lua-do|) is a closure--and they all work the same.
82  A Lua module is literally just a big closure discovered on the "path"
83  (where your modules are found: |package.cpath|).
84- Stackful coroutines enable cooperative multithreading, generators, and
85  versatile control for both Lua and its host (Nvim).
86
87                                                          *lua-error-handling*
88Lua functions may throw |lua-errors| for exceptional (unexpected) failures,
89which you can handle with |pcall()|.
90                                                       *lua-result-or-message*
91When failure is normal and expected, it's idiomatic to return `nil` which
92signals to the caller that failure is not "exceptional" and must be handled.
93This "result-or-message" pattern is expressed as the multi-value return type
94`any|nil,nil|string`, or in LuaLS notation: >
95
96    ---@return any|nil    # result on success, nil on failure.
97    ---@return nil|string # nil on success, error message on failure.
98<
99Examples of the "result-or-message" pattern:
100- |vim.ui.open()|
101- |io.open()|
102- |luv-error-handling|
103
104When a caller can't proceed on failure, it's idiomatic to `assert()` the
105"result-or-message" result: >lua
106
107    local value = assert(fn())
108
109Guidance: use the "result-or-message" pattern for...
110- Functions where failure is expected, especially when communicating with the
111  external world. E.g. HTTP requests or LSP requests often fail because of
112  server problems, even if the caller did everything right.
113- Functions that return a value, e.g. Foo:new().
114- When there is a list of known error codes which can be returned as a third
115  value (like |luv-error-handling|).
116<
117                                                                    *iterator*
118An iterator is just a function that can be called repeatedly to get the "next"
119value of a collection (or any other |iterable|). This interface is expected by
120|for-in| loops, produced by |pairs()|, supported by |vim.iter|, etc.
121https://www.lua.org/pil/7.1.html
122
123                                                                    *iterable*
124An "iterable" is anything that |vim.iter()| can consume: tables, dicts, lists,
125iterator functions, tables implementing the |__call()| metamethod, and
126|vim.iter()| objects.
127
128                                                               *list-iterator*
129Iterators on |lua-list| tables have a "middle" and "end", whereas iterators in
130general may be logically infinite. Therefore some |vim.iter| operations (e.g.
131|IterArray:rev()|) make sense only on list-like tables (which are finite by
132definition).
133
134                                                           *lua-function-call*
135Lua functions can be called in multiple ways. Consider the function: >lua
136    local foo = function(a, b)
137        print("A: ", a)
138        print("B: ", b)
139    end
140
141The first way to call this function is: >lua
142    foo(1, 2)
143    -- ==== Result ====
144    -- A: 1
145    -- B: 2
146
147This way of calling a function is familiar from most scripting languages. In
148Lua, any missing arguments are passed as `nil`, and extra parameters are
149silently discarded. Example: >lua
150    foo(1)
151    -- ==== Result ====
152    -- A: 1
153    -- B: nil
154<
155                                                                      *kwargs*
156When calling a function, you can omit the parentheses if the function takes
157exactly one string literal (`"foo"`) or table literal (`{1,2,3}`). The latter
158is often used to mimic "named parameters" ("kwargs" or "keyword args") as in
159languages like Python and C#. Example: >lua
160    local func_with_opts = function(opts)
161        local will_do_foo = opts.foo
162        local filename = opts.filename
163        -- ...
164    end
165
166    func_with_opts { foo = true, filename = "hello.world" }
167<
168There's nothing special going on here except that parentheses are implicitly
169added. But visually, this small bit of sugar gets reasonably close to a
170"keyword args" interface.
171
172                                                                   *lua-regex*
173Lua intentionally does not support regular expressions, instead it has limited
174|lua-pattern|s which avoid the performance pitfalls of extended regex. Lua
175scripts can also use Vim regex via |vim.regex()|.
176
177Examples: >lua
178
179    print(string.match("foo123bar123", "%d+"))
180    -- 123
181    print(string.match("foo123bar123", "[^%d]+"))
182    -- foo
183    print(string.match("foo123bar123", "[abc]+"))
184    -- ba
185    print(string.match("foo.bar", "%.bar"))
186    -- .bar
187<
188                                                                  *lua-truthy*
189Only `false` and `nil` evaluate to "false" in Lua. All other values are "true".
190
191
192==============================================================================
193IMPORTING LUA MODULES                                        *lua-module-load*
194
195Modules are searched for under the directories specified in 'runtimepath' and
196|packages-runtimepath|, in the order they appear in the output of this command
197>vim
198    :echo nvim_list_runtime_paths()
199<
200Any "." in the module name is treated as a directory separator when searching.
201For a module `foo.bar`, each directory is searched for `lua/foo/bar.lua`, then
202`lua/foo/bar/init.lua`.  If no files are found, the directories are searched
203again for a shared library with a name matching `lua/foo/bar.?`, where `?` is
204a list of suffixes (such as `so` or `dll`) derived from the initial value of
205|package.cpath|. If still no files are found, Nvim falls back to Lua's default
206search mechanism. The first script found is run and `require()` returns the
207value returned by the script if any, else `true`.
208
209The return value is cached after the first call to `require()` for each module,
210with subsequent calls returning the cached value without searching for, or
211executing any script. For further details see |require()|.
212
213For example, if 'runtimepath' is `foo,bar` and |package.cpath| was
214`./?.so;./?.dll` at startup, `require('mod')` searches these paths in order
215and loads the first module found ("first wins"): >
216    foo/lua/mod.lua
217    foo/lua/mod/init.lua
218    bar/lua/mod.lua
219    bar/lua/mod/init.lua
220    foo/lua/mod.so
221    foo/lua/mod.dll
222    bar/lua/mod.so
223    bar/lua/mod.dll
224<
225Note:
226
227- Although 'runtimepath' is tracked, Nvim does not track current
228  values of |package.path| or |package.cpath|. If you happen to delete some
229  paths from there you can set 'runtimepath' to trigger an update: >vim
230      let &runtimepath = &runtimepath
231
232- Skipping paths from 'runtimepath' which contain semicolons applies both to
233  |package.path| and |package.cpath|. Given that there are some badly written
234  plugins using shell, which will not work with paths containing semicolons,
235  it is better to not have them in 'runtimepath' at all.
236
237                                                         *lua-script-location*
238To get its own location, Lua scripts/modules can use |debug.getinfo()|: >
239    debug.getinfo(1, 'S').source:gsub('^@', '')
240<
241
242==============================================================================
243COMMANDS                                                        *lua-commands*
244
245These commands execute a Lua chunk from either the command line (:lua, :luado)
246or a file (:luafile) on the given line [range]. As always in Lua, each chunk
247has its own scope (closure), so only global variables are shared between
248command calls. The |lua-stdlib| modules, user modules, and anything else on
249|package.path| are available.
250
251The Lua print() function redirects its output to the Nvim message area, with
252arguments separated by " " (space) instead of "\t" (tab).
253
254                                                                  *:lua=* *:lua*
255:lua {chunk}
256    Executes Lua chunk {chunk}. If {chunk} starts with "=" the rest of the
257    chunk is evaluated as an expression and printed. `:lua =expr` and `:=expr`
258    are equivalent to `:lua print(vim.inspect(expr))`. |E5107| |E5108|
259
260    Examples: >vim
261        :lua vim.api.nvim_command('echo "Hello, Nvim!"')
262<    To see the Lua version: >vim
263        :lua print(_VERSION)
264<    To see the LuaJIT version: >vim
265        :lua =jit.version
266<
267:{range}lua
268    Executes buffer lines in {range} as Lua code. Unlike |:source|, this
269    always treats the lines as Lua code.
270
271    Example: select the following code and type ":lua<Enter>" to execute it: >lua
272        print(string.format(
273            'unix time: %s', os.time()))
274<
275                                                                *:lua-heredoc*
276:lua << [trim] [{endmarker}]
277{script}
278{endmarker}
279    Executes Lua script {script} from within Vimscript. You can omit
280    [endmarker] after the "<<" and use a dot "." after {script} (similar to
281    |:append|, |:insert|). Refer to |:let-heredoc| for more information.
282
283    Example: >vim
284        function! CurrentLineInfo()
285        lua << EOF
286        local linenr = vim.api.nvim_win_get_cursor(0)[1]
287        local curline = vim.api.nvim_buf_get_lines(0, linenr - 1, linenr, false)[1]
288        print(string.format('Line [%d] has %d bytes', linenr, #curline))
289        EOF
290        endfunction
291<
292    Note that the `local` variables will disappear when the block finishes.
293    But not globals.
294
295                                                                      *:luado*
296:[range]luado {body}
297    Executes Lua chunk "function(line, linenr) {body} end" for each buffer
298    line in [range], where `line` is the current line text (without <EOL>),
299    and `linenr` is the current line number. If the function returns a string
300    that becomes the text of the corresponding buffer line. Default [range] is
301    the whole file: "1,$". |E5109| |E5110| |E5111|
302
303    Examples: >vim
304        :luado return string.format("%s\t%d", line:reverse(), #line)
305
306        :lua require"lpeg"
307        :lua -- balanced parenthesis grammar:
308        :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
309        :luado if bp:match(line) then return "=>\t" .. line end
310<
311                                                                    *:luafile*
312:luafile {file}
313    Execute Lua script in {file}.
314    The whole argument is used as the filename (like |:edit|), spaces do not
315    need to be escaped. Alternatively you can |:source| Lua files.
316    |E5111| |E5112| |E5113|
317
318    Examples: >vim
319        :luafile script.lua
320        :luafile %
321<
322
323==============================================================================
324luaeval()                                                 *lua-eval*
325
326The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is
327"luaeval". "luaeval" takes an expression string and an optional argument used
328for _A inside expression and returns the result of the expression. It is
329semantically equivalent in Lua to: >lua
330
331    local chunkheader = "local _A = select(1, ...) return "
332    function luaeval (expstr, arg)
333        local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
334        return chunk(arg) -- return typval
335    end
336<
337Lua nils, numbers, strings, tables and booleans are converted to their
338respective Vimscript types. If a Lua string contains a NUL byte, it will be
339converted to a |Blob|. Conversion of other Lua types is an error.
340
341The magic global "_A" contains the second argument to luaeval().
342
343Example: >vim
344    :echo luaeval('_A[1] + _A[2]', [40, 2])
345    " 42
346    :echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123')
347    " foo
348<
349                                                         *lua-table-ambiguous*
350Lua tables are used as both dictionaries and lists, so it is impossible to
351decide whether empty table is a list or a dict. Also Lua does not have integer
352numbers. To disambiguate these cases, we define:
353                                                                    *lua-list*
3540. Empty table is a list. Use |vim.empty_dict()| to represent empty dict.
3551. Table with N consecutive (no `nil` values, aka "holes") integer keys 1…N is
356   a list. See also |list-iterator|.
357                                                                    *lua-dict*
3582. Table with string keys, none of which contains NUL byte, is a dict.
3593. Table with string keys, at least one of which contains NUL byte, is also
360   considered to be a dictionary, but this time it is converted to
361   a |msgpack-special-map|.
362                                     *lua-special-tbl* *E5100* *E5101* *E5102*
3634. Table with `vim.type_idx` key may be a dictionary, a list or floating-point
364   value:
365   - `{[vim.type_idx]=vim.types.float, [vim.val_idx]=1}` is converted to
366     a floating-point 1.0. Note that by default integral Lua numbers are
367     converted to |Number|s, non-integral are converted to |Float|s. This
368     variant allows integral |Float|s.
369   - `{[vim.type_idx]=vim.types.dictionary}` is converted to an empty
370     dictionary, `{[vim.type_idx]=vim.types.dictionary, [42]=1, a=2}` is
371     converted to a dictionary `{'a': 42}`: non-string keys are ignored.
372     Without `vim.type_idx` key tables with keys not fitting in 1., 2. or 3.
373     are errors.
374   - `{[vim.type_idx]=vim.types.array}` is converted to an empty list. As well
375     as `{[vim.type_idx]=vim.types.array, [42]=1}`: integral keys that do not
376     form a 1-step sequence from 1 to N are ignored, as well as all
377     non-integral keys.
378
379Examples: >vim
380
381    :echo luaeval('math.pi')
382    :function Rand(x,y) " random uniform between x and y
383    :  return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
384    :  endfunction
385    :echo Rand(1,10)
386<
387Note: Second argument to `luaeval` is converted ("marshalled") from Vimscript
388to Lua, so changes to Lua containers do not affect values in Vimscript. Return
389value is also always converted. When converting, |msgpack-special-dict|s are
390treated specially.
391
392==============================================================================
393Vimscript v:lua interface                                         *v:lua-call*
394
395From Vimscript the special `v:lua` prefix can be used to call Lua functions
396which are global or accessible from global tables. The expression >vim
397    call v:lua.func(arg1, arg2)
398is equivalent to the Lua chunk >lua
399    return func(...)
400where the args are converted to Lua values. The expression >vim
401    call v:lua.somemod.func(args)
402is equivalent to the Lua chunk >lua
403    return somemod.func(...)
404
405Lua module functions can be accessed like: >vim
406    call v:lua.require'mypack'.func(arg1, arg2)
407    call v:lua.require'mypack.submod'.func(arg1, arg2)
408Note: Only single quote form without parens is allowed. Using
409`require"mypack"` or `require('mypack')` as a prefix does NOT work.
410
411You can use `v:lua` in "func" options like 'tagfunc', 'omnifunc', etc.
412For example consider the following Lua omnifunc handler: >lua
413
414    function mymod.omnifunc(findstart, base)
415      if findstart == 1 then
416        return 0
417      else
418        return {'stuff', 'steam', 'strange things'}
419      end
420    end
421    -- Note: The module ("mymod") must be a Lua global, or use require() as
422    -- shown above to access it from a package.
423    vim.bo[buf].omnifunc = 'v:lua.mymod.omnifunc'
424
425You can also use `v:lua` to call Lua functions as Vimscript |method|s: >vim
426    :eval arg1->v:lua.somemod.func(arg2)
427<
428Note: `v:lua` without a call is not allowed in a Vimscript expression:
429|Funcref|s cannot represent Lua functions. The following are errors: >vim
430
431    let g:Myvar = v:lua.myfunc        " Error
432    call SomeFunc(v:lua.mycallback)   " Error
433    let g:foo = v:lua                 " Error
434    let g:foo = v:['lua']             " Error
435<
436==============================================================================
437Lua standard modules                                              *lua-stdlib*
438
439The Nvim Lua "standard library" (stdlib) is the `vim` module, which exposes
440various functions and sub-modules. It is always loaded, thus `require("vim")`
441is unnecessary.
442
443You can peek at the module properties: >vim
444
445    :lua vim.print(vim)
446
447Result is something like this: >
448
449    {
450      _os_proc_children = <function 1>,
451      _os_proc_info = <function 2>,
452      ...
453      api = {
454        nvim__id = <function 5>,
455        nvim__id_array = <function 6>,
456        ...
457      },
458      deepcopy = <function 106>,
459      gsplit = <function 107>,
460      ...
461    }
462
463To find documentation on e.g. the "deepcopy" function: >vim
464
465    :help vim.deepcopy()
466
467Note that underscore-prefixed functions (e.g. "_os_proc_children") are
468internal/private and must not be used by plugins.
469
470------------------------------------------------------------------------------
471VIM.UV                                                   *lua-loop* *vim.uv*
472
473`vim.uv` exposes the "luv" Lua bindings for the libUV library that Nvim uses
474for networking, filesystem, and process management, see |luvref.txt|.
475In particular, it allows interacting with the main Nvim |luv-event-loop|.
476
477                                                    *E5560* *lua-loop-callbacks*
478It is an error to directly invoke `vim.api` functions (except |api-fast|) in
479`vim.uv` callbacks. For example, this is an error: >lua
480
481    local timer = vim.uv.new_timer()
482    timer:start(1000, 0, function()
483      vim.api.nvim_command('echomsg "test"')
484    end)
485<
486To avoid the error, |schedule| the callback: >lua
487
488    local timer = vim.uv.new_timer()
489    timer:start(1000, 0, vim.schedule_wrap(function()
490      vim.api.nvim_command('echomsg "test"')
491    end))
492<
493(For one-shot timers, see |vim.defer_fn()|, which automatically adds the
494wrapping.)
495
496Example: repeating timer
497    1. Save this code to a file.
498    2. Execute it with ":luafile %". >lua
499
500    -- Create a timer handle (implementation detail: uv_timer_t).
501    local timer = vim.uv.new_timer()
502    local i = 0
503    -- Waits 1000ms, then repeats every 750ms until timer:close().
504    timer:start(1000, 750, function()
505      print('timer invoked! i='..tostring(i))
506      if i > 4 then
507        timer:close()  -- Always close handles to avoid leaks.
508      end
509      i = i + 1
510    end)
511    print('sleeping');
512<
513Example: File-change detection                                    *watch-file*
514    1. Save this code to a file.
515    2. Execute it with ":luafile %".
516    3. Use ":Watch %" to watch any file.
517    4. Try editing the file from another text editor.
518    5. Observe that the file reloads in Nvim (because on_change() calls
519       |:checktime|). >lua
520
521    local w = vim.uv.new_fs_event()
522    local function on_change(err, fname, status)
523      -- Do work...
524      vim.api.nvim_command('checktime')
525      -- Debounce: stop/start.
526      w:stop()
527      watch_file(fname)
528    end
529    function watch_file(fname)
530      local fullpath = vim.api.nvim_call_function(
531        'fnamemodify', {fname, ':p'})
532      w:start(fullpath, {}, vim.schedule_wrap(function(...)
533        on_change(...) end))
534    end
535    vim.api.nvim_command(
536      "command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))")
537<
538                                                         *inotify-limitations*
539When on Linux you may need to increase the maximum number of `inotify` watches
540and queued events as the default limit can be too low. To increase the limit,
541run: >bash
542    sysctl fs.inotify.max_user_watches=494462
543<
544This will increase the limit to 494462 watches and queued events. These lines
545can be added to `/etc/sysctl.conf` to make the changes persistent.
546
547Note that each watch is a structure in the Kernel, thus available memory is
548also a bottleneck for using inotify. In fact, a watch can take up to 1KB of
549space. This means a million watches could result in 1GB of extra RAM usage.
550
551Example: TCP echo-server                                          *tcp-server*
552    1. Save this code to a file.
553    2. Execute it with ":luafile %".
554    3. Note the port number.
555    4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): >lua
556
557    local function create_server(host, port, on_connect)
558      local server = vim.uv.new_tcp()
559      server:bind(host, port)
560      server:listen(128, function(err)
561        assert(not err, err)  -- Check for errors.
562        local sock = vim.uv.new_tcp()
563        server:accept(sock)  -- Accept client connection.
564        on_connect(sock)  -- Start reading messages.
565      end)
566      return server
567    end
568    local server = create_server('0.0.0.0', 0, function(sock)
569      sock:read_start(function(err, chunk)
570        assert(not err, err)  -- Check for errors.
571        if chunk then
572          sock:write(chunk)  -- Echo received messages to the channel.
573        else  -- EOF (stream closed).
574          sock:close()  -- Always close handles to avoid leaks.
575        end
576      end)
577    end)
578    print('TCP echo-server listening on port: '..server:getsockname().port)
579<
580Multithreading                                            *lua-loop-threading*
581
582Plugins can perform work in separate (os-level) threads using the threading
583APIs in luv, for instance `vim.uv.new_thread`. Each thread has its own
584separate Lua interpreter state, with no access to Lua globals on the main
585thread. Neither can the editor state (buffers, windows, etc) be directly
586accessed from threads.
587
588A subset of the `vim.*` stdlib is available in threads, including:
589
590- `vim.uv` with a separate event loop per thread.
591- `vim.mpack` and `vim.json` (useful for serializing messages between threads)
592- `require` in threads can use Lua packages from the global |package.path|
593- `print()` and `vim.inspect`
594- `vim.text.diff`
595- Most utility functions in `vim.*` that work with pure Lua values, like
596  `vim.split`, `vim.tbl_*`, `vim.list_*`, etc.
597- `vim.is_thread()` returns true from a non-main thread.
598
599==============================================================================
600VIM                                                              *vim.builtin*
601
602vim.api.{func}({...})                                                *vim.api*
603    Invokes Nvim |API| function {func} with arguments {...}.
604    Example: call the "nvim_get_current_line()" API function: >lua
605        print(tostring(vim.api.nvim_get_current_line()))
606
607vim.NIL                                                              *vim.NIL*
608    Special value representing NIL in |RPC| and |v:null| in Vimscript
609    conversion, and similar cases. Lua `nil` cannot be used as part of a Lua
610    table representing a Dictionary or Array, because it is treated as
611    missing: `{"foo", nil}` is the same as `{"foo"}`.
612
613vim.type_idx                                                    *vim.type_idx*
614    Type index for use in |lua-special-tbl|. Specifying one of the values from
615    |vim.types| allows typing the empty table (it is unclear whether empty Lua
616    table represents empty list or empty array) and forcing integral numbers
617    to be |Float|. See |lua-special-tbl| for more details.
618
619vim.val_idx                                                      *vim.val_idx*
620    Value index for tables representing |Float|s. A table representing
621    floating-point value 1.0 looks like this: >lua
622        {
623          [vim.type_idx] = vim.types.float,
624          [vim.val_idx] = 1.0,
625        }
626<    See also |vim.type_idx| and |lua-special-tbl|.
627
628vim.types                                                          *vim.types*
629    Table with possible values for |vim.type_idx|. Contains two sets of
630    key-value pairs: first maps possible values for |vim.type_idx| to
631    human-readable strings, second maps human-readable type names to values
632    for |vim.type_idx|. Currently contains pairs for `float`, `array` and
633        `dictionary` types.
634
635    Note: One must expect that values corresponding to `vim.types.float`,
636    `vim.types.array` and `vim.types.dictionary` fall under only two following
637    assumptions:
638    1. Value may serve both as a key and as a value in a table. Given the
639       properties of Lua tables this basically means “value is not `nil`”.
640    2. For each value in `vim.types` table `vim.types[vim.types[value]]` is the
641       same as `value`.
642    No other restrictions are put on types, and it is not guaranteed that
643    values corresponding to `vim.types.float`, `vim.types.array` and
644    `vim.types.dictionary` will not change or that `vim.types` table will only
645    contain values for these three types.
646
647                                                   *log_levels* *vim.log.levels*
648Log levels are one of the values defined in `vim.log.levels`:
649
650    vim.log.levels.DEBUG
651    vim.log.levels.ERROR
652    vim.log.levels.INFO
653    vim.log.levels.TRACE
654    vim.log.levels.WARN
655    vim.log.levels.OFF
656
657
658
659vim.empty_dict()                                            *vim.empty_dict()*
660    Creates a special empty table (marked with a metatable), which Nvim
661    converts to an empty dictionary when translating Lua values to Vimscript
662    or API types. Nvim by default converts an empty table `{}` without this
663    metatable to an list/array.
664
665    Note: If numeric keys are present in the table, Nvim ignores the metatable
666    marker and converts the dict to a list/array anyway.
667
668    Return: ~
669        (`table`)
670
671vim.iconv({str}, {from}, {to})                                   *vim.iconv()*
672    The result is a String, which is the text {str} converted from encoding
673    {from} to encoding {to}. When the conversion fails `nil` is returned. When
674    some characters could not be converted they are replaced with "?". The
675    encoding names are whatever the iconv() library function can accept, see
676    ":Man 3 iconv".
677
678    Parameters: ~
679      • {str}   (`string`) Text to convert
680      • {from}  (`string`) Encoding of {str}
681      • {to}    (`string`) Target encoding
682
683    Return: ~
684        (`string?`) Converted string if conversion succeeds, `nil` otherwise.
685
686vim.in_fast_event()                                      *vim.in_fast_event()*
687    Returns true if the code is executing as part of a "fast" event handler,
688    where most of the API is disabled. These are low-level events (e.g.
689    |lua-loop-callbacks|) which can be invoked whenever Nvim polls for input.
690    When this is `false` most API functions are callable (but may be subject
691    to other restrictions such as |textlock|).
692
693vim.rpcnotify({channel}, {method}, {...})                    *vim.rpcnotify()*
694    Sends {event} to {channel} via |RPC| and returns immediately. If {channel}
695    is 0, the event is broadcast to all channels.
696
697    This function also works in a fast callback |lua-loop-callbacks|.
698
699    Parameters: ~
700      • {channel}  (`integer`)
701      • {method}   (`string`)
702      • {...}      (`any?`)
703
704vim.rpcrequest({channel}, {method}, {...})                  *vim.rpcrequest()*
705    Invokes |RPC| `method` on `channel` and blocks until a response is
706    received.
707
708    Note: Msgpack NIL values in the response are represented as |vim.NIL|.
709
710    Example: see |nvim_exec_lua()|
711
712    Parameters: ~
713      • {channel}  (`integer`)
714      • {method}   (`string`)
715      • {...}      (`any?`)
716
717vim.schedule({fn})                                            *vim.schedule()*
718    Schedules {fn} to be invoked soon by the main event-loop. Useful to avoid
719    |textlock| or other temporary restrictions.
720
721    Parameters: ~
722      • {fn}  (`fun()`)
723
724    Return (multiple): ~
725        (`nil`) result
726        (`string?`) err Error message if scheduling failed, `nil` otherwise.
727
728vim.str_utf_end({str}, {index})                            *vim.str_utf_end()*
729    Gets the distance (in bytes) from the last byte of the codepoint
730    (character) that {index} points to.
731
732    Examples: >lua
733        -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)
734
735        -- Returns 0 because the index is pointing at the last byte of a character
736        vim.str_utf_end('æ', 2)
737
738        -- Returns 1 because the index is pointing at the penultimate byte of a character
739        vim.str_utf_end('æ', 1)
740<
741
742    Parameters: ~
743      • {str}    (`string`)
744      • {index}  (`integer`)
745
746    Return: ~
747        (`integer`)
748
749vim.str_utf_pos({str})                                     *vim.str_utf_pos()*
750    Gets a list of the starting byte positions of each UTF-8 codepoint in the
751    given string.
752
753    Embedded NUL bytes are treated as terminating the string.
754
755    Parameters: ~
756      • {str}  (`string`)
757
758    Return: ~
759        (`integer[]`)
760
761vim.str_utf_start({str}, {index})                        *vim.str_utf_start()*
762    Gets the distance (in bytes) from the starting byte of the codepoint
763    (character) that {index} points to.
764
765    The result can be added to {index} to get the starting byte of a
766    character.
767
768    Examples: >lua
769        -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)
770
771        -- Returns 0 because the index is pointing at the first byte of a character
772        vim.str_utf_start('æ', 1)
773
774        -- Returns -1 because the index is pointing at the second byte of a character
775        vim.str_utf_start('æ', 2)
776<
777
778    Parameters: ~
779      • {str}    (`string`)
780      • {index}  (`integer`)
781
782    Return: ~
783        (`integer`)
784
785vim.stricmp({a}, {b})                                          *vim.stricmp()*
786    Compares strings case-insensitively.
787
788    Parameters: ~
789      • {a}  (`string`)
790      • {b}  (`string`)
791
792    Return: ~
793        (`0|1|-1`) if strings are equal, {a} is greater than {b} or {a} is
794        lesser than {b}, respectively.
795
796vim.ui_attach({ns}, {opts}, {callback})                      *vim.ui_attach()*
797    WARNING: This feature is experimental/unstable.
798
799    Subscribe to |ui-events|, similar to |nvim_ui_attach()| but receive events
800    in a Lua callback. Used to implement screen elements like popupmenu or
801    message handling in Lua.
802
803    {callback} receives event name plus additional parameters. See
804    |ui-popupmenu| and the sections below for event format for respective
805    events.
806
807    Callbacks for `msg_show` events originating from internal messages (as
808    opposed to events from commands or API calls) are executed in |api-fast|
809    context; showing the message needs to be scheduled.
810
811    Excessive errors inside the callback will result in forced detachment.
812
813    WARNING: This api is considered experimental. Usability will vary for
814    different screen elements. In particular `ext_messages` behavior is
815    subject to further changes and usability improvements. This is expected to
816    be used to handle messages when setting 'cmdheight' to zero (which is
817    likewise experimental).
818
819    Example (stub for a |ui-popupmenu| implementation): >lua
820        ns = vim.api.nvim_create_namespace('my_fancy_pum')
821
822        vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...)
823          if event == 'popupmenu_show' then
824            local items, selected, row, col, grid = ...
825            print('display pum ', #items)
826          elseif event == 'popupmenu_select' then
827            local selected = ...
828            print('selected', selected)
829          elseif event == 'popupmenu_hide' then
830            print('FIN')
831          end
832        end)
833<
834
835    Parameters: ~
836      • {ns}        (`integer`) Namespace ID
837      • {opts}      (`table<string, any>`) Optional parameters.
838                    • {ext_…}? (`boolean`) Any of |ui-ext-options|, if true
839                      enable events for the respective UI element.
840                    • {set_cmdheight}? (`boolean`) If false, avoid setting
841                      'cmdheight' to 0 when `ext_messages` is enabled.
842      • {callback}  (`fun(event: string, ...): any`) Function called for each
843                    UI event. A truthy return value signals to Nvim that the
844                    event is handled, in which case it is not propagated to
845                    remote UIs.
846
847vim.ui_detach({ns})                                          *vim.ui_detach()*
848    Detach a callback previously attached with |vim.ui_attach()| for the given
849    namespace {ns}.
850
851    Parameters: ~
852      • {ns}  (`integer`) Namespace ID
853
854
855==============================================================================
856LUA-VIMSCRIPT BRIDGE                                           *lua-vimscript*
857
858Nvim Lua provides an interface or "bridge" to Vimscript variables and
859functions, and editor commands and options.
860
861Objects passed over this bridge are COPIED (marshalled): there are no
862"references". |lua-guide-variables| For example, using `vim.fn.remove()` on a
863Lua list copies the list object to Vimscript and does NOT modify the Lua list: >lua
864    local list = { 1, 2, 3 }
865    vim.fn.remove(list, 0)
866    vim.print(list)  --> "{ 1, 2, 3 }"
867<
868
869vim.call({func}, {...})                                           *vim.call()*
870    Invokes |vim-function| or |user-function| {func} with arguments {...}.
871    See also |vim.fn|.
872    Equivalent to: >lua
873        vim.fn[func]({...})
874<
875vim.cmd({command})
876    See |vim.cmd()|.
877
878vim.fn.{func}({...})                                                  *vim.fn*
879    Invokes |vim-function| or |user-function| {func} with arguments {...}.
880    To call autoload functions, use the syntax: >lua
881        vim.fn['some#function']({...})
882<
883    Unlike vim.api.|nvim_call_function()| this converts directly between Vim
884    objects and Lua objects. If the Vim function returns a float, it will be
885    represented directly as a Lua number. Empty lists and dictionaries both
886    are represented by an empty table.
887
888    Note: |v:null| values as part of the return value is represented as
889    |vim.NIL| special value
890
891    Note: vim.fn keys are generated lazily, thus `pairs(vim.fn)` only
892    enumerates functions that were called at least once.
893
894    Note: The majority of functions cannot run in |api-fast| callbacks with some
895    undocumented exceptions which are allowed.
896
897                                                           *lua-vim-variables*
898The Vim editor global dictionaries |g:| |w:| |b:| |t:| |v:| can be accessed
899from Lua conveniently and idiomatically by referencing the `vim.*` Lua tables
900described below. In this way you can easily read and modify global Vimscript
901variables from Lua.
902
903Example: >lua
904
905    vim.g.foo = 5     -- Set the g:foo Vimscript variable.
906    print(vim.g.foo)  -- Get and print the g:foo Vimscript variable.
907    vim.g.foo = nil   -- Delete (:unlet) the Vimscript variable.
908    vim.b[2].foo = 6  -- Set b:foo for buffer 2
909<
910
911Note that setting dictionary fields directly will not write them back into
912Nvim. This is because the index into the namespace simply returns a copy.
913Instead the whole dictionary must be written as one. This can be achieved by
914creating a short-lived temporary.
915
916Example: >lua
917
918    vim.g.my_dict.field1 = 'value'  -- Does not work
919
920    local my_dict = vim.g.my_dict   --
921    my_dict.field1 = 'value'        -- Instead do
922    vim.g.my_dict = my_dict         --
923
924vim.g                                                                  *vim.g*
925    Global (|g:|) editor variables.
926    Key with no value returns `nil`.
927
928vim.b                                                                  *vim.b*
929    Buffer-scoped (|b:|) variables for the current buffer.
930    Invalid or unset key returns `nil`. Can be indexed with
931    an integer to access variables for a specific buffer.
932
933vim.w                                                                  *vim.w*
934    Window-scoped (|w:|) variables for the current window.
935    Invalid or unset key returns `nil`. Can be indexed with
936    an integer to access variables for a specific window.
937
938vim.t                                                                  *vim.t*
939    Tabpage-scoped (|t:|) variables for the current tabpage.
940    Invalid or unset key returns `nil`. Can be indexed with
941    an integer to access variables for a specific tabpage.
942
943vim.v                                                                  *vim.v*
944    |v:| variables.
945    Invalid or unset key returns `nil`.
946
947                                                                 *lua-options*
948                                                             *lua-vim-options*
949                                                                 *lua-vim-set*
950                                                            *lua-vim-setlocal*
951
952Vim options can be accessed through |vim.o|, which behaves like Vimscript
953|:set|.
954
955    Examples: ~
956
957    To set a boolean toggle:
958        Vimscript: `set number`
959        Lua:       `vim.o.number = true`
960
961    To set a string value:
962        Vimscript: `set wildignore=*.o,*.a,__pycache__`
963        Lua:       `vim.o.wildignore = '*.o,*.a,__pycache__'`
964        Lua (alt): `vim.o.wildignore = { '*.o', '*.a', '__pycache__' }`
965
966    To set a key:value type option:
967        Vimscript: `set listchars=eol:~,space:-`
968        Lua:       `vim.o.listchars = 'eol:~,space:-'`
969        Lua (alt): `vim.o.listchars = { eol = '~', space = '-' }`
970
971Similarly, there is |vim.bo| and |vim.wo| for setting buffer-scoped and
972window-scoped options. Note that this must NOT be confused with
973|local-options| and |:setlocal|. There is also |vim.go| that only accesses the
974global value of a |global-local| option, see |:setglobal|.
975
976                                                               *vim.opt_local*
977                                                              *vim.opt_global*
978                                                                     *vim.opt*
979
980
981A special interface |vim.opt| exists for conveniently interacting with list-
982and map-style options from Lua: It allows accessing them as Lua tables and
983offers object-oriented method for adding and removing entries.
984
985    Examples: ~
986
987    The following methods of setting a list-style option are equivalent:
988        In Vimscript: >vim
989            set wildignore=*.o,*.a,__pycache__
990<
991        In Lua using `vim.o`: >lua
992            vim.o.wildignore = '*.o,*.a,__pycache__'
993<
994        In Lua using `vim.opt`: >lua
995            vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
996<
997    To replicate the behavior of |:set+=|, use: >lua
998
999        vim.opt.wildignore:append { "*.pyc", "node_modules" }
1000<
1001    To replicate the behavior of |:set^=|, use: >lua
1002
1003        vim.opt.wildignore:prepend { "new_first_value" }
1004<
1005    To replicate the behavior of |:set-=|, use: >lua
1006
1007        vim.opt.wildignore:remove { "node_modules" }
1008<
1009    The following methods of setting a map-style option are equivalent:
1010        In Vimscript: >vim
1011            set listchars=space:_,tab:>~
1012<
1013        In Lua using `vim.o`: >lua
1014            vim.o.listchars = 'space:_,tab:>~'
1015<
1016        In Lua using `vim.opt`: >lua
1017            vim.opt.listchars = { space = '_', tab = '>~' }
1018<
1019
1020Note that |vim.opt| returns an `Option` object, not the value of the option,
1021which is accessed through |vim.opt:get()|:
1022
1023    Examples: ~
1024
1025    The following methods of getting a list-style option are equivalent:
1026        In Vimscript: >vim
1027            echo wildignore
1028<
1029        In Lua using `vim.o`: >lua
1030            print(vim.o.wildignore)
1031<
1032        In Lua using `vim.opt`: >lua
1033            vim.print(vim.opt.wildignore:get())
1034<
1035
1036In any of the above examples, to replicate the behavior |:setlocal|, use
1037`vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use
1038`vim.opt_global`.
1039
1040
1041Option:append({value})                                      *vim.opt:append()*
1042    Append a value to string-style options. See |:set+=|
1043
1044    These are equivalent: >lua
1045        vim.opt.formatoptions:append('j')
1046        vim.opt.formatoptions = vim.opt.formatoptions + 'j'
1047<
1048
1049    Parameters: ~
1050      • {value}  (`string`) Value to append
1051
1052Option:get()                                                   *vim.opt:get()*
1053    Returns a Lua-representation of the option. Boolean, number and string
1054    values will be returned in exactly the same fashion.
1055
1056    For values that are comma-separated lists, an array will be returned with
1057    the values as entries in the array: >lua
1058        vim.cmd [[set wildignore=*.pyc,*.o]]
1059
1060        vim.print(vim.opt.wildignore:get())
1061        -- { "*.pyc", "*.o", }
1062
1063        for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
1064            print("Will ignore:", ignore_pattern)
1065        end
1066        -- Will ignore: *.pyc
1067        -- Will ignore: *.o
1068<
1069
1070    For values that are comma-separated maps, a table will be returned with
1071    the names as keys and the values as entries: >lua
1072        vim.cmd [[set listchars=space:_,tab:>~]]
1073
1074        vim.print(vim.opt.listchars:get())
1075        --  { space = "_", tab = ">~", }
1076
1077        for char, representation in pairs(vim.opt.listchars:get()) do
1078            print(char, "=>", representation)
1079        end
1080<
1081
1082    For values that are lists of flags, a set will be returned with the flags
1083    as keys and `true` as entries. >lua
1084        vim.cmd [[set formatoptions=njtcroql]]
1085
1086        vim.print(vim.opt.formatoptions:get())
1087        -- { n = true, j = true, c = true, ... }
1088
1089        local format_opts = vim.opt.formatoptions:get()
1090        if format_opts.j then
1091            print("J is enabled!")
1092        end
1093<
1094
1095    Return: ~
1096        (`string|integer|boolean|string[]|table<string,string|boolean>?`)
1097        value of option
1098
1099Option:prepend({value})                                    *vim.opt:prepend()*
1100    Prepend a value to string-style options. See |:set^=|
1101
1102    These are equivalent: >lua
1103        vim.opt.wildignore:prepend('*.o')
1104        vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
1105<
1106
1107    Parameters: ~
1108      • {value}  (`string`) Value to prepend
1109
1110Option:remove({value})                                      *vim.opt:remove()*
1111    Remove a value from string-style options. See |:set-=|
1112
1113    These are equivalent: >lua
1114        vim.opt.wildignore:remove('*.pyc')
1115        vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
1116<
1117
1118    Parameters: ~
1119      • {value}  (`string`) Value to remove
1120
1121vim.bo[{bufnr}]                                                       *vim.bo*
1122    Gets or sets buffer-scoped |options| on buffer {bufnr} (or "current
1123    buffer" if 0 or omitted). Like `:setlocal`. Invalid {bufnr} or key is an
1124    error.
1125
1126    Example: >lua
1127        local bufnr = vim.api.nvim_get_current_buf()
1128        vim.bo[bufnr].buflisted = true    -- same as vim.bo.buflisted = true
1129        print(vim.bo.comments)
1130        print(vim.bo.baz)                 -- error: invalid key
1131<
1132
1133vim.env                                                              *vim.env*
1134    Gets or sets environment variables in the current editor process. See
1135    |expand-env| and |:let-environment| for the Vimscript behavior. Invalid or
1136    unset key returns `nil`.
1137
1138    Example: >lua
1139        vim.env.FOO = 'bar'
1140        print(vim.env.TERM)
1141<
1142
1143vim.go                                                                *vim.go*
1144    Gets or sets global |options|. Like `:setglobal`. Invalid key is an error.
1145
1146    Note: unlike |vim.o|, this accesses the global option value and thus is
1147    mostly useful with |global-local| options.
1148
1149    Example: >lua
1150        vim.go.cmdheight = 4
1151        print(vim.go.columns)
1152        print(vim.go.bar)     -- error: invalid key
1153<
1154
1155vim.o                                                                  *vim.o*
1156    Gets or sets |options|. Works like `:set`, so buffer/window-scoped options
1157    target the current buffer/window. Invalid key is an error.
1158
1159    Example: >lua
1160        vim.o.cmdheight = 4
1161        print(vim.o.columns)
1162        print(vim.o.foo)     -- error: invalid key
1163<
1164
1165vim.wo[{winid}][{bufnr}]                                              *vim.wo*
1166    Gets or sets window-scoped |options| on window {winid} (or "current
1167    window" if 0 or omitted) and buffer {bufnr} (0 for current buffer). Like
1168    `:setlocal` if setting a |global-local| option or if {bufnr} is specified,
1169    like `:set` otherwise. Invalid {winid}, {bufnr}, or key is an error.
1170
1171    Note: only bufnr=0 (current window-buffer) is supported, currently.
1172
1173    Example: >lua
1174        local winid = vim.api.nvim_get_current_win()
1175        vim.wo[winid].number = true    -- same as vim.wo.number = true
1176        print(vim.wo.foldmarker)
1177        print(vim.wo.quux)             -- error: invalid key
1178        vim.wo[winid][0].spell = false -- like ':setlocal nospell'
1179<
1180
1181
1182==============================================================================
1183Lua module: vim                                                      *lua-vim*
1184
1185*vim.Ringbuf*
1186
1187    Fields: ~
1188      • {clear}  (`fun()`) See |Ringbuf:clear()|.
1189      • {peek}   (`fun(): T?`) See |Ringbuf:peek()|.
1190      • {pop}    (`fun(): T?`) See |Ringbuf:pop()|.
1191      • {push}   (`fun(item: T)`) See |Ringbuf:push()|.
1192
1193
1194Ringbuf:clear()                                              *Ringbuf:clear()*
1195    Clear all items
1196
1197Ringbuf:peek()                                                *Ringbuf:peek()*
1198    Returns the first unread item without removing it
1199
1200    Return: ~
1201        (`T?`)
1202
1203Ringbuf:pop()                                                  *Ringbuf:pop()*
1204    Removes and returns the first unread item
1205
1206    Return: ~
1207        (`T?`)
1208
1209Ringbuf:push({item})                                          *Ringbuf:push()*
1210    Adds an item, overriding the oldest item if the buffer is full.
1211
1212    Parameters: ~
1213      • {item}  (`T`)
1214
1215vim.cmd({cmd})                                                     *vim.cmd()*
1216    Executes Vimscript (|Ex-command|s).
1217
1218    Can be indexed with a command name to get a function, thus you can write
1219    `vim.cmd.echo(…)` instead of `vim.cmd{cmd='echo',…}`.
1220
1221    Examples: >lua
1222        -- Single command:
1223        vim.cmd('echo 42')
1224        -- Multiline script:
1225        vim.cmd([[
1226          augroup my.group
1227            autocmd!
1228            autocmd FileType c setlocal cindent
1229          augroup END
1230        ]])
1231
1232        -- Ex command :echo "foo". Note: string literals must be double-quoted.
1233        vim.cmd('echo "foo"')
1234        vim.cmd { cmd = 'echo', args = { '"foo"' } }
1235        vim.cmd.echo({ args = { '"foo"' } })
1236        vim.cmd.echo('"foo"')
1237
1238        -- Ex command :write! myfile.txt
1239        vim.cmd('write! myfile.txt')
1240        vim.cmd { cmd = 'write', args = { 'myfile.txt' }, bang = true }
1241        vim.cmd.write { args = { 'myfile.txt' }, bang = true }
1242        vim.cmd.write { 'myfile.txt', bang = true }
1243
1244        -- Ex command :vertical resize +2
1245        vim.cmd.resize({ '+2', mods = { vertical = true } })
1246
1247        -- Pass arg literally, without needing to escape special chars:
1248        vim.cmd.edit({ '%foo"|bar#baz"', magic = { file = false, bar = false } })
1249<
1250
1251    Parameters: ~
1252      • {cmd}  (`string|table`) Command(s) to execute.
1253               • The string form supports multiline Vimscript (alias to
1254                 |nvim_exec2()|, behaves like |:source|).
1255               • The table form executes a single command (alias to
1256                 |nvim_cmd()|).
1257
1258    See also: ~
1259      • |ex-cmd-index|
1260
1261vim.deep_equal({a}, {b})                                    *vim.deep_equal()*
1262    Deep compare values for equality
1263
1264    Tables are compared recursively unless they both provide the `eq`
1265    metamethod. All other types are compared using the equality `==` operator.
1266    Cyclic tables are supported.
1267
1268    Parameters: ~
1269      • {a}  (`any`) First value
1270      • {b}  (`any`) Second value
1271
1272    Return: ~
1273        (`boolean`) `true` if values are equals, else `false`
1274
1275vim.deepcopy({orig}, {noref})                                 *vim.deepcopy()*
1276    Returns a deep copy of the given object. Non-table objects are copied as
1277    in a typical Lua assignment, whereas table objects are copied recursively.
1278    Functions are naively copied, so functions in the copied table point to
1279    the same functions as those in the input table. Userdata and threads are
1280    not copied and will throw an error.
1281
1282    Note: `noref=true` is much more performant on tables with unique table
1283    fields, while `noref=false` is more performant on tables that reuse table
1284    fields.
1285
1286    Parameters: ~
1287      • {orig}   (`table`) Table to copy
1288      • {noref}  (`boolean?`) When `false` (default) a contained table is only
1289                 copied once and all references point to this single copy.
1290                 When `true` every occurrence of a table results in a new
1291                 copy. This also means that a cyclic reference can cause
1292                 `deepcopy()` to fail.
1293
1294    Return: ~
1295        (`table`) Table of copied keys and (nested) values.
1296
1297vim.defaulttable({createfn})                              *vim.defaulttable()*
1298    Creates a table whose missing keys are provided by {createfn} (like
1299    Python's "defaultdict").
1300
1301    If {createfn} is `nil` it defaults to defaulttable() itself, so accessing
1302    nested keys creates nested tables: >lua
1303        local a = vim.defaulttable()
1304        a.b.c = 1
1305<
1306
1307    Parameters: ~
1308      • {createfn}  (`fun(key:any):any?`) Provides the value for a missing
1309                    `key`.
1310
1311    Return: ~
1312        (`table`) Empty table with `__index` metamethod.
1313
1314vim.defer_fn({fn}, {timeout})                                 *vim.defer_fn()*
1315    Defers calling {fn} until {timeout} ms passes.
1316
1317    Use to do a one-shot timer that calls {fn}. Note: The {fn} is |schedule|d
1318    automatically, so API functions are safe to call.
1319
1320    Parameters: ~
1321      • {fn}       (`function`) Callback to call once `timeout` expires
1322      • {timeout}  (`integer`) Number of milliseconds to wait before calling
1323                   `fn`
1324
1325    Return: ~
1326        (`uv.uv_timer_t`) timer luv timer object
1327
1328                                                             *vim.deprecate()*
1329vim.deprecate({name}, {alternative}, {version}, {plugin}, {backtrace})
1330    Shows a deprecation message to the user.
1331
1332    Parameters: ~
1333      • {name}         (`string`) Deprecated feature (function, API, etc.).
1334      • {alternative}  (`string?`) Suggested alternative feature.
1335      • {version}      (`string`) Version when the deprecated function will be
1336                       removed.
1337      • {plugin}       (`string?`) Name of the plugin that owns the deprecated
1338                       feature. Defaults to "Nvim".
1339      • {backtrace}    (`boolean?`) Prints backtrace. Defaults to true.
1340
1341    Return: ~
1342        (`string?`) Deprecation message, or nil if no message was shown.
1343
1344vim.endswith({s}, {suffix})                                   *vim.endswith()*
1345    Tests if `s` ends with `suffix`.
1346
1347    Parameters: ~
1348      • {s}       (`string`) String
1349      • {suffix}  (`string`) Suffix to match
1350
1351    Return: ~
1352        (`boolean`) `true` if `suffix` is a suffix of `s`
1353
1354vim.gsplit({s}, {sep}, {opts})                                  *vim.gsplit()*
1355    Gets an |iterator| that splits a string at each instance of a separator,
1356    in "lazy" fashion (as opposed to |vim.split()| which is "eager").
1357
1358    Example: >lua
1359        for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
1360          print(s)
1361        end
1362<
1363
1364    If you want to also inspect the separator itself (instead of discarding
1365    it), use |string.gmatch()|. Example: >lua
1366        for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
1367          print(('word: %s num: %s'):format(word, num))
1368        end
1369<
1370
1371    Parameters: ~
1372      • {s}     (`string`) String to split
1373      • {sep}   (`string`) Separator or pattern
1374      • {opts}  (`table?`) Keyword arguments |kwargs|:
1375                • {plain}? (`boolean`) Use `sep` literally (as in
1376                  string.find).
1377                • {trimempty}? (`boolean`) Discard empty segments at start and
1378                  end of the sequence.
1379
1380    Return: ~
1381        (`fun():string?`) Iterator over the split components
1382
1383    See also: ~
1384      • |string.gmatch()|
1385      • |vim.split()|
1386      • |lua-pattern|s
1387      • https://www.lua.org/pil/20.2.html
1388      • http://lua-users.org/wiki/StringLibraryTutorial
1389
1390vim.inspect({root}, {options})                                 *vim.inspect()*
1391    Gets a human-readable representation of the given object.
1392
1393    Parameters: ~
1394      • {root}     (`any`)
1395      • {options}  (`table?`) A table with the following fields:
1396                   • {depth}? (`integer`, default: unlimited) Maximum table
1397                     nesting depth. Deeper tables are shown as `{...}`.
1398                   • {indent}? (`string`, default: `"  "`) String repeated for
1399                     each level of indentation.
1400                   • {newline}? (`string`, default: `"\n"`) String used for
1401                     line breaks.
1402                   • {process}? (`fun(item: any, path: any[]): any`)
1403                     Transforms values, keys, and metatables before
1404                     formatting. Return a replacement value, or `nil` to omit
1405                     a table entry. {path} lists the keys leading to {item},
1406                     with `vim.inspect.KEY` appended for keys or
1407                     `vim.inspect.METATABLE` for metatables. The root has an
1408                     empty path.
1409
1410    Return: ~
1411        (`string`)
1412
1413    See also: ~
1414      • |vim.print()|
1415      • https://github.com/kikito/inspect.lua
1416      • https://github.com/mpeterv/vinspect
1417
1418vim.is_callable({f})                                       *vim.is_callable()*
1419    Returns true if object `f` can be called as a function.
1420
1421    Parameters: ~
1422      • {f}  (`any?`) Any object
1423
1424    Return: ~
1425        (`boolean`) `true` if `f` is callable, else `false`
1426
1427vim.isarray({t})                                               *vim.isarray()*
1428    Tests if `t` is an "array": a table indexed only by integers (potentially
1429    non-contiguous).
1430
1431    If the indexes start from 1 and are contiguous then the array is also a
1432    list. |vim.islist()|
1433
1434    Empty table `{}` is an array, unless it was created by |vim.empty_dict()|
1435    or returned as a dict-like |API| or Vimscript result, for example from
1436    |rpcrequest()| or |vim.fn|.
1437
1438    Parameters: ~
1439      • {t}  (`any?`)
1440
1441    Return: ~
1442        (`boolean`) `true` if array-like table, else `false`.
1443
1444    See also: ~
1445      • https://github.com/openresty/luajit2#tableisarray
1446
1447vim.islist({t})                                                 *vim.islist()*
1448    Tests if `t` is a "list": a table indexed only by contiguous integers
1449    starting from 1 (what |lua-length| calls a "regular array").
1450
1451    Empty table `{}` is a list, unless it was created by |vim.empty_dict()| or
1452    returned as a dict-like |API| or Vimscript result, for example from
1453    |rpcrequest()| or |vim.fn|.
1454
1455    Parameters: ~
1456      • {t}  (`any?`)
1457
1458    Return: ~
1459        (`boolean`) `true` if list-like table, else `false`.
1460
1461    See also: ~
1462      • |vim.isarray()|
1463
1464vim.isnil({t})                                                   *vim.isnil()*
1465    Tests if `t` is `nil` or |vim.NIL|.
1466
1467    Attributes: ~
1468        Since: 0.13.0
1469
1470    Parameters: ~
1471      • {t}  (`any?`)
1472
1473    Return: ~
1474        (`boolean`) `true` if `nil` or |vim.NIL|, else `false`.
1475
1476vim.keycode({keys}, {info})                                    *vim.keycode()*
1477    Converts keys from |key-notation| to the internal encoding. Optionally
1478    returns structured *key-chord* info as retval 2.
1479
1480    Inverse of |keytrans()|, which converts the internal encoding back to
1481    |key-notation|.
1482
1483    Examples: >lua
1484        local k = vim.keycode
1485        vim.g.mapleader = k'<bs>'
1486
1487        -- Split a key sequence into chords, e.g. to inspect modifiers.
1488        local _, chords = vim.keycode('<C-w>v', true)
1489        assert(chords[1].key == 'w' and chords[1].mod[1] == 'C')
1490
1491        -- keytrans() is the inverse: internal encoding => key-notation.
1492        assert(vim.fn.keytrans(vim.keycode('<C-a>')) == '<C-A>')
1493<
1494
1495    Parameters: ~
1496      • {keys}  (`string`) Keys in |key-notation|.
1497      • {info}  (`boolean?`) Also return key-chord info.
1498
1499    Return (multiple): ~
1500        (`string`) Internal representation of the given `keys`.
1501        (`table?`) List of parsed key-chords, each with fields:
1502        • {key} (`string`) Key without modifiers. Example: `<C-A>` has
1503          `key="a"`.
1504        • {key_alt} (`string?`) Alternative spelling of `key`, or nil if There
1505          Is No Alternative (TINA). Example: `"<"` has `key_alt="lt"`.
1506        • {keys} (`string`) Full key-chord in canonical key-notation (as
1507          produced by |keytrans()|), including modifiers. Example: `<A-f>` has
1508          `keys="<M-f>"`.
1509        • {mod} (`('M'|'T'|'C'|'S'|'2'|'3'|'4'|'D')[]`) List of key-chord
1510          modifiers. Example: `<C-S-f>` has `mod={ 'C', 'S' }`.
1511
1512    See also: ~
1513      • |nvim_replace_termcodes()|
1514      • |keytrans()|
1515
1516vim.list.bisect({t}, {val}, {opts})                        *vim.list.bisect()*
1517    Search for a position in a sorted |lua-list| {t} where {val} can be
1518    inserted while keeping the list sorted.
1519
1520    Use {bound} to determine whether to return the first or the last position,
1521    defaults to "lower", i.e., the first position.
1522
1523    With {opts.key}, {val} may differ from the list elements, provided the key
1524    function accepts both. For a string key, that field must exist on both. A
1525    partial record is sufficient if it contains all fields used by the key.
1526
1527    NOTE: The values being compared must support `<`, and the list must be
1528    sorted by those values (after applying {opts.key}, if provided).
1529
1530    Example: >lua
1531
1532        local t = { 1, 2, 2, 3, 3, 3 }
1533        local first = vim.list.bisect(t, 3)
1534        -- `first` is `val`'s first index if found,
1535        -- useful for existence checks.
1536        print(t[first]) -- 3
1537
1538        local last = vim.list.bisect(t, 3, { bound = 'upper' })
1539        -- Note that `last` is 7, not 6,
1540        -- this is suitable for insertion.
1541
1542        table.insert(t, last, 4)
1543        -- t is now { 1, 2, 2, 3, 3, 3, 4 }
1544
1545        -- You can use lower bound and upper bound together
1546        -- to obtain the range of occurrences of `val`.
1547
1548        -- 3 is in [first, last)
1549        for i = first, last - 1 do
1550          print(t[i]) -- { 3, 3, 3 }
1551        end
1552<
1553
1554    Attributes: ~
1555        Since: 0.12.0
1556
1557    Parameters: ~
1558      • {t}     (`any[]`) A sorted list.
1559      • {val}   (`any`) The value to search.
1560      • {opts}  (`table?`) A table with the following fields:
1561                • {bound}? (`'lower'|'upper'`, default: `'lower'`) Specifies
1562                  the search variant.
1563                  • "lower": returns the first position where inserting {val}
1564                    keeps the list sorted.
1565                  • "upper": returns the last position where inserting {val}
1566                    keeps the list sorted..
1567                • {hi}? (`integer`, default: `#t + 1`) End index of the list,
1568                  exclusive.
1569                • {key}? (`(string & keyof T)|fun(val: T): any`) Applied to
1570                  {val} and the list elements being compared. If a string,
1571                  index both by this field name. If a function, it must accept
1572                  both {val} and the list elements and return mutually
1573                  comparable keys.
1574                • {lo}? (`integer`, default: `1`) Start index of the list.
1575
1576    Overloads: ~
1577      • `fun<T, Q>(t: T[], val: Q, opts: vim.list.bisect.Opts<T|Q> & { key: fun(val: T|Q): any }): integer`
1578      • `fun<T: table, Q: table>(t: T[], val: Q, opts: vim.list.bisect.Opts<T|Q> & { key: string & keyof T & keyof Q }): integer`
1579
1580    Return: ~
1581        (`integer`) index serves as either the lower bound or the upper bound
1582        position.
1583
1584vim.list.unique({t}, {key})                                *vim.list.unique()*
1585    Removes duplicate values from a |lua-list| in-place.
1586
1587    Only the first occurrence of each value is kept. The operation is
1588    performed in-place and the input table is modified.
1589
1590    Accepts an optional `key` argument, which if provided is called for each
1591    value in the list to compute a hash key for uniqueness comparison. If
1592    `key` is a string, it is used as the field name to index each value. This
1593    is useful for deduplicating table values or complex objects. If `key`
1594    returns `nil` for a value, that value will be considered unique, even if
1595    multiple values return `nil`.
1596
1597    Example: >lua
1598
1599        local t = {1, 2, 2, 3, 1}
1600        vim.list.unique(t)
1601        -- t is now {1, 2, 3}
1602
1603        local t = { {id=1}, {id=2}, {id=1} }
1604        vim.list.unique(t, 'id')
1605        -- t is now { {id=1}, {id=2} }
1606<
1607
1608    Attributes: ~
1609        Since: 0.12.0
1610
1611    Parameters: ~
1612      • {t}    (`any[]`)
1613      • {key}  (`string|fun(x: T): any?`) Optional field name or hash function
1614               to determine uniqueness of values
1615
1616    Return: ~
1617        (`any[]`) The deduplicated list
1618
1619    See also: ~
1620      • |Iter:unique()|
1621
1622vim.list_contains({t}, {value})                          *vim.list_contains()*
1623    Checks if a list-like table (integer keys without gaps) contains `value`.
1624
1625    Parameters: ~
1626      • {t}      (`table`) Table to check (must be list-like, not validated)
1627      • {value}  (`any`) Value to compare
1628
1629    Return: ~
1630        (`boolean`) `true` if `t` contains `value`
1631
1632    See also: ~
1633      • |vim.tbl_contains()| for checking values in general tables
1634
1635vim.list_extend({dst}, {src}, {start}, {finish})           *vim.list_extend()*
1636    Extends a list-like table with the values of another list-like table.
1637
1638    NOTE: This mutates dst!
1639
1640    Parameters: ~
1641      • {dst}     (`table`) List which will be modified and appended to
1642      • {src}     (`table`) List from which values will be inserted
1643      • {start}   (`integer?`) Start index on src. Defaults to 1
1644      • {finish}  (`integer?`) Final index on src. Defaults to `#src`
1645
1646    Return: ~
1647        (`table`) dst
1648
1649    See also: ~
1650      • |vim.tbl_extend()|
1651
1652vim.list_slice({list}, {start}, {finish})                   *vim.list_slice()*
1653    Creates a copy of a table containing only elements from start to end
1654    (inclusive)
1655
1656    Parameters: ~
1657      • {list}    (`any[]`) Table
1658      • {start}   (`integer?`) Start range of slice
1659      • {finish}  (`integer?`) End range of slice
1660
1661    Return: ~
1662        (`any[]`) Copy of table sliced from start to finish (inclusive)
1663
1664vim.lua_omnifunc({find_start})                            *vim.lua_omnifunc()*
1665    Omnifunc for completing Lua values from the runtime Lua interpreter,
1666    similar to the builtin completion for the `:lua` command.
1667
1668    Activate using `vim.bo.omnifunc = vim.lua_omnifunc` in a Lua buffer.
1669
1670    Parameters: ~
1671      • {find_start}  (`1|0`)
1672
1673vim.nonnil({...})                                               *vim.nonnil()*
1674    Returns the first argument which is not nil.
1675
1676    If all arguments are nil, returns nil.
1677
1678    Example: >lua
1679        local a = nil
1680        local b = nil
1681        local c = 42
1682        local d = true
1683        assert(vim.nonnil(a, b, c, d) == 42)
1684<
1685
1686    Attributes: ~
1687        Since: 0.13.0
1688
1689    Parameters: ~
1690      • {...}  (`any`)
1691
1692    Return: ~
1693        (`any`)
1694
1695vim.notify({msg}, {level}, {opts})                              *vim.notify()*
1696    Displays a notification to the user.
1697
1698    This function can be overridden by plugins to display notifications using
1699    a custom provider (such as the system notification provider). By default,
1700    writes to |:messages|.
1701
1702    Parameters: ~
1703      • {msg}    (`string`) Content of the notification to show to the user.
1704      • {level}  (`integer?`) One of the values from |vim.log.levels|.
1705      • {opts}   (`table?`) Optional parameters. Unused by default.
1706
1707vim.notify_once({msg}, {level}, {opts})                    *vim.notify_once()*
1708    Displays a notification only one time.
1709
1710    Like |vim.notify()|, but subsequent calls with the same message will not
1711    display a notification.
1712
1713    Parameters: ~
1714      • {msg}    (`string`) Content of the notification to show to the user.
1715      • {level}  (`integer?`) One of the values from |vim.log.levels|.
1716      • {opts}   (`table?`) Optional parameters. Unused by default.
1717
1718    Return: ~
1719        (`boolean`) true if message was displayed, else false
1720
1721vim.npcall({fn}, {...})                                         *vim.npcall()*
1722    Calls the function `fn` in `protected mode` like |pcall()|, but returns
1723    `nil` on error.
1724
1725    Attributes: ~
1726        Since: 0.13.0
1727
1728    Parameters: ~
1729      • {fn}   (`fun(...):T`)
1730      • {...}  (`any?`)
1731
1732    Return: ~
1733        (`any`) ...
1734
1735vim.on_key({fn}, {ns_id}, {opts})                               *vim.on_key()*
1736    Registers function {fn} with |namespace| {ns_id} as a listener to EVERY
1737    input key (except keys consumed by |getchar()|, by {fn} itself, or by a
1738    <Cmd> payload).
1739
1740    To parse |key-chord|s, see |vim.keycode()|. Example: >lua
1741        local keychords = vim.keycode(vim.fn.keytrans(key), true)
1742<
1743
1744    Note: ~
1745      • If {fn} returns an empty string, {key} is discarded/ignored; if {key}
1746        is <Cmd> then the "<Cmd>…<CR>" sequence is discarded as a whole.
1747      • Non-recursive: if {fn} itself consumes input, it won't be invoked for
1748        those keys.
1749      • Not invoked for keys consumed by getchar()/getcharstr(): they never
1750        reach the main loop.
1751      • To UNregister a given {ns_id}, pass `nil` {fn}.
1752      • {fn} will be removed on error.
1753      • {fn} will not be cleared by |nvim_buf_clear_namespace()|
1754      • The |-w| command-line option is related but does not support callbacks
1755        and cannot be toggled dynamically.
1756
1757    Parameters: ~
1758      • {fn}     (`fun(key: string, typed: string): string??`) Function
1759                 invoked for every input key, after mappings have been applied
1760                 but before further processing. Arguments {key} and {typed}
1761                 are raw input (use |keytrans()| to get |keycodes|).
1762                 • {key} is the key after mappings are applied.
1763                 • {typed} is the input before mappings are applied; may be
1764                   empty if {key} was produced by non-typed key(s) or by the
1765                   same typed key(s) that produced a previous {key}.
1766      • {ns_id}  (`integer?`) Namespace ID. If nil or 0, returns a new
1767                 |namespace| id.
1768      • {opts}   (`table?`) Optional parameters
1769
1770    Return: ~
1771        (`integer`) Namespace id associated with {fn}. Or count of all
1772        callbacks if on_key() is called without arguments.
1773
1774    See also: ~
1775      • |keytrans()|
1776      • |vim.keycode()|
1777
1778vim.paste({lines}, {phase})                                      *vim.paste()*
1779    Paste handler, invoked by |nvim_paste()|.
1780
1781    Note: This is provided only as a "hook", don't call it directly; call
1782    |nvim_paste()| instead, which arranges redo (dot-repeat) and invokes
1783    `vim.paste`.
1784
1785    Example: To remove ANSI color codes when pasting: >lua
1786        vim.paste = (function(overridden)
1787          return function(lines, phase)
1788            for i,line in ipairs(lines) do
1789              -- Scrub ANSI color codes from paste input.
1790              lines[i] = line:gsub('\27%[[0-9;mK]+', '')
1791            end
1792            return overridden(lines, phase)
1793          end
1794        end)(vim.paste)
1795<
1796
1797    Parameters: ~
1798      • {lines}  (`string[]`) |readfile()|-style list of lines to paste.
1799                 |channel-lines|
1800      • {phase}  (`-1|1|2|3`) -1: "non-streaming" paste: the call contains all
1801                 lines. If paste is "streamed", `phase` indicates the stream
1802                 state:
1803                 • 1: starts the paste (exactly once)
1804                 • 2: continues the paste (zero or more times)
1805                 • 3: ends the paste (exactly once)
1806
1807    Return: ~
1808        (`boolean`) result false if client should cancel the paste.
1809
1810    See also: ~
1811      • |paste|
1812
1813vim.pesc({s})                                                     *vim.pesc()*
1814    Escapes magic chars in |lua-pattern|s.
1815
1816    Parameters: ~
1817      • {s}  (`string`) String to escape
1818
1819    Return: ~
1820        (`string`) %-escaped pattern string
1821
1822    See also: ~
1823      • https://github.com/rxi/lume
1824
1825vim.print({...})                                                 *vim.print()*
1826    "Pretty prints" the given arguments and returns them unmodified.
1827
1828    Example: >lua
1829        local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
1830<
1831
1832    Parameters: ~
1833      • {...}  (`any`)
1834
1835    Return: ~
1836        (`any`) given arguments.
1837
1838    See also: ~
1839      • |vim.inspect()|
1840      • |:=|
1841
1842vim.ringbuf({size})                                            *vim.ringbuf()*
1843    Create a ring buffer limited to a maximal number of items. Once the buffer
1844    is full, adding a new entry overrides the oldest entry. >lua
1845        local ringbuf = vim.ringbuf(4)
1846        ringbuf:push("a")
1847        ringbuf:push("b")
1848        ringbuf:push("c")
1849        ringbuf:push("d")
1850        ringbuf:push("e")    -- overrides "a"
1851        print(ringbuf:pop()) -- returns "b"
1852        print(ringbuf:pop()) -- returns "c"
1853
1854        -- Can be used as iterator. Pops remaining items:
1855        for val in ringbuf do
1856          print(val)
1857        end
1858<
1859
1860    Returns a Ringbuf instance with the following methods:
1861    • |Ringbuf:push()|
1862    • |Ringbuf:pop()|
1863    • |Ringbuf:peek()|
1864    • |Ringbuf:clear()|
1865
1866    Parameters: ~
1867      • {size}  (`integer`)
1868
1869    Return: ~
1870        (`vim.Ringbuf<any>`) ringbuf
1871
1872vim.schedule_wrap({fn})                                  *vim.schedule_wrap()*
1873    Returns a function which calls {fn} via |vim.schedule()|.
1874
1875    The returned function passes all arguments to {fn}.
1876
1877    Example: >lua
1878        function notify_readable(_err, readable)
1879          vim.notify("readable? " .. tostring(readable))
1880        end
1881        vim.uv.fs_access(vim.fn.stdpath("config"), "R", vim.schedule_wrap(notify_readable))
1882<
1883
1884    Parameters: ~
1885      • {fn}  (`function`)
1886
1887    Return: ~
1888        (`function`)
1889
1890    See also: ~
1891      • |lua-loop-callbacks|
1892      • |vim.schedule()|
1893      • |vim.in_fast_event()|
1894
1895vim.spairs({t})                                                 *vim.spairs()*
1896    Enumerates key-value pairs of a table, ordered by key.
1897
1898    Parameters: ~
1899      • {t}  (`table`) Dict-like table
1900
1901    Return (multiple): ~
1902        (`fun(table: table<K, V>, index?: K):K, V`) |for-in| iterator over
1903        sorted keys and their values
1904        (`table`)
1905
1906    See also: ~
1907      • Based on
1908        https://github.com/premake/premake-core/blob/master/src/base/table.lua
1909
1910vim.split({s}, {sep}, {opts})                                    *vim.split()*
1911    Splits a string at each instance of a separator and returns the result as
1912    a table (unlike |vim.gsplit()|).
1913
1914    Examples: >lua
1915        split(":aa::b:", ":")                   --> {'','aa','','b',''}
1916        split("axaby", "ab?")                   --> {'','x','y'}
1917        split("x*yz*o", "*", {plain=true})      --> {'x','yz','o'}
1918        split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
1919<
1920
1921    Parameters: ~
1922      • {s}     (`string`) String to split
1923      • {sep}   (`string`) Separator or pattern
1924      • {opts}  (`table?`) Keyword arguments |kwargs|:
1925                • {plain}? (`boolean`) Use `sep` literally (as in
1926                  string.find).
1927                • {trimempty}? (`boolean`) Discard empty segments at start and
1928                  end of the sequence.
1929
1930    Return: ~
1931        (`string[]`) List of split components
1932
1933    See also: ~
1934      • |vim.gsplit()|
1935      • |string.gmatch()|
1936
1937vim.startswith({s}, {prefix})                               *vim.startswith()*
1938    Tests if `s` starts with `prefix`.
1939
1940    Parameters: ~
1941      • {s}       (`string`) String
1942      • {prefix}  (`string`) Prefix to match
1943
1944    Return: ~
1945        (`boolean`) `true` if `prefix` is a prefix of `s`
1946
1947                                                         *vim.str_byteindex()*
1948vim.str_byteindex({s}, {encoding}, {index}, {strict_indexing})
1949    Convert UTF-32, UTF-16 or UTF-8 {index} to byte index. If
1950    {strict_indexing} is false then an out of range index will return byte
1951    length instead of throwing an error.
1952
1953    Invalid UTF-8 and NUL is treated like in |vim.str_utfindex()|. An {index}
1954    in the middle of a UTF-16 sequence is rounded upwards to the end of that
1955    sequence.
1956
1957    Parameters: ~
1958      • {s}                (`string`)
1959      • {encoding}         (`"utf-8"|"utf-16"|"utf-32"`)
1960      • {index}            (`integer`)
1961      • {strict_indexing}  (`boolean?`) default: true
1962
1963    Return: ~
1964        (`integer`)
1965
1966                                                          *vim.str_utfindex()*
1967vim.str_utfindex({s}, {encoding}, {index}, {strict_indexing})
1968    Convert byte index to UTF-32, UTF-16 or UTF-8 indices. If {index} is not
1969    supplied, the length of the string is used. All indices are zero-based.
1970
1971    If {strict_indexing} is false then an out of range index will return
1972    string length instead of throwing an error. Invalid UTF-8 bytes, and
1973    embedded surrogates are counted as one code point each. An {index} in the
1974    middle of a UTF-8 sequence is rounded upwards to the end of that sequence.
1975
1976    Parameters: ~
1977      • {s}                (`string`)
1978      • {encoding}         (`"utf-8"|"utf-16"|"utf-32"`)
1979      • {index}            (`integer?`)
1980      • {strict_indexing}  (`boolean?`) default: true
1981
1982    Return: ~
1983        (`integer`)
1984
1985vim.tbl_contains({t}, {value}, {opts})                    *vim.tbl_contains()*
1986    Checks if a table contains a given value, specified either directly or via
1987    a predicate that is checked for each value.
1988
1989    Example: >lua
1990        vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
1991          return vim.deep_equal(v, { 'b', 'c' })
1992        end, { predicate = true })
1993        -- true
1994<
1995
1996    Parameters: ~
1997      • {t}      (`table`) Table to check
1998      • {value}  (`any`) Value to compare or predicate function reference
1999      • {opts}   (`table?`) Keyword arguments |kwargs|:
2000                 • {predicate}? (`boolean`, default: false) `value` is a
2001                   function reference to be checked
2002
2003    Return: ~
2004        (`boolean`) `true` if `t` contains `value`
2005
2006    See also: ~
2007      • |vim.list_contains()| for checking values in list-like tables
2008
2009vim.tbl_count({t})                                           *vim.tbl_count()*
2010    Counts the number of non-nil values in table `t`. >lua
2011        vim.tbl_count({ a=1, b=2 })  --> 2
2012        vim.tbl_count({ 1, 2 })      --> 2
2013<
2014
2015    Parameters: ~
2016      • {t}  (`table`) Table
2017
2018    Return: ~
2019        (`integer`) Number of non-nil values in table
2020
2021    See also: ~
2022      • https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
2023
2024vim.tbl_deep_extend({behavior}, {...})                 *vim.tbl_deep_extend()*
2025    Merges two or more tables recursively.
2026
2027    Only |lua-dict| tables are merged recursively; |lua-list| tables are
2028    treated as opaque values (overwritten instead of merged). That is
2029    convenient for merging default/user configurations where lists typically
2030    should not be merged together.
2031
2032    Example: >lua
2033        -- Set `config.settings.…` without worrying about whether intermediate dicts exist.
2034        local config = { settings = { tailwindCSS = { foo = 'bar' } } }
2035        local merged = vim.tbl_deep_extend('force',
2036          config,
2037          { settings = { tailwindCSS = { experimental = { configFile = '/my/config.json' } } } }
2038        )
2039        vim.print(merged)
2040<
2041
2042    Parameters: ~
2043      • {behavior}  (`'error'|'keep'|'force'|fun(key:any, prev_value:any?, value:any): any`)
2044                    Decides what to do if a key is found in more than one map:
2045                    • "error": raise an error
2046                    • "force": use value from the rightmost map
2047                    • "keep": use value from the leftmost map
2048                    • If a function, it receives the current key, the previous
2049                      value in the currently merged table (if present), the
2050                      current value and should return the value for the given
2051                      key in the merged table.
2052      • {...}       (`table`) Two or more tables
2053
2054    Return: ~
2055        (`table`) Merged table
2056
2057    See also: ~
2058      • |vim.tbl_extend()|
2059
2060vim.tbl_extend({behavior}, {...})                           *vim.tbl_extend()*
2061    Merges two or more tables.
2062
2063    Parameters: ~
2064      • {behavior}  (`'error'|'keep'|'force'|fun(key:any, prev_value:any?, value:any): any`)
2065                    Decides what to do if a key is found in more than one map:
2066                    • "error": raise an error
2067                    • "force": use value from the rightmost map
2068                    • "keep": use value from the leftmost map
2069                    • If a function, it receives the current key, the previous
2070                      value in the currently merged table (if present), the
2071                      current value and should return the value for the given
2072                      key in the merged table.
2073      • {...}       (`table`) Two or more tables
2074
2075    Return: ~
2076        (`table`) Merged table
2077
2078    See also: ~
2079      • |extend()|
2080
2081vim.tbl_filter({fn}, {t})                                   *vim.tbl_filter()*
2082    Filter a table using a predicate function
2083
2084    Parameters: ~
2085      • {fn}  (`function`) Function
2086      • {t}   (`table`) Table
2087
2088    Return: ~
2089        (`any[]`) Table of filtered values
2090
2091vim.tbl_get({o}, {...})                                        *vim.tbl_get()*
2092    Gets a (nested) value from table `o` given by a sequence of keys `...`, or
2093    `nil` if not found.
2094
2095    Note: To set deeply nested keys, see |vim.tbl_deep_extend()|.
2096
2097    Example: >lua
2098        local o = { a = { b = true } }
2099        -- Get `o.a.b`.
2100        vim.print(vim.tbl_get(o, 'a', 'b')) -- true
2101        o.a = {}
2102        vim.print(vim.tbl_get(o, 'a', 'b')) -- nil
2103<
2104
2105    Parameters: ~
2106      • {o}    (`table`) Table to index
2107      • {...}  (`any`) Optional keys (0 or more, variadic) via which to index
2108               the table
2109
2110    Return: ~
2111        (`any`) Nested value indexed by key (if it exists), else nil
2112
2113    See also: ~
2114      • |unpack()|
2115      • |vim.tbl_deep_extend()|
2116
2117vim.tbl_isempty({t})                                       *vim.tbl_isempty()*
2118    Checks if a table is empty.
2119
2120    Parameters: ~
2121      • {t}  (`table`) Table to check
2122
2123    Return: ~
2124        (`boolean`) `true` if `t` is empty
2125
2126    See also: ~
2127      • https://github.com/premake/premake-core/blob/master/src/base/table.lua
2128
2129vim.tbl_keys({t})                                             *vim.tbl_keys()*
2130    Return a list of all keys used in a table. However, the order of the
2131    return table of keys is not guaranteed.
2132
2133    Parameters: ~
2134      • {t}  (`table`) Table
2135
2136    Return: ~
2137        (`any[]`) List of keys
2138
2139    See also: ~
2140      • From
2141        https://github.com/premake/premake-core/blob/master/src/base/table.lua
2142
2143vim.tbl_map({fn}, {t})                                         *vim.tbl_map()*
2144    Applies function `fn` to all values of table `t`, in `pairs()` iteration
2145    order (which is not guaranteed to be stable, even when the data doesn't
2146    change).
2147
2148    Parameters: ~
2149      • {fn}  (`fun(value: T): R`) Function
2150      • {t}   (`table<any, T>`) Table
2151
2152    Return: ~
2153        (`table<any, R>`) Table of transformed values
2154
2155vim.tbl_values({t})                                         *vim.tbl_values()*
2156    Return a list of all values used in a table. However, the order of the
2157    return table of values is not guaranteed.
2158
2159    Parameters: ~
2160      • {t}  (`table`) Table
2161
2162    Return: ~
2163        (`any[]`) List of values
2164
2165vim.trim({s})                                                     *vim.trim()*
2166    Trim whitespace (Lua pattern "%s") from both sides of a string.
2167
2168    Parameters: ~
2169      • {s}  (`string`) String to trim
2170
2171    Return: ~
2172        (`string`) String with whitespace removed from its beginning and end
2173
2174    See also: ~
2175      • |lua-pattern|s
2176      • https://www.lua.org/pil/20.2.html
2177
2178                                                              *vim.validate()*
2179vim.validate({name}, {value}, {validator}, {optional}, {message})
2180    Validate function arguments.
2181
2182    This function has two valid forms:
2183    1. `vim.validate(name, value, validator[, optional][, message])`
2184       Validates that argument {name} with value {value} satisfies
2185       {validator}. If {optional} is given and is `true`, then {value} may be
2186       `nil`. If {message} is given, then it is used as the expected type in
2187       the error message.
2188       Example: >lua
2189         function vim.startswith(s, prefix)
2190          vim.validate('s', s, 'string')
2191          vim.validate('prefix', prefix, 'string')
2192          -- ...
2193        end
2194<
2195    2. `vim.validate(spec)` (DEPRECATED) where `spec` is of type
2196       `table<string,[value:any, validator: vim.validate.Validator, optional_or_msg? : boolean|string]>)`
2197       Validates a argument specification. Specs are evaluated in alphanumeric
2198       order, until the first failure.
2199
2200    Examples: >lua
2201        vim.validate('arg1', {'foo'}, 'table')
2202           --> NOP (success)
2203        vim.validate('arg2', 'foo', 'string')
2204           --> NOP (success)
2205
2206        vim.validate('arg1', 1, 'table')
2207           --> error('arg1: expected table, got number')
2208
2209        vim.validate('arg1', 3, function(a) return (a % 2) == 0 end, 'even number')
2210           --> error('arg1: expected even number, got 3')
2211
2212        -- If multiple types are valid they can be given as a list:
2213        vim.validate('arg1', {'foo'}, {'table', 'string'})
2214        vim.validate('arg2', 'foo', {'table', 'string'})
2215        -- NOP (success)
2216        vim.validate('arg1', 1, {'string', 'table'})
2217        -- error('arg1: expected string|table, got number')
2218<
2219
2220    Note: ~
2221      • `validator` set to a value returned by |lua-type()| provides the best
2222        performance.
2223
2224    Parameters: ~
2225      • {name}       (`string`) Argument name
2226      • {value}      (`any`) Argument value
2227      • {validator}  (`vim.validate.Validator`)
2228                     • (`string|string[]`): Any value that can be returned
2229                       from |lua-type()| in addition to `'callable'`:
2230                       `'boolean'`, `'callable'`, `'function'`, `'nil'`,
2231                       `'number'`, `'string'`, `'table'`, `'thread'`,
2232                       `'userdata'`.
2233                     • (`fun(val:any): boolean, string?`) A function that
2234                       returns a boolean and an optional string message.
2235      • {optional}   (`boolean?`) (default: false) Parameter is optional (may
2236                     be omitted or nil)
2237      • {message}    (`string?`) message when validation fails
2238
2239    Overloads: ~
2240      • `fun(name: string, val: any, validator: vim.validate.Validator, message: string)`
2241      • `fun(spec: table<string,[any, vim.validate.Validator, boolean|string]>)`
2242
2243vim.wait({time}, {callback}, {interval}, {fast_only})             *vim.wait()*
2244    Waits up to `time` milliseconds, until `callback` returns `true`
2245    (success). Executes `callback` immediately, then on user events, internal
2246    events, and approximately every `interval` milliseconds (default 200).
2247    Returns `true` plus any remaining callback results on success.
2248
2249    Nvim processes other events while waiting. Cannot be called during an
2250    |api-fast| event.
2251
2252    Examples: >lua
2253        -- Wait for 100 ms, allowing other events to process.
2254        vim.wait(100)
2255
2256        -- Wait up to 1000 ms or until `vim.g.foo` is true, at intervals of ~500 ms.
2257        vim.wait(1000, function() return vim.g.foo end, 500)
2258
2259        -- Wait indefinitely until `vim.g.foo` is true, and get the callback results.
2260        local ok, rv1, rv2, rv3 = vim.wait(math.huge, function()
2261          return vim.g.foo, 'a', 42, { ok = { 'yes' } }
2262        end)
2263
2264        -- Schedule a function to set a value in 100ms. This would wait 10s if blocked, but actually
2265        -- only waits 100ms because `vim.wait` processes other events while waiting.
2266        vim.defer_fn(function() vim.g.timer_result = true end, 100)
2267        if vim.wait(10000, function() return vim.g.timer_result end) then
2268          print('Only waiting a little bit of time!')
2269        end
2270
2271        -- Yield via vim.wait() to allow CTRL-C to interrupt Lua code.
2272        while true do
2273          -- ...work...
2274          local _, code = vim.wait(0, nil, 0)
2275          if code == -2 then -- CTRL-C.
2276            break
2277          end
2278        end
2279<
2280
2281    Parameters: ~
2282      • {time}       (`number`) Number of milliseconds to wait. Must be
2283                     non-negative number, any fractional part is truncated.
2284      • {callback}   (`fun(): boolean, ...?`) Optional callback. Waits until
2285                     {callback} returns true
2286      • {interval}   (`integer?`) (Approximate) number of milliseconds to wait
2287                     between polls
2288      • {fast_only}  (`boolean?`) If true, only |api-fast| events will be
2289                     processed.
2290
2291    Return (multiple): ~
2292        (`boolean`)
2293        (`-1|-2?`)
2294        • If callback returns `true` before timeout: `true, ...` (remaining
2295          callback results).
2296        • On timeout: `false, -1`
2297        • On interrupt: `false, -2`
2298        • On error: the error is raised.
2299
2300
2301==============================================================================
2302Lua module: vim.inspector                                      *vim.inspector*
2303
2304vim.inspect_pos({buf}, {row}, {col}, {filter})             *vim.inspect_pos()*
2305    Get all the items at a given buffer position.
2306
2307    Can also be pretty-printed with `:Inspect!`.                   *:Inspect!*
2308
2309    Attributes: ~
2310        Since: 0.9.0
2311
2312    Parameters: ~
2313      • {buf}     (`integer?`) defaults to the current buffer
2314      • {row}     (`integer?`) row to inspect, 0-based. Defaults to the row of
2315                  the current cursor
2316      • {col}     (`integer?`) col to inspect, 0-based. Defaults to the col of
2317                  the current cursor
2318      • {filter}  (`table?`) Table with key-value pairs to filter the items
2319                  • {extmarks} (`boolean|"all"`, default: true) Include
2320                    extmarks. When `all`, then extmarks without a `hl_group`
2321                    will also be included.
2322                  • {semantic_tokens} (`boolean`, default: true) Include
2323                    semantic token highlights.
2324                  • {syntax} (`boolean`, default: `true`) Include syntax based
2325                    highlight groups.
2326                  • {treesitter} (`boolean`, default: `true`) Include
2327                    treesitter based highlight groups.
2328
2329    Return: ~
2330        (`table`) a table with the following key-value pairs. Items are in
2331        "traversal order":
2332        • treesitter: a list of treesitter captures
2333        • syntax: a list of syntax groups
2334        • semantic_tokens: a list of semantic tokens
2335        • extmarks: a list of extmarks
2336        • buffer: the buffer used to get the items
2337        • row: the row used to get the items
2338        • col: the col used to get the items
2339
2340vim.show_pos({buf}, {row}, {col}, {filter})                   *vim.show_pos()*
2341    Show all the items at a given buffer position.
2342
2343    Can also be shown with `:Inspect`.                              *:Inspect*
2344
2345    See also |:marks| to list all extmarks.
2346
2347    Example: To bind this function to the vim-scriptease inspired `zS` in
2348    Normal mode: >lua
2349        vim.keymap.set('n', 'zS', vim.show_pos)
2350<
2351
2352    Attributes: ~
2353        Since: 0.9.0
2354
2355    Parameters: ~
2356      • {buf}     (`integer?`) defaults to the current buffer
2357      • {row}     (`integer?`) row to inspect, 0-based. Defaults to the row of
2358                  the current cursor
2359      • {col}     (`integer?`) col to inspect, 0-based. Defaults to the col of
2360                  the current cursor
2361      • {filter}  (`table?`) A table with the following fields:
2362                  • {extmarks} (`boolean|"all"`, default: true) Include
2363                    extmarks. When `all`, then extmarks without a `hl_group`
2364                    will also be included.
2365                  • {semantic_tokens} (`boolean`, default: true) Include
2366                    semantic token highlights.
2367                  • {syntax} (`boolean`, default: `true`) Include syntax based
2368                    highlight groups.
2369                  • {treesitter} (`boolean`, default: `true`) Include
2370                    treesitter based highlight groups.
2371
2372
2373==============================================================================
2374Lua module: vim.base64                                            *vim.base64*
2375
2376vim.base64.decode({str})                                 *vim.base64.decode()*
2377    Decode a Base64 encoded string.
2378
2379    Parameters: ~
2380      • {str}  (`string`) Base64 encoded string
2381
2382    Return: ~
2383        (`string`) Decoded string
2384
2385vim.base64.encode({str})                                 *vim.base64.encode()*
2386    Encode {str} using Base64.
2387
2388    Parameters: ~
2389      • {str}  (`string`) String to encode
2390
2391    Return: ~
2392        (`string`) Encoded string
2393
2394
2395==============================================================================
2396Lua module: vim.filetype                                        *vim.filetype*
2397
2398vim.filetype.add({filetypes})                             *vim.filetype.add()*
2399    Add new filetype mappings.
2400
2401    Filetype mappings can be added either by extension or by filename (either
2402    the "tail" or the full file path). The full file path is checked first,
2403    followed by the file name. If a match is not found using the filename,
2404    then the filename is matched against the list of |lua-pattern|s (sorted by
2405    priority) until a match is found. Lastly, if pattern matching does not
2406    find a filetype, then the file extension is used. Extension mappings match
2407    only the text after the final dot in the filename.
2408
2409    The filetype can be either a string (in which case it is used as the
2410    filetype directly) or a function. If a function, it takes the full path
2411    and buffer number of the file as arguments (along with captures from the
2412    matched pattern, if any) and should return a string that will be used as
2413    the buffer's filetype. Optionally, the function can return a second
2414    function value which, when called, modifies the state of the buffer. This
2415    can be used to, for example, set filetype-specific buffer variables. This
2416    function will be called by Nvim before setting the buffer's filetype.
2417
2418    Filename patterns can specify an optional priority to resolve cases when a
2419    file path matches multiple patterns. Higher priorities are matched first.
2420    When omitted, the priority defaults to 0. A pattern can contain
2421    environment variables of the form "${SOME_VAR}" that will be automatically
2422    expanded. If the environment variable is not set, the pattern won't be
2423    matched.
2424
2425    See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
2426
2427    Example: >lua
2428        vim.filetype.add({
2429          extension = {
2430            foo = 'fooscript',
2431            bar = function(path, bufnr)
2432              if some_condition() then
2433                return 'barscript', function(bufnr)
2434                  -- Set a buffer variable
2435                  vim.b[bufnr].barscript_version = 2
2436                end
2437              end
2438              return 'bar'
2439            end,
2440          },
2441          filename = {
2442            ['.foorc'] = 'toml',
2443            ['/etc/foo/config'] = 'toml',
2444          },
2445          pattern = {
2446            ['.*/etc/foo/.*'] = 'fooscript',
2447            -- Using an optional priority
2448            ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } },
2449            -- A pattern containing an environment variable
2450            ['${XDG_CONFIG_HOME}/foo/git'] = 'git',
2451            ['.*README.(%a+)'] = function(path, bufnr, ext)
2452              if ext == 'md' then
2453                return 'markdown'
2454              elseif ext == 'rst' then
2455                return 'rst'
2456              end
2457            end,
2458          },
2459        })
2460<
2461
2462    To add a fallback match on contents, use >lua
2463        vim.filetype.add {
2464          pattern = {
2465            ['.*'] = {
2466              function(path, bufnr)
2467                local content = vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] or ''
2468                if vim.regex([[^#!.*\\<mine\\>]]):match_str(content) ~= nil then
2469                  return 'mine'
2470                elseif vim.regex([[\\<drawing\\>]]):match_str(content) ~= nil then
2471                  return 'drawing'
2472                end
2473              end,
2474              { priority = -math.huge },
2475            },
2476          },
2477        }
2478<
2479
2480    Parameters: ~
2481      • {filetypes}  (`table`) A table containing new filetype maps (see
2482                     example).
2483                     • {extension}? (`vim.filetype.mapping`)
2484                     • {filename}? (`vim.filetype.mapping`)
2485                     • {pattern}? (`vim.filetype.mapping`)
2486
2487                                                   *vim.filetype.get_option()*
2488vim.filetype.get_option({filetype}, {option})
2489    Get the default option value for a {filetype}.
2490
2491    The returned value is what would be set in a new buffer after 'filetype'
2492    is set, meaning it should respect all FileType autocmds and ftplugin
2493    files.
2494
2495    Example: >lua
2496        vim.filetype.get_option('vim', 'commentstring')
2497<
2498
2499    Note: this uses |nvim_get_option_value()| but caches the result. This
2500    means |ftplugin| and |FileType| autocommands are only triggered once and
2501    may not reflect later changes.
2502
2503    Attributes: ~
2504        Since: 0.9.0
2505
2506    Parameters: ~
2507      • {filetype}  (`string`) Filetype
2508      • {option}    (`string`) Option name
2509
2510    Return: ~
2511        (`string|boolean|integer`) Option value
2512
2513vim.filetype.inspect()                                *vim.filetype.inspect()*
2514    Inspect the current state of the filetype registry.
2515
2516    Returns a copy of the internal tables used for filetype detection by
2517    extension, filename, or pattern. Note: Due to the dynamic nature of
2518    filetype detection, this is only useful for checking whether a certain
2519    extension, filename, or pattern has been registered so far. In addition,
2520    the `pattern` table is in an internal format optimized for fast lookup.
2521    Prefer |vim.filetype.match()| for checking the detected filetype for a
2522    given pattern.
2523
2524    Return: ~
2525        (`{ extension: vim.filetype.mapping, filename: vim.filetype.mapping, pattern: table<string, vim.filetype.mapping> }`)
2526
2527vim.filetype.match({args})                              *vim.filetype.match()*
2528    Perform filetype detection.
2529
2530    The filetype can be detected using one of three methods:
2531    1. Using an existing buffer
2532    2. Using only a file name
2533    3. Using only file contents
2534
2535    Of these, option 1 provides the most accurate result as it uses both the
2536    buffer's filename and (optionally) the buffer contents. Options 2 and 3
2537    can be used without an existing buffer, but may not always provide a match
2538    in cases where the filename (or contents) cannot unambiguously determine
2539    the filetype.
2540
2541    Each of the three options is specified using a key to the single argument
2542    of this function. Example: >lua
2543        -- Using a buffer number
2544        vim.filetype.match({ buf = 42 })
2545
2546        -- Override the filename of the given buffer
2547        vim.filetype.match({ buf = 42, filename = 'foo.c' })
2548
2549        -- Using a filename without a buffer
2550        vim.filetype.match({ filename = 'main.lua' })
2551
2552        -- Using file contents
2553        vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
2554<
2555
2556    Parameters: ~
2557      • {args}  (`table`) Table specifying which matching strategy to use.
2558                Accepted keys are:
2559                • {buf}? (`integer`) Buffer number to use for matching.
2560                  Mutually exclusive with {contents}
2561                • {contents}? (`string[]`) An array of lines representing file
2562                  contents to use for matching. Can be used with {filename}.
2563                  Mutually exclusive with {buf}.
2564                • {filename}? (`string`) Filename to use for matching. When
2565                  {buf} is given, defaults to the filename of the given buffer
2566                  number. The file need not actually exist in the filesystem.
2567                  When used without {buf} only the name of the file is used
2568                  for filetype matching. This may result in failure to detect
2569                  the filetype in cases where the filename alone is not enough
2570                  to disambiguate the filetype.
2571
2572    Return (multiple): ~
2573        (`string?`) The matched filetype, if any.
2574        (`function?`) A function `fun(buf: integer)` that modifies buffer
2575        state when called (for example, to set some filetype specific buffer
2576        variables).
2577        (`boolean?`) true if a match was found by falling back to a generic
2578        filetype (i.e., ".conf"), which indicates the filetype should be set
2579        with `:setf FALLBACK conf`. See |:setfiletype|.
2580
2581
2582==============================================================================
2583Lua module: vim.fs                                                    *vim.fs*
2584
2585                                                               *vim.fs.copy()*
2586
2587Use |filecopy()| or |uv.fs_copyfile()| to performantly copy an existing file.
2588
2589Example: >lua
2590    vim.fn.filecopy('foo.txt', 'bar.txt')
2591<
2592
2593                                                             *vim.fs.exists()*
2594
2595Use |uv.fs_stat()| to check a file's type, and whether it exists.
2596
2597Example: >lua
2598    if vim.uv.fs_stat(file) then
2599      vim.print('file exists')
2600    end
2601<
2602
2603                                                               *vim.fs.read()*
2604
2605You can use |readblob()| to get a file's contents without explicitly
2606opening/closing it. Or use |io.lines()| to iterate lines in a text file.
2607
2608Example: >lua
2609    vim.print(vim.fn.readblob('.git/config'))
2610<
2611
2612                                                              *vim.fs.write()*
2613
2614You can use |writefile()| to write a file without explicitly opening/closing
2615it.
2616
2617Example: >lua
2618    vim.fn.writefile('foo\0bar', 'data.bin', 'b')
2619<
2620
2621
2622vim.fs.abspath({path}, {opts})                              *vim.fs.abspath()*
2623    Converts `path` to an absolute path. Expands tilde (~) at the beginning of
2624    the path (unless plain=true). Does not check if the path exists, normalize
2625    the path, resolve symlinks or hardlinks (including "." and ".."), or
2626    expand environment variables. If the path is already absolute, it is
2627    returned unchanged. Converts `\` path separators to `/`.
2628
2629    Attributes: ~
2630        Since: 0.11.0
2631
2632    Parameters: ~
2633      • {path}  (`string`) Path
2634      • {opts}  (`table?`) A table with the following fields:
2635                • {cwd}? (`string`) Resolve the path relative to this
2636                  directory.
2637                • {plain}? (`boolean`) Do not expand tilde (~).
2638
2639    Return: ~
2640        (`string`) Absolute path
2641
2642vim.fs.basename({file})                                    *vim.fs.basename()*
2643    Gets the basename of the given path (not expanded/resolved).
2644
2645    Attributes: ~
2646        Since: 0.8.0
2647
2648    Parameters: ~
2649      • {file}  (`string?`) Path
2650
2651    Return: ~
2652        (`string?`) Basename of `file`
2653
2654vim.fs.dir({path}, {opts})                                      *vim.fs.dir()*
2655    Gets an iterator over items found in `path` (normalized via
2656    |vim.fs.normalize()|).
2657
2658    Example: >lua
2659        for name, type, err in vim.fs.dir(path, { err = true }) do
2660          if err then
2661            -- Failed to scan directory {name} (may be the root {path} itself).
2662          end
2663        end
2664<
2665
2666    Attributes: ~
2667        Since: 0.8.0
2668
2669    Parameters: ~
2670      • {path}  (`string`) Directory to iterate over, expanded (unless
2671                `opts.plain=true`) and normalized.
2672      • {opts}  (`table?`) A table with the following fields:
2673                • {depth}? (`integer`, default: `1`) How deep to traverse.
2674                • {err}? (`boolean`, default: `false`) Report errors via the
2675                  iterator's third value ("err"), instead of silently
2676                  skipping.
2677                • {follow}? (`boolean`, default: `false`) Follow symbolic
2678                  links.
2679                • {plain}? (`boolean`, default: `false`) Do not expand special
2680                  forms like "~" and "$" in {path}.
2681                • {skip}? (`fun(dir_name: string): boolean`) Predicate to
2682                  control traversal. Return false to stop searching the
2683                  current directory. Only useful when depth > 1 Return an
2684                  iterator over the items located in {path}
2685
2686    Return: ~
2687        (`fun(): string?, string?, string?`) Iterator over items in {path},
2688        yielding (name, type, err):
2689        • name: Basename of the item relative to {path}.
2690        • type: One of: "file", "directory", "link", "fifo", "socket", "char",
2691          "block", "unknown".
2692        • err: Error string, or nil. Only if `opts.err=true`. If the root
2693          {path} itself could not be scanned, yields a single (name, nil, err)
2694          item.
2695
2696vim.fs.dirname({file})                                      *vim.fs.dirname()*
2697    Gets the parent directory of the given path (not expanded/resolved, the
2698    caller must do that).
2699
2700    Attributes: ~
2701        Since: 0.8.0
2702
2703    Parameters: ~
2704      • {file}  (`string?`) Path
2705
2706    Return: ~
2707        (`string?`) Parent directory of `file`
2708
2709vim.fs.ext({file}, {opts})                                      *vim.fs.ext()*
2710    Return the file's last extension, if any.
2711
2712    Similar to |fnamemodify()| with the |::e| modifier. The extension does not
2713    include a leading period.
2714
2715    Examples: >lua
2716        vim.fs.ext('archive.tar.gz') -- 'gz'
2717        vim.fs.ext('~/.git') -- ''
2718        vim.fs.ext('plugin/myplug.lua') -- 'lua'
2719<
2720
2721    Attributes: ~
2722        Since: 0.12.0
2723
2724    Parameters: ~
2725      • {file}  (`string`) Path
2726      • {opts}  (`table?`) Reserved for future use
2727
2728    Return: ~
2729        (`string`) Extension of {file}
2730
2731vim.fs.find({names}, {opts})                                   *vim.fs.find()*
2732    Find files or directories (or other items as specified by `opts.type`) in
2733    the given path.
2734
2735    Finds items given in {names} starting from {path}. If {upward} is "true"
2736    then the search traverses upward through parent directories; otherwise,
2737    the search traverses downward. Note that downward searches are recursive
2738    and may search through many directories! If {stop} is non-nil, then the
2739    search stops when the directory given in {stop} is reached. The search
2740    terminates when {limit} (default 1) matches are found. You can set {type}
2741    to "file", "directory", "link", "socket", "char", "block", or "fifo" to
2742    narrow the search to find only that type.
2743
2744    Examples: >lua
2745        -- List all test directories under the runtime directory.
2746        local dirs = vim.fs.find(
2747          { 'test', 'tst', 'testdir' },
2748          { limit = math.huge, type = 'directory', path = './runtime/' }
2749        )
2750
2751        -- Get all "lib/*.cpp" and "lib/*.hpp" files, using Lua patterns.
2752        -- Or use `vim.glob.to_lpeg(…):match(…)` for glob/wildcard matching.
2753        local files = vim.fs.find(function(name, path)
2754          return name:match('.*%.[ch]pp$') and path:match('[/\\]lib$')
2755        end, { limit = math.huge, type = 'file' })
2756<
2757
2758    Attributes: ~
2759        Since: 0.8.0
2760
2761    Parameters: ~
2762      • {names}  (`string|string[]|fun(name: string, path: string): boolean`)
2763                 Names of the items to find. Must be base names, paths and
2764                 globs are not supported when {names} is a string or a table.
2765                 If {names} is a function, it is called for each traversed
2766                 item with args:
2767                 • name: base name of the current item
2768                 • path: full path of the current item
2769
2770                 The function should return `true` if the given item is
2771                 considered a match.
2772      • {opts}   (`table?`) Optional keyword arguments:
2773                 • {follow}? (`boolean`, default: `false`) Follow symbolic
2774                   links.
2775                 • {limit}? (`number`, default: `1`) Stop searching after this
2776                   many matches. Use `math.huge` for "unlimited".
2777                 • {path}? (`string`) Path to begin searching from, defaults
2778                   to |current-directory|. Not expanded.
2779                 • {stop}? (`string`) Stop searching when this directory is
2780                   reached. The directory itself is not searched.
2781                 • {type}? (`string`) Find only items of the given type. If
2782                   omitted, all items that match {names} are included.
2783                 • {upward}? (`boolean`, default: `false`) Search upward
2784                   through parent directories. Otherwise, search child
2785                   directories (recursively).
2786
2787    Return (multiple): ~
2788        (`string[]`) Normalized paths |vim.fs.normalize()| of all matching
2789        items.
2790        (`string[]`) Errors collected while searching.
2791
2792vim.fs.joinpath({...})                                     *vim.fs.joinpath()*
2793    Concatenates partial paths (one absolute or relative path followed by zero
2794    or more relative paths). Slashes are normalized: redundant slashes are
2795    removed, and (on Windows) backslashes are replaced with forward-slashes.
2796    Empty segments are removed. Paths are not expanded/resolved.
2797
2798    Examples:
2799    • "foo/", "/bar" => "foo/bar"
2800    • "", "after/plugin" => "after/plugin"
2801    • Windows: "a\foo\", "\bar" => "a/foo/bar"
2802
2803    Attributes: ~
2804        Since: 0.10.0
2805
2806    Parameters: ~
2807      • {...}  (`string`)
2808
2809    Return: ~
2810        (`string`)
2811
2812vim.fs.mkdir({path}, {opts})                                  *vim.fs.mkdir()*
2813    Creates a directory.
2814
2815    Attributes: ~
2816        Since: 0.13.0
2817
2818    Parameters: ~
2819      • {path}  (`string`) Path to create (not expanded/resolved).
2820      • {opts}  (`table?`) Optional keyword arguments.
2821                • {mode}? (`integer`, default: `493`) Permission bits for
2822                  newly-created directories.
2823                • {parents}? (`boolean`, default: `false`) Create intermediate
2824                  directories as necessary.
2825
2826vim.fs.normalize({path}, {opts})                          *vim.fs.normalize()*
2827    Normalize a path to a standard format. Expands environment variables, and
2828    tilde "~" at the beginning of the path. Resolves "." and ".." components,
2829    except when the path is relative and resolving it would produce an
2830    absolute path.
2831    • "." as the only part in a relative path:
2832      • "." => "."
2833      • "././" => "."
2834    • ".." when it leads outside the current directory
2835      • "foo/../../bar" => "../bar"
2836      • "../../foo" => "../../foo"
2837    • ".." in the root directory returns the root directory.
2838      • "/../../" => "/"
2839
2840    On Windows, backslashes (`\`) are converted to forward slashes (`/`).
2841
2842    Examples: >lua
2843        [[C:\Users\jdoe]]                         --> "C:/Users/jdoe"
2844        "~/src/neovim"                            --> "/home/jdoe/src/neovim"
2845        "$XDG_CONFIG_HOME/nvim/init.vim"          --> "/Users/jdoe/.config/nvim/init.vim"
2846        "~/src/nvim/api/../tui/./tui.c"           --> "/home/jdoe/src/nvim/tui/tui.c"
2847        "./foo/bar"                               --> "foo/bar"
2848        "foo/../../../bar"                        --> "../../bar"
2849        "/home/jdoe/../../../bar"                 --> "/bar"
2850        "C:foo/../../baz"                         --> "C:../baz"
2851        "C:/foo/../../baz"                        --> "C:/baz"
2852        [[\\?\UNC\server\share\foo\..\..\..\bar]] --> "//?/UNC/server/share/bar"
2853<
2854
2855    Attributes: ~
2856        Since: 0.8.0
2857
2858    Parameters: ~
2859      • {path}  (`string`) Path to normalize
2860      • {opts}  (`table?`) A table with the following fields:
2861                • {plain}? (`boolean`, default: `false`) Do not expand
2862                  environment variables and leading tildes "~".
2863                • {win}? (`boolean`, default: `true` in Windows, `false`
2864                  otherwise) Path is a Windows path.
2865
2866    Return: ~
2867        (`string`) Normalized path
2868
2869vim.fs.parents({start})                                     *vim.fs.parents()*
2870    Iterate over all the parents of the given path (not expanded/resolved, the
2871    caller must do that).
2872
2873    Example: >lua
2874        local root_dir
2875        for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
2876          if vim.fn.isdirectory(dir .. '/.git') == 1 then
2877            root_dir = dir
2878            break
2879          end
2880        end
2881
2882        if root_dir then
2883          print('Found git repository at', root_dir)
2884        end
2885<
2886
2887    Attributes: ~
2888        Since: 0.8.0
2889
2890    Parameters: ~
2891      • {start}  (`string`) Initial path.
2892
2893    Return (multiple): ~
2894        (`fun(_, dir: string): string?`) Iterator
2895        (`nil`)
2896        (`string?`)
2897
2898vim.fs.relpath({base}, {target}, {opts})                    *vim.fs.relpath()*
2899    Gets `target` path relative to `base`, or `nil` if `base` is not an
2900    ancestor.
2901
2902    Example: >lua
2903        vim.fs.relpath('/var', '/var/lib') -- 'lib'
2904        vim.fs.relpath('/var', '/usr/bin') -- nil
2905<
2906
2907    Attributes: ~
2908        Since: 0.11.0
2909
2910    Parameters: ~
2911      • {base}    (`string`)
2912      • {target}  (`string`)
2913      • {opts}    (`table?`) Reserved for future use
2914
2915    Return: ~
2916        (`string?`)
2917
2918vim.fs.rm({path}, {opts})                                        *vim.fs.rm()*
2919    Removes a file or directory.
2920
2921    Removes symlinks without touching the origin. To remove the origin,
2922    resolve it explicitly with |uv.fs_realpath()|: >lua
2923        vim.fs.rm(vim.uv.fs_realpath('symlink-dir'), { recursive = true })
2924<
2925
2926    Attributes: ~
2927        Since: 0.11.0
2928
2929    Parameters: ~
2930      • {path}  (`string`) Path to remove (not expanded/resolved).
2931      • {opts}  (`table?`) A table with the following fields:
2932                • {force}? (`boolean`) Ignore nonexistent files and arguments.
2933                • {recursive}? (`boolean`) Remove directory contents
2934                  recursively.
2935
2936vim.fs.root({source}, {marker})                                *vim.fs.root()*
2937    Find the first parent directory containing a specific "marker", relative
2938    to a file path or buffer.
2939
2940    If the buffer is unnamed (has no backing file) or has a non-empty
2941    'buftype' then the search begins from Nvim's |current-directory|.
2942
2943    Examples: >lua
2944        -- Find the root of a Python project, starting from file 'main.py'
2945        vim.fs.root(vim.fs.joinpath(vim.env.PWD, 'main.py'), {'pyproject.toml', 'setup.py' })
2946
2947        -- Find the root of a git repository
2948        vim.fs.root(0, '.git')
2949
2950        -- Find the parent directory containing any file with a .csproj extension
2951        vim.fs.root(0, function(name, path)
2952          return vim.fs.ext(name) == 'csproj'
2953        end)
2954
2955        -- Find the first ancestor directory containing EITHER "stylua.toml" or ".luarc.json"; if
2956        -- not found, find the first ancestor containing ".git":
2957        vim.fs.root(0, { { 'stylua.toml', '.luarc.json' }, '.git' })
2958<
2959
2960    Attributes: ~
2961        Since: 0.10.0
2962
2963    Parameters: ~
2964      • {source}  (`integer|string`) Buffer number (0 for current buffer) or
2965                  file path (absolute or relative, expanded via `abspath()`)
2966                  to begin the search from.
2967      • {marker}  (`(string|string[]|fun(name: string, path: string): boolean)[]|string|fun(name: string, path: string): boolean`)
2968                  Filename, function, or list thereof, that decides how to
2969                  find the root. To indicate "equal priority", specify items
2970                  in a nested list `{ { 'a.txt', 'b.lua' }, … }`. A function
2971                  item must return true if `name` and `path` are a match. Each
2972                  item (which may itself be a nested list) is evaluated
2973                  in-order against all ancestors, until a match is found.
2974
2975    Return: ~
2976        (`string?`) Directory path containing one of the given markers, or nil
2977        if no directory was found.
2978
2979vim.fs.slug({path}, {opts})                                    *vim.fs.slug()*
2980    Gets a filesystem-safe, mnemonic slug (readable prefix + short hash) of an
2981    arbitrary filepath or other "identity string".
2982    • The input is normalized so equivalent paths produce the same result.
2983    • A hash of the normalized input is appended to prevent collisions.
2984    • Unsafe chars are replaced with "-".
2985    • `$HOME` is replaced with "~".
2986    • URIs (`scheme://...`) are prefixed with "=uri-{scheme}-".
2987    • UNC paths (Windows) are prefixed with "=unc-".
2988    • If `opts.maxlen` is exceeded, the result will be truncated to
2989      `{head}~~~{tail}-{hash8}`.
2990    • If the sanitized name is empty, the reserved label `=special` will be
2991      used.
2992
2993    Examples: >lua
2994        vim.print(vim.fs.slug('/tmp/test/foo.md'))           --> "tmp-test-foo.md-{hash}"
2995        vim.print(vim.fs.slug('C:/src/project/main.c'))      --> "C--src-project-main.c-{hash}"
2996        vim.print(vim.fs.slug(vim.fn.expand('~/file.txt')))  --> "~-file.txt-{hash}"
2997        vim.print(vim.fs.slug('---'))                        --> "=special-{hash}"
2998        vim.print(vim.fs.slug('term://foo/bar//123:bash'))   --> "=uri-term-foo-bar-123-bash-{hash}"
2999        vim.print(vim.fs.slug(('/a/very/long/path'):rep(10) .. '/file.txt', { maxlen = 60 }))
3000           --> "a-very-long-~~~-path-a-very-long-path-file.txt-{hash}"
3001<
3002
3003    Attributes: ~
3004        Since: 0.13.0
3005
3006    Parameters: ~
3007      • {path}  (`string`) Filepath (or other identity string).
3008      • {opts}  (`{ maxlen?: integer }?`)
3009                • maxlen: (integer, default: 180) Max length (bytes) of the
3010                  result.
3011
3012    Return: ~
3013        (`string`) Filesystem-safe, mnemonic slug.
3014
3015
3016==============================================================================
3017Lua module: vim.glob                                                *vim.glob*
3018
3019Glob-to-LPeg Converter (Peglob) This module converts glob patterns to LPeg
3020patterns according to the LSP 3.17 specification:
3021https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern
3022
3023Glob grammar overview:
3024• `*` to match zero or more characters in a path segment
3025• `?` to match on one character in a path segment
3026• `**` to match any number of path segments, including none
3027• `{}` to group conditions (e.g. `*.{ts,js}` matches TypeScript and JavaScript
3028  files)
3029• `[]` to declare a range of characters to match in a path segment (e.g.,
3030  `example.[0-9]` to match on `example.0`, `example.1`, …)
3031• `[!...]` to negate a range of characters to match in a path segment (e.g.,
3032  `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)
3033
3034Additional constraints:
3035• A Glob pattern must match an entire path, with partial matches considered
3036  failures.
3037• The pattern only determines success or failure, without specifying which
3038  parts correspond to which characters.
3039• A path segment is the portion of a path between two adjacent path separators
3040  (`/`), or between the start/end of the path and the nearest separator.
3041• The `**` (globstar) pattern matches zero or more path segments, including
3042  intervening separators (`/`). Within pattern strings, `**` must be delimited
3043  by path separators (`/`) or pattern boundaries and cannot be adjacent to any
3044  characters other than `/`. If `**` is not the final element, it must be
3045  followed by `/`.
3046• `{}` (braced conditions) contains valid Glob patterns as branches, separated
3047  by commas. Commas are exclusively used for separating branches and cannot
3048  appear within a branch for any other purpose. Nested `{}` structures are
3049  allowed, but `{}` must contain at least two branches—zero or one branch is
3050  not permitted.
3051• In `[]` or `[!...]`, a character range consists of character intervals
3052  (e.g., `a-z`) or individual characters (e.g., `w`). A range including `/`
3053  won’t match that character.
3054
3055
3056vim.glob.to_lpeg({pattern})                               *vim.glob.to_lpeg()*
3057    Parses a raw glob into an |lua-lpeg| pattern.
3058
3059    Parameters: ~
3060      • {pattern}  (`string`) The raw glob pattern
3061
3062    Return: ~
3063        (`vim.lpeg.Pattern`) An |lua-lpeg| representation of the pattern
3064
3065
3066==============================================================================
3067Lua module: vim.hl                                                    *vim.hl*
3068
3069vim.hl.hl_op({opts})                                          *vim.hl.hl_op()*
3070    Highlights the affected text region during a |TextYankPost| or
3071    |TextPutPost| event.
3072
3073    Add this to your `init.vim`: >vim
3074        autocmd TextYankPost * silent! lua vim.hl.hl_op {higroup='Visual', timeout=300}
3075        autocmd TextPutPost  * silent! lua vim.hl.hl_op {higroup='Visual', timeout=300}
3076<
3077
3078    Parameters: ~
3079      • {opts}  (`table?`) Optional parameters
3080                • event (default: vim.v.event) Event structure.
3081                • higroup (default: "IncSearch") Highlight group for the text
3082                  region.
3083                • on_macro (default: false) Highlight during |macro|
3084                  execution.
3085                • on_visual (default: true) Highlight during |Visual| mode.
3086                • priority (default: |vim.hl.priorities|`.user`) Integer
3087                  priority.
3088                • timeout (default: 150) Time in ms before highlight is
3089                  cleared.
3090
3091vim.hl.priorities                                          *vim.hl.priorities*
3092    Table with default priorities used for highlighting:
3093    • `syntax`: `50`, used for standard syntax highlighting
3094    • `treesitter`: `100`, used for treesitter-based highlighting
3095    • `semantic_tokens`: `125`, used for LSP semantic token highlighting
3096    • `diagnostics`: `150`, used for code analysis such as diagnostics
3097    • `user`: `200`, used for user-triggered highlights such as LSP document
3098      symbols or `hl_op` autocommands
3099
3100                                                              *vim.hl.range()*
3101vim.hl.range({buf}, {ns}, {hlgroup}, {start}, {finish}, {opts})
3102    Apply highlight group to range of text.
3103
3104    Parameters: ~
3105      • {buf}      (`integer`) Buffer number to apply highlighting to
3106      • {ns}       (`integer`) Namespace to add highlight to
3107      • {hlgroup}  (`integer|integer[]|string|string[]`) Highlight group used
3108                   for the text range. See the `hl_group` option in
3109                   |nvim_buf_set_extmark()|.
3110      • {start}    (`[integer,integer]|string`) Start of region as a (line,
3111                   column) tuple or string accepted by |getpos()|
3112      • {finish}   (`[integer,integer]|string`) End of region as a (line,
3113                   column) tuple or string accepted by |getpos()|
3114      • {opts}     (`table?`) A table with the following fields:
3115                   • {inclusive}? (`boolean`, default: `false`) Indicates
3116                     whether the range is end-inclusive
3117                   • {priority}? (`integer`, default:
3118                     `vim.hl.priorities.user`) Highlight priority
3119                   • {regtype}? (`string`, default: `'v'` i.e. charwise) Type
3120                     of range. See |getregtype()|
3121                   • {timeout}? (`integer`, default: -1 no timeout) Time in ms
3122                     before highlight is cleared
3123
3124    Return (multiple): ~
3125        (`uv.uv_timer_t?`) range_timer A timer which manages how much time the
3126        highlight has left
3127        (`fun()?`) range_clear A function which allows clearing the highlight
3128        manually. nil is returned if timeout is not specified
3129
3130
3131==============================================================================
3132Lua module: vim.iter                                                *vim.iter*
3133
3134*vim.iter()* is an interface for |iterable|s: it wraps a table or function
3135argument into an *Iter* object with methods (such as |Iter:filter()| and
3136|Iter:map()|) that transform the underlying source data. These methods can be
3137chained to create iterator "pipelines": the output of each pipeline stage is
3138input to the next stage. The first stage depends on the type passed to
3139`vim.iter()`:
3140• Lists or arrays (|lua-list|) yield only the value of each element.
3141  • Holes (nil values) are allowed (but discarded).
3142  • Use pairs() to treat array/list tables as dicts (preserve holes and
3143    non-contiguous integer keys): `vim.iter(pairs(…))`.
3144  • Use |Iter:enumerate()| to also pass the index to the next stage.
3145    • Or initialize with ipairs(): `vim.iter(ipairs(…))`.
3146• Non-list tables (|lua-dict|) yield both the key and value of each element.
3147• Function |iterator|s yield all values returned by the underlying function.
3148• Tables with a |__call()| metamethod are treated as function iterators.
3149
3150The iterator pipeline terminates when the underlying |iterable| is exhausted
3151(for function iterators this means it returned nil).
3152
3153Note: `vim.iter()` scans table input to decide if it is a list or a dict; to
3154avoid this cost you can wrap the table with an iterator e.g.
3155`vim.iter(ipairs({…}))`, but that precludes the use of |list-iterator|
3156operations such as |IterArray:rev()|).
3157
3158Examples: >lua
3159    local it = vim.iter({ 1, 2, 3, 4, 5 })
3160    it:map(function(v)
3161      return v * 3
3162    end)
3163    it:rev()
3164    it:skip(2)
3165    it:totable()
3166    -- { 9, 6, 3 }
3167
3168    -- ipairs() is a function iterator which returns both the index (i) and the value (v)
3169    vim.iter(ipairs({ 1, 2, 3, 4, 5 })):map(function(i, v)
3170      if i > 2 then return v end
3171    end):totable()
3172    -- { 3, 4, 5 }
3173
3174    local it = vim.iter(vim.gsplit('1,2,3,4,5', ','))
3175    it:map(function(s) return tonumber(s) end)
3176    for i, d in it:enumerate() do
3177      print(string.format("Column %d is %d", i, d))
3178    end
3179    -- Column 1 is 1
3180    -- Column 2 is 2
3181    -- Column 3 is 3
3182    -- Column 4 is 4
3183    -- Column 5 is 5
3184
3185    vim.iter({ a = 1, b = 2, c = 3, z = 26 }):any(function(k, v)
3186      return k == 'z'
3187    end)
3188    -- true
3189
3190    local rb = vim.ringbuf(3)
3191    rb:push("a")
3192    rb:push("b")
3193    vim.iter(rb):totable()
3194    -- { "a", "b" }
3195<
3196
3197
3198Iter:all({pred})                                                  *Iter:all()*
3199    Returns true if all items in the iterator match the given predicate.
3200
3201    Attributes: ~
3202        Since: 0.10.0
3203
3204    Parameters: ~
3205      • {pred}  (`fun(v: V1, ...: V...): boolean`) Predicate function. Takes
3206                all values returned from the previous stage in the pipeline as
3207                arguments and returns true if the predicate matches.
3208
3209Iter:any({pred})                                                  *Iter:any()*
3210    Returns true if any of the items in the iterator match the given
3211    predicate.
3212
3213    Attributes: ~
3214        Since: 0.10.0
3215
3216    Parameters: ~
3217      • {pred}  (`fun(v: V1, ...: V...): boolean`) Predicate function. Takes
3218                all values returned from the previous stage in the pipeline as
3219                arguments and returns true if the predicate matches.
3220
3221Iter:count()                                                    *Iter:count()*
3222    Drains the iterator, counting the number of iterations and returning it.
3223
3224    Attributes: ~
3225        Since: 0.13.0
3226
3227    Return: ~
3228        (`integer`)
3229
3230Iter:each({f})                                                   *Iter:each()*
3231    Calls a function once for each item in the pipeline, draining the
3232    iterator.
3233
3234    For functions with side effects. To modify the values in the iterator, use
3235    |Iter:map()|.
3236
3237    Attributes: ~
3238        Since: 0.10.0
3239
3240    Parameters: ~
3241      • {f}  (`fun(v: V1, ...: V...)`) Function to execute for each item in
3242             the pipeline. Takes all of the values returned by the previous
3243             stage in the pipeline as arguments.
3244
3245Iter:enumerate()                                            *Iter:enumerate()*
3246    Yields the item index (count) and value for each item of an iterator
3247    pipeline.
3248
3249    For list tables, this is more efficient: >lua
3250        vim.iter(ipairs(t))
3251<
3252
3253    instead of: >lua
3254        vim.iter(t):enumerate()
3255<
3256
3257    Example: >lua
3258
3259        local it = vim.iter(vim.gsplit('abc', '')):enumerate()
3260        it:next()
3261        -- 1	'a'
3262        it:next()
3263        -- 2	'b'
3264        it:next()
3265        -- 3	'c'
3266<
3267
3268    Attributes: ~
3269        Since: 0.10.0
3270
3271    Overloads: ~
3272      • `fun<V1, V...>(self: vim.IterArray<V1, V...>): vim.IterArray<integer, V1, V...>`
3273
3274    Return: ~
3275        (`vim.Iter<integer, V1, V...>`)
3276
3277Iter:filter({f})                                               *Iter:filter()*
3278    Filters an iterator pipeline.
3279
3280    Example: >lua
3281        local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
3282<
3283
3284    Parameters: ~
3285      • {f}  (`fun(v: V1, ...: V...): boolean`) Takes all values returned from
3286             the previous stage in the pipeline and returns false or nil if
3287             the current iterator element should be removed.
3288
3289    Overloads: ~
3290      • `fun<V1, V...>(self: vim.IterArray<V1, V...>, f: fun(v: V1, ...: V...): boolean): vim.IterArray<V1, V...>`
3291
3292    Return: ~
3293        (`vim.Iter<V1, V...>`)
3294
3295Iter:find({f})                                                   *Iter:find()*
3296    Find the first value in the iterator that satisfies the given predicate.
3297
3298    Advances the iterator. Returns nil and drains the iterator if no value is
3299    found.
3300
3301    Examples: >lua
3302
3303        local it = vim.iter({ 3, 6, 9, 12 })
3304        it:find(12)
3305        -- 12
3306
3307        local it = vim.iter({ 3, 6, 9, 12 })
3308        it:find(20)
3309        -- nil
3310
3311        local it = vim.iter({ 3, 6, 9, 12 })
3312        it:find(function(v) return v % 4 == 0 end)
3313        -- 12
3314<
3315
3316    Attributes: ~
3317        Since: 0.10.0
3318
3319    Parameters: ~
3320      • {f}  (`V1|fun(v: V1, ...: V...): any`)
3321
3322    Return (multiple): ~
3323        (`V1?`)
3324        (`V...`)
3325
3326Iter:fold({init}, {f})                                           *Iter:fold()*
3327    Folds ("reduces") an iterator into a single value.         *Iter:reduce()*
3328
3329    Examples: >lua
3330        -- Create a new table with only even values
3331        vim.iter({ a = 1, b = 2, c = 3, d = 4 })
3332          :filter(function(k, v) return v % 2 == 0 end)
3333          :fold({}, function(acc, k, v)
3334            acc[k] = v
3335            return acc
3336          end) --> { b = 2, d = 4 }
3337
3338        -- Get the "maximum" item of an iterable.
3339        vim.iter({ -99, -4, 3, 42, 0, 0, 7 })
3340          :fold({}, function(acc, v)
3341            acc.max = math.max(v, acc.max or v)
3342            return acc
3343          end) --> { max = 42 }
3344<
3345
3346    Attributes: ~
3347        Since: 0.10.0
3348
3349    Parameters: ~
3350      • {init}  (`any`) Initial value of the accumulator.
3351      • {f}     (`fun(acc: A, v: V1, ...: V...): A`) Accumulation function.
3352
3353    Return: ~
3354        (`any`)
3355
3356Iter:join({delim})                                               *Iter:join()*
3357    Collect the iterator into a delimited string.
3358
3359    Each element in the iterator is joined into a string separated by {delim}.
3360
3361    Consumes the iterator.
3362
3363    Attributes: ~
3364        Since: 0.10.0
3365
3366    Parameters: ~
3367      • {delim}  (`string`) Delimiter
3368
3369    Return: ~
3370        (`string`)
3371
3372Iter:last()                                                      *Iter:last()*
3373    Drains the iterator and returns the last item.
3374
3375    Example: >lua
3376
3377        local it = vim.iter(vim.gsplit('abcdefg', ''))
3378        it:last()
3379        -- 'g'
3380
3381        local it = vim.iter({ 3, 6, 9, 12, 15 })
3382        it:last()
3383        -- 15
3384<
3385
3386    Attributes: ~
3387        Since: 0.10.0
3388
3389    Return (multiple): ~
3390        (`V1?`)
3391        (`V...`)
3392
3393    See also: ~
3394      • |IterArray:rpeek()|
3395
3396Iter:map({f})                                                     *Iter:map()*
3397    Maps the items of an iterator pipeline to the values returned by `f`.
3398
3399    If the map function returns nil, the value is filtered from the iterator.
3400
3401    Example: >lua
3402        local it = vim.iter({ 1, 2, 3, 4 }):map(function(v)
3403          if v % 2 == 0 then
3404            return v * 3
3405          end
3406        end)
3407        it:totable()
3408        -- { 6, 12 }
3409<
3410
3411    Attributes: ~
3412        Since: 0.10.0
3413
3414    Parameters: ~
3415      • {f}  (`fun(v: V1, ...: V...): K2, V2...`) Mapping function. Takes all
3416             values returned from the previous stage in the pipeline as
3417             arguments and returns one or more new values, which are used in
3418             the next pipeline stage. Nil return values are filtered from the
3419             output.
3420
3421    Overloads: ~
3422      • `fun<V1, V..., K1, K...>(self: vim.IterArray<V1, V...>, f: fun(v: V1, ...: V...): K1, K...): vim.IterArray<K1, K...>`
3423
3424    Return: ~
3425        (`vim.Iter<K2, V2...>`)
3426
3427Iter:next()                                                      *Iter:next()*
3428    Gets the next value from the iterator.
3429
3430    Example: >lua
3431
3432        local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber)
3433        it:next()
3434        -- 1
3435        it:next()
3436        -- 2
3437        it:next()
3438        -- 3
3439<
3440
3441    Attributes: ~
3442        Since: 0.10.0
3443
3444    Return (multiple): ~
3445        (`V1?`)
3446        (`V...`)
3447
3448Iter:nth({n})                                                     *Iter:nth()*
3449    Gets the nth value of an iterator (and advances to it).
3450
3451    If `n` is negative, offsets from the end of a |list-iterator|.
3452
3453    Example: >lua
3454        local it = vim.iter({ 3, 6, 9, 12 })
3455        it:nth(2)
3456        -- 6
3457        it:nth(2)
3458        -- 12
3459
3460        local it2 = vim.iter({ 3, 6, 9, 12 })
3461        it2:nth(-2)
3462        -- 9
3463        it2:nth(-2)
3464        -- 3
3465<
3466
3467    Attributes: ~
3468        Since: 0.10.0
3469
3470    Parameters: ~
3471      • {n}  (`integer`) Index of the value to return. May be negative if the
3472             source is a |list-iterator|.
3473
3474    Return (multiple): ~
3475        (`V1?`)
3476        (`V...`)
3477
3478Iter:peek()                                                      *Iter:peek()*
3479    Gets the next value from the iterator without consuming it.
3480
3481    The value returned by |Iter:peek()| will be returned again by the next
3482    call to |Iter:next()|.
3483
3484    Example: >lua
3485
3486        local it = vim.iter({ 3, 6, 9, 12 })
3487        it:peek()
3488        -- 3
3489        it:peek()
3490        -- 3
3491        it:next()
3492        -- 3
3493<
3494
3495    Attributes: ~
3496        Since: 0.10.0
3497
3498    Return (multiple): ~
3499        (`V1?`)
3500        (`V...`)
3501
3502Iter:skip({n})                                                   *Iter:skip()*
3503    Skips `n` values of an iterator pipeline, or skips values while a
3504    predicate returns |lua-truthy|.
3505
3506    When a predicate is used, skipping stops at the first value for which the
3507    predicate returns non-truthy. That value is not consumed and will be
3508    returned by the next call to |Iter:next()|
3509
3510    Example: >lua
3511
3512        local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
3513        it:next()
3514        -- 9
3515
3516        local function pred(x) return x < 10 end
3517        local it2 = vim.iter({ 3, 6, 9, 12 }):skip(pred)
3518        it2:next()
3519        -- 12
3520<
3521
3522    Attributes: ~
3523        Since: 0.10.0
3524
3525    Parameters: ~
3526      • {n}  (`integer|fun(v: V1, ...: V...): boolean`) Number of values to
3527             skip or a predicate.
3528
3529    Overloads: ~
3530      • `fun<V1, V...>(self: vim.IterArray<V1, V...>, n: integer|fun(v: V1, ...: V...): boolean): vim.IterArray<V1, V...>`
3531
3532    Return: ~
3533        (`vim.Iter<V1, V...>`)
3534
3535Iter:take({n})                                                   *Iter:take()*
3536    Transforms an iterator to yield only the first n values, or all values
3537    satisfying a predicate.
3538
3539    Example: >lua
3540        local it = vim.iter({ 1, 2, 3, 4 }):take(2)
3541        it:next()
3542        -- 1
3543        it:next()
3544        -- 2
3545        it:next()
3546        -- nil
3547
3548        local function pred(x) return x < 2 end
3549        local it2 = vim.iter({ 1, 2, 3, 4 }):take(pred)
3550        it2:next()
3551        -- 1
3552        it2:next()
3553        -- nil
3554<
3555
3556    Attributes: ~
3557        Since: 0.10.0
3558
3559    Parameters: ~
3560      • {n}  (`integer|fun(v: V1, ...: V...): boolean`) Number of values to
3561             take or a predicate.
3562
3563    Overloads: ~
3564      • `fun<V1, V...>(self: vim.IterArray<V1, V...>, n: integer|fun(v: V1, ...: V...): boolean): vim.IterArray<V1, V...>`
3565
3566    Return: ~
3567        (`vim.Iter<V1, V...>`)
3568
3569Iter:totable()                                                *Iter:totable()*
3570    Collect the iterator into a table.
3571
3572    The resulting table depends on the initial source in the iterator
3573    pipeline. Array-like tables and function iterators will be collected into
3574    an array-like table. If multiple values are returned from the final stage
3575    in the iterator pipeline, each value will be included in a table.
3576
3577    Examples: >lua
3578        vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable()
3579        -- { 100, 20, 50 }
3580
3581        vim.iter({ 1, 2, 3 }):map(function(v) return v, 2 * v end):totable()
3582        -- { { 1, 2 }, { 2, 4 }, { 3, 6 } }
3583
3584        vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable()
3585        -- { { 'a', 1 }, { 'c', 3 } }
3586<
3587
3588    The generated table is an array-like table with consecutive, numeric
3589    indices. To create a map-like table with arbitrary keys, use
3590    |Iter:fold()|.
3591
3592    Attributes: ~
3593        Since: 0.10.0
3594
3595    Return: ~
3596        (`any[]`)
3597
3598Iter:unique({key})                                             *Iter:unique()*
3599    Removes duplicate values from an iterator pipeline.
3600
3601    Only the first occurrence of each value is kept.
3602
3603    Accepts an optional `key` argument, which if provided is called for each
3604    value in the iterator to compute a hash key for uniqueness comparison.
3605    This is useful for deduplicating table values or complex objects. If `key`
3606    returns `nil` for a value, that value will be considered unique, even if
3607    multiple values return `nil`.
3608
3609    If a function-based iterator returns multiple arguments, uniqueness is
3610    checked based on the first return value. To change this behavior, specify
3611    `key`.
3612
3613    Examples: >lua
3614        vim.iter({ 1, 2, 2, 3, 2 }):unique():totable()
3615        -- { 1, 2, 3 }
3616
3617        vim.iter({ {id=1}, {id=2}, {id=1} })
3618          :unique(function(x)
3619            return x.id
3620          end)
3621          :totable()
3622        -- { {id=1}, {id=2} }
3623<
3624
3625    Attributes: ~
3626        Since: 0.12.0
3627
3628    Parameters: ~
3629      • {key}  (`fun(v: V1, ...: V...): any?`) Optional hash function to
3630               determine uniqueness of values.
3631
3632    Overloads: ~
3633      • `fun<V1, V...>(self: vim.IterArray<V1, V...>, key: fun(v: V1, ...: V...): any?): vim.IterArray<V1, V...>`
3634
3635    Return: ~
3636        (`vim.Iter<V1, V...>`)
3637
3638    See also: ~
3639      • |vim.list.unique()|
3640
3641IterArray:flatten({depth})                               *IterArray:flatten()*
3642    Flattens a |list-iterator|, un-nesting nested values up to the given
3643    {depth}. Errors if it attempts to flatten a dict-like value.
3644
3645    Examples: >lua
3646        vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable()
3647        -- { 1, 2, { 3 } }
3648
3649        vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable()
3650        -- { 1, { a = 2 }, 3 }
3651
3652        vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable()
3653        -- error: attempt to flatten a dict-like table
3654<
3655
3656    Attributes: ~
3657        Since: 0.10.0
3658
3659    Parameters: ~
3660      • {depth}  (`integer?`) Depth to which |list-iterator| should be
3661                 flattened (defaults to 1)
3662
3663    Return: ~
3664        (`vim.IterArray<V1, V...>`)
3665
3666IterArray:pop()                                              *IterArray:pop()*
3667    "Pops" a value from a |list-iterator| (gets the last value and decrements
3668    the tail).
3669
3670    Example: >lua
3671        local it = vim.iter({1, 2, 3, 4})
3672        it:pop()
3673        -- 4
3674        it:pop()
3675        -- 3
3676<
3677
3678    Attributes: ~
3679        Since: 0.10.0
3680
3681    Return (multiple): ~
3682        (`V1?`)
3683        (`V...`)
3684
3685IterArray:rev()                                              *IterArray:rev()*
3686    Reverses a |list-iterator| pipeline.
3687
3688    Example: >lua
3689
3690        local it = vim.iter({ 3, 6, 9, 12 }):rev()
3691        it:totable()
3692        -- { 12, 9, 6, 3 }
3693<
3694
3695    Attributes: ~
3696        Since: 0.10.0
3697
3698    Return: ~
3699        (`vim.IterArray<V1, V...>`)
3700
3701IterArray:rfind({f})                                       *IterArray:rfind()*
3702    Gets the first value satisfying a predicate, from the end of a
3703    |list-iterator|.
3704
3705    Advances the iterator. Returns nil and drains the iterator if no value is
3706    found.
3707
3708    Examples: >lua
3709
3710        local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
3711        it:rfind(1)
3712        -- 5	1
3713        it:rfind(1)
3714        -- 1	1
3715<
3716
3717    Attributes: ~
3718        Since: 0.10.0
3719
3720    Parameters: ~
3721      • {f}  (`V1|fun(v: V1, ...: V...): boolean`)
3722
3723    Return (multiple): ~
3724        (`V1?`)
3725        (`V...`)
3726
3727    See also: ~
3728      • |Iter:find()|
3729
3730IterArray:rpeek()                                          *IterArray:rpeek()*
3731    Gets the last value of a |list-iterator| without consuming it.
3732
3733    Example: >lua
3734        local it = vim.iter({1, 2, 3, 4})
3735        it:rpeek()
3736        -- 4
3737        it:rpeek()
3738        -- 4
3739        it:pop()
3740        -- 4
3741<
3742
3743    Attributes: ~
3744        Since: 0.10.0
3745
3746    Return (multiple): ~
3747        (`V1?`)
3748        (`V...`)
3749
3750    See also: ~
3751      • |Iter:last()|
3752
3753IterArray:rskip({n})                                       *IterArray:rskip()*
3754    Discards `n` values from the end of a |list-iterator| pipeline.
3755
3756    Example: >lua
3757        local it = vim.iter({ 1, 2, 3, 4, 5 }):rskip(2)
3758        it:next()
3759        -- 1
3760        it:pop()
3761        -- 3
3762<
3763
3764    Attributes: ~
3765        Since: 0.10.0
3766
3767    Parameters: ~
3768      • {n}  (`integer`)
3769
3770    Return: ~
3771        (`vim.IterArray<V1, V...>`)
3772
3773IterArray:slice({first}, {last})                           *IterArray:slice()*
3774    Sets the start and end of a |list-iterator| pipeline.
3775
3776    Equivalent to `:skip(first - 1):rskip(len - last + 1)`.
3777
3778    Attributes: ~
3779        Since: 0.10.0
3780
3781    Parameters: ~
3782      • {first}  (`integer`)
3783      • {last}   (`integer`)
3784
3785    Return: ~
3786        (`vim.IterArray<V1, V...>`)
3787
3788
3789==============================================================================
3790Lua module: vim.json                                                *vim.json*
3791
3792This module provides encoding and decoding of Lua objects to and from
3793JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
3794
3795
3796vim.json.decode({str}, {opts})                             *vim.json.decode()*
3797    Decodes (or "unpacks") stringified JSON to a Lua object.
3798    • Decodes JSON "null" as |vim.NIL| (controllable by {opts}, see below).
3799    • Decodes empty object as |vim.empty_dict()|.
3800    • Decodes empty array as `{}` (empty Lua table).
3801
3802    Example: >lua
3803        vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
3804        -- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
3805<
3806
3807    Parameters: ~
3808      • {str}   (`string`) Stringified JSON data.
3809      • {opts}  (`table?`) A table with the following fields:
3810                • {luanil}? (`{ object?: boolean, array?: boolean }`, default:
3811                  `nil`) Convert JSON "null" in objects/arrays to Lua `nil`
3812                  instead of |vim.NIL|.
3813                • {skip_comments}? (`boolean`, default: `false`) Allows
3814                  JavaScript-style comments within JSON data. Comments are
3815                  treated as whitespace and may appear anywhere whitespace is
3816                  valid in JSON. Supports single-line comments beginning with
3817                  '//' and block comments enclosed with '/' and '/'.
3818
3819    Return: ~
3820        (`any`)
3821
3822vim.json.encode({obj}, {opts})                             *vim.json.encode()*
3823    Encodes (or "packs") a Lua object to stringified JSON.
3824
3825    Example: Implement a basic 'formatexpr' for JSON, so |gq| with a motion
3826    formats JSON in a buffer. (The motion must operate on a valid JSON
3827    object.) >lua
3828        function _G.fmt_json()
3829          local indent = vim.bo.expandtab and (' '):rep(vim.o.shiftwidth) or '\t'
3830          local lines = vim.api.nvim_buf_get_lines(0, vim.v.lnum - 1, vim.v.lnum + vim.v.count - 1, true)
3831          local o = vim.json.decode(table.concat(lines, '\n'))
3832          local stringified = vim.json.encode(o, { indent = indent, sort_keys = true })
3833          lines = vim.split(stringified, '\n')
3834          vim.api.nvim_buf_set_lines(0, vim.v.lnum - 1, vim.v.count, true, lines)
3835        end
3836        vim.o.formatexpr = 'v:lua.fmt_json()'
3837<
3838
3839    Parameters: ~
3840      • {obj}   (`any`)
3841      • {opts}  (`table?`) A table with the following fields:
3842                • {escape_slash}? (`boolean`, default: `false`) Escape slash
3843                  characters "/" in string values.
3844                • {indent}? (`string`, default: `""`) If non-empty, each value
3845                  in a JSON object or array starts on a new line and is
3846                  prefixed with `indent` per nesting level. Adds a space after
3847                  colons. Does not add a final newline.
3848                • {sort_keys}? (`boolean`, default: `false`) Sort object keys
3849                  in alphabetical order.
3850
3851    Return: ~
3852        (`string`)
3853
3854
3855==============================================================================
3856Lua module: vim.keymap                                            *vim.keymap*
3857
3858vim.keymap.del({modes}, {lhs}, {opts})                      *vim.keymap.del()*
3859    Removes a mapping, or removes each (mode, lhs) pair if `lhs` is a list.
3860
3861    Examples: >lua
3862        vim.keymap.del('n', 'lhs')
3863        vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buf = 5 })
3864<
3865
3866    Parameters: ~
3867      • {modes}  (`string|string[]`)
3868      • {lhs}    (`string|string[]`)
3869      • {opts}   (`table?`) A table with the following fields:
3870                 • {buf}? (`integer`) Remove a mapping from the given buffer.
3871                   `0` for current.
3872                 • {lhs}? (`boolean`) When true, only match {lhs}, not {rhs}.
3873
3874    See also: ~
3875      • |vim.keymap.set()|
3876
3877vim.keymap.set({modes}, {lhs}, {rhs}, {opts})               *vim.keymap.set()*
3878    Defines a |mapping| of |keycodes| to a function or keycodes. If `lhs` is a
3879    list, defines a mapping for each (mode, lhs) pair.
3880
3881    Examples: >lua
3882        -- Map "x" to a Lua function:
3883        vim.keymap.set('n', 'x', function() print('real lua function') end)
3884        -- Map "<leader>x" to multiple modes for the current buffer:
3885        vim.keymap.set({'n', 'v'}, '<leader>x', vim.lsp.buf.references, { buf = 0 })
3886        -- Map <Tab> to an expression (|:map-<expr>|):
3887        vim.keymap.set('i', '<Tab>', function()
3888          return vim.fn.pumvisible() == 1 and '<C-n>' or '<Tab>'
3889        end, { expr = true })
3890        -- Map "[%%" to a <Plug> mapping:
3891        vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)')
3892
3893        -- Use `getregionpos(getpos('v'))` to get the "current visual selection":
3894        vim.keymap.set('x', 'M', function()
3895          local region = vim.fn.getregionpos(vim.fn.getpos('v'), vim.fn.getpos('.'), {
3896            type = 'v',
3897            exclusive = false,
3898            eol = false,
3899            bounds = true,
3900          })
3901          local line1 = region[1][1][2]
3902          local line2 = region[1][2][2]
3903          vim.print({ line1, line2 })
3904        end)
3905
3906        vim.keymap.set({ 'n', 'i' }, { 'a', 'b' }, '<cmd>echom localtime()<cr>')
3907        -- ... is the same as:
3908        vim.keymap.set('n', 'a', '<cmd>echom localtime()<cr>')
3909        vim.keymap.set('i', 'a', '<cmd>echom localtime()<cr>')
3910        vim.keymap.set('n', 'b', '<cmd>echom localtime()<cr>')
3911        vim.keymap.set('i', 'b', '<cmd>echom localtime()<cr>')
3912<
3913
3914    Parameters: ~
3915      • {modes}  (`string|string[]`) Mode "short-name" (see
3916                 |nvim_set_keymap()|), or a list thereof.
3917      • {lhs}    (`string|string[]`) Left-hand side |{lhs}| of the mapping, or
3918                 a list thereof.
3919      • {rhs}    (`string|function`) Right-hand side |{rhs}| of the mapping,
3920                 can be a Lua function.
3921      • {opts}   (`table?`) Table of |:map-arguments|. Same as
3922                 |nvim_set_keymap()| {opts}, except:
3923                 • {replace_keycodes} defaults to `true` if "expr" is `true`.
3924                 • {noremap} is not supported; use {remap} instead (see
3925                   below).
3926
3927                 Also accepts:
3928                 • {buf}? (`integer`) Creates buffer-local mapping, `0` for
3929                   current buffer.
3930                 • {remap}? (`boolean`, default: `false`) Make the mapping
3931                   recursive. Inverse of {noremap}.
3932
3933    See also: ~
3934      • |nvim_set_keymap()|
3935      • |maparg()|
3936      • |mapcheck()|
3937      • |mapset()|
3938
3939
3940==============================================================================
3941Lua module: vim.loader                                            *vim.loader*
3942
3943vim.loader.enable({enable})                              *vim.loader.enable()*
3944    WARNING: This feature is experimental/unstable.
3945
3946    Enables or disables the experimental Lua module loader:
3947
3948    Enable (`enable=true`):
3949    • overrides |loadfile()|
3950    • adds the Lua loader using the byte-compilation cache
3951    • adds the libs loader
3952    • removes the default Nvim loader
3953
3954    Disable (`enable=false`):
3955    • removes the loaders
3956    • adds the default Nvim loader
3957
3958    Parameters: ~
3959      • {enable}  (`boolean?`) true/nil to enable, false to disable
3960
3961vim.loader.find({modname}, {opts})                         *vim.loader.find()*
3962    WARNING: This feature is experimental/unstable.
3963
3964    Finds Lua modules for the given module name.
3965
3966    Parameters: ~
3967      • {modname}  (`string`) Module name, or `"*"` to find the top-level
3968                   modules instead
3969      • {opts}     (`table?`) Options for finding a module:
3970                   • {all}? (`boolean`, default: `false`) Search for all
3971                     matches.
3972                   • {paths}? (`string[]`, default: `{}`) Extra paths to
3973                     search for modname
3974                   • {patterns}? (`string[]`, default:
3975                     `{"/init.lua", ".lua"}`) List of patterns to use when
3976                     searching for modules. A pattern is a string added to the
3977                     basename of the Lua module being searched.
3978                   • {rtp}? (`boolean`, default: `true`) Search for modname in
3979                     the runtime path.
3980
3981    Return: ~
3982        (`table[]`) A list of objects with the following fields:
3983        • {modname} (`string`) Name of the module
3984        • {modpath} (`string`) Path of the module
3985        • {stat}? (`uv.fs_stat.result`) The fs_stat of the module path. Won't
3986          be returned for `modname="*"`
3987
3988vim.loader.reset({path})                                  *vim.loader.reset()*
3989    WARNING: This feature is experimental/unstable.
3990
3991    Resets the cache for the path, or all the paths if path is nil.
3992
3993    Parameters: ~
3994      • {path}  (`string?`) path to reset
3995
3996
3997==============================================================================
3998Lua module: vim.log                                                  *vim.log*
3999
4000The |vim.log| module provides file-backed logger instances.
4001
4002Use `vim.log.new()` to create a logger, it exposes five writer functions:
4003`trace()`, `debug()`, `info()`, `warn()`, and `error()`. They are correspond
4004to log levels defined by |vim.log.levels|.
4005
4006Example: >lua
4007    local log = vim.log.new({ name = 'my-plugin', })
4008    -- By default, logs will be written to {name}.log under `stdpath('log')`.
4009
4010    log.error('request failed', 'timeout')
4011    -- This will write a line like the following to the log file:
4012    --   [ERROR][2024-01-01 12:00:00] source.lua:123    request failed    timeout
4013
4014    -- Set the log level to `INFO`, otherwise the `info()` call below would be ignored,
4015    -- since the default level is `WARN`.
4016    vim.log.set_level(log, vim.log.levels.INFO)
4017    log.info('starting', { buf = vim.api.nvim_get_current_buf() })
4018    -- This will write a line like the following to the log file:
4019    --   [INFO][2024-01-01 12:01:00] source.lua:124    starting    { buf = 1 }
4020<
4021
4022You can also provide a custom formatter function to customize the log output
4023format.
4024
4025
4026*vim.Log*
4027
4028    Fields: ~
4029      • {debug}  (`fun(...:any): boolean?`) Writes a message at
4030                 `vim.log.levels.DEBUG`.
4031      • {error}  (`fun(...:any): boolean?`) Writes a message at
4032                 `vim.log.levels.ERROR`.
4033      • {info}   (`fun(...:any): boolean?`) Writes a message at
4034                 `vim.log.levels.INFO`.
4035      • {trace}  (`fun(...:any): boolean?`) Writes a message at
4036                 `vim.log.levels.TRACE`.
4037      • {warn}   (`fun(...:any): boolean?`) Writes a message at
4038                 `vim.log.levels.WARN`.
4039
4040
4041get_level({log})                                         *vim.log.get_level()*
4042    Gets the current log level.
4043
4044    Parameters: ~
4045      • {log}  (`vim.Log`)
4046
4047    Return: ~
4048        (`vim.log.levels`)
4049
4050new({opts})                                                    *vim.log.new()*
4051    Creates a logger instance.
4052
4053    The logger writes formatted messages to a file, using a per-instance log
4054    level and formatting function.
4055
4056    Parameters: ~
4057      • {opts}  (`table`) A table with the following fields:
4058                • {format_func}?
4059                  (`fun(min_level: vim.log.levels, level: vim.log.levels, ...): string?`)
4060                  Formatter used for each log entry. Receives the logger's
4061                  minimum level, the message level, and the values passed to
4062                  the writer. Return a string to write an entry, or `nil` to
4063                  skip it.
4064                • {level}? (`vim.log.levels`, default: `vim.log.levels.WARN`)
4065                  Minimum level that will be written.
4066                • {name} (`string`) Display name used in notifications emitted
4067                  by the logger.
4068
4069    Return: ~
4070        (`vim.Log`)
4071
4072set_format_func({log}, {func})                     *vim.log.set_format_func()*
4073    Sets the formatter used to produce log entries.
4074
4075    The formatter receives the logger's minimum level, the message level, and
4076    the values passed to the writer method. Return a string to write an entry,
4077    or `nil` to skip it.
4078
4079    Parameters: ~
4080      • {log}   (`vim.Log`)
4081      • {func}  (`fun(min_level: vim.log.levels, level: vim.log.levels, ...): string?`)
4082
4083set_level({log}, {level})                                *vim.log.set_level()*
4084    Sets the current log level.
4085
4086    Entries below this level are skipped.
4087
4088    Parameters: ~
4089      • {log}    (`vim.Log`)
4090      • {level}  (`vim.log.levels`)
4091
4092
4093==============================================================================
4094Lua module: vim.lpeg                                                *vim.lpeg*
4095
4096LPeg is a pattern-matching library for Lua, based on Parsing Expression
4097Grammars (PEGs). https://bford.info/packrat/
4098
4099                                                   *lua-lpeg* *vim.lpeg.Pattern*
4100The LPeg library for parsing expression grammars is included as `vim.lpeg`
4101(https://www.inf.puc-rio.br/~roberto/lpeg/).
4102
4103In addition, its regex-like interface is available as |vim.re|
4104(https://www.inf.puc-rio.br/~roberto/lpeg/re.html).
4105
4106
4107
4108Pattern:match({subject}, {init}, {...})                      *Pattern:match()*
4109    Matches the given `pattern` against the `subject` string. If the match
4110    succeeds, returns the index in the subject of the first character after
4111    the match, or the captured values (if the pattern captured any value). An
4112    optional numeric argument `init` makes the match start at that position in
4113    the subject string. As usual in Lua libraries, a negative value counts
4114    from the end. Unlike typical pattern-matching functions, `match` works
4115    only in anchored mode; that is, it tries to match the pattern with a
4116    prefix of the given subject string (at position `init`), not with an
4117    arbitrary substring of the subject. So, if we want to find a pattern
4118    anywhere in a string, we must either write a loop in Lua or write a
4119    pattern that matches anywhere.
4120
4121    Example: >lua
4122        local pattern = lpeg.R('az') ^ 1 * -1
4123        assert(pattern:match('hello') == 6)
4124        assert(lpeg.match(pattern, 'hello') == 6)
4125        assert(pattern:match('1 hello') == nil)
4126<
4127
4128    Parameters: ~
4129      • {subject}  (`string`)
4130      • {init}     (`integer?`)
4131      • {...}      (`any`)
4132
4133    Return: ~
4134        (`any`) ...
4135
4136vim.lpeg.B({pattern})                                           *vim.lpeg.B()*
4137    Returns a pattern that matches only if the input string at the current
4138    position is preceded by `patt`. Pattern `patt` must match only strings
4139    with some fixed length, and it cannot contain captures. Like the `and`
4140    predicate, this pattern never consumes any input, independently of success
4141    or failure.
4142
4143    Parameters: ~
4144      • {pattern}  (`vim.lpeg.Pattern|string|integer|boolean|table`)
4145
4146    Return: ~
4147        (`vim.lpeg.Pattern`)
4148
4149vim.lpeg.C({patt})                                              *vim.lpeg.C()*
4150    Creates a simple capture, which captures the substring of the subject that
4151    matches `patt`. The captured value is a string. If `patt` has other
4152    captures, their values are returned after this one.
4153
4154    Example: >lua
4155        local function split (s, sep)
4156          sep = lpeg.P(sep)
4157          local elem = lpeg.C((1 - sep) ^ 0)
4158          local p = elem * (sep * elem) ^ 0
4159          return lpeg.match(p, s)
4160        end
4161        local a, b, c = split('a,b,c', ',')
4162        assert(a == 'a')
4163        assert(b == 'b')
4164        assert(c == 'c')
4165<
4166
4167    Parameters: ~
4168      • {patt}  (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
4169
4170    Return: ~
4171        (`vim.lpeg.Capture`)
4172
4173vim.lpeg.Carg({n})                                           *vim.lpeg.Carg()*
4174    Creates an argument capture. This pattern matches the empty string and
4175    produces the value given as the nth extra argument given in the call to
4176    `lpeg.match`.
4177
4178    Parameters: ~
4179      • {n}  (`integer`)
4180
4181    Return: ~
4182        (`vim.lpeg.Capture`)
4183
4184vim.lpeg.Cb({name})                                            *vim.lpeg.Cb()*
4185    Creates a back capture. This pattern matches the empty string and produces
4186    the values produced by the most recent group capture named `name` (where
4187    `name` can be any Lua value). Most recent means the last complete
4188    outermost group capture with the given name. A Complete capture means that
4189    the entire pattern corresponding to the capture has matched. An Outermost
4190    capture means that the capture is not inside another complete capture. In
4191    the same way that LPeg does not specify when it evaluates captures, it
4192    does not specify whether it reuses values previously produced by the group
4193    or re-evaluates them.
4194
4195    Parameters: ~
4196      • {name}  (`any`)
4197
4198    Return: ~
4199        (`vim.lpeg.Capture`)
4200
4201vim.lpeg.Cc({...})                                             *vim.lpeg.Cc()*
4202    Creates a constant capture. This pattern matches the empty string and
4203    produces all given values as its captured values.
4204
4205    Parameters: ~
4206      • {...}  (`any`)
4207
4208    Return: ~
4209        (`vim.lpeg.Capture`)
4210
4211vim.lpeg.Cf({patt}, {func})                                    *vim.lpeg.Cf()*
4212    Creates a fold capture. If `patt` produces a list of captures C1 C2 ...
4213    Cn, this capture will produce the value
4214    `func(...func(func(C1, C2), C3)...,Cn)`, that is, it will fold (or
4215    accumulate, or reduce) the captures from `patt` using function `func`.
4216    This capture assumes that `patt` should produce at least one capture with
4217    at least one value (of any type), which becomes the initial value of an
4218    accumulator. (If you need a specific initial value, you may prefix a
4219    constant capture to `patt`.) For each subsequent capture, LPeg calls
4220    `func` with this accumulator as the first argument and all values produced
4221    by the capture as extra arguments; the first result from this call becomes
4222    the new value for the accumulator. The final value of the accumulator
4223    becomes the captured value.
4224
4225    Example: >lua
4226        local number = lpeg.R('09') ^ 1 / tonumber
4227        local list = number * (',' * number) ^ 0
4228        local function add(acc, newvalue) return acc + newvalue end
4229        local sum = lpeg.Cf(list, add)
4230        assert(sum:match('10,30,43') == 83)
4231<
4232
4233    Parameters: ~
4234      • {patt}  (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
4235      • {func}  (`fun(acc, newvalue)`)
4236
4237    Return: ~
4238        (`vim.lpeg.Capture`)
4239
4240vim.lpeg.Cg({patt}, {name})                                    *vim.lpeg.Cg()*
4241    Creates a group capture. It groups all values returned by `patt` into a
4242    single capture. The group may be anonymous (if no name is given) or named
4243    with the given name (which can be any non-nil Lua value).
4244
4245    Parameters: ~
4246      • {patt}  (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
4247      • {name}  (`string?`)
4248
4249    Return: ~
4250        (`vim.lpeg.Capture`)
4251
4252vim.lpeg.Cmt({patt}, {fn})                                    *vim.lpeg.Cmt()*
4253    Creates a match-time capture. Unlike all other captures, this one is
4254    evaluated immediately when a match occurs (even if it is part of a larger
4255    pattern that fails later). It forces the immediate evaluation of all its
4256    nested captures and then calls `function`. The given function gets as
4257    arguments the entire subject, the current position (after the match of
4258    `patt`), plus any capture values produced by `patt`. The first value
4259    returned by `function` defines how the match happens. If the call returns
4260    a number, the match succeeds and the returned number becomes the new
4261    current position. (Assuming a subject sand current position `i`, the
4262    returned number must be in the range `[i, len(s) + 1]`.) If the call
4263    returns `true`, the match succeeds without consuming any input (so, to
4264    return true is equivalent to return `i`). If the call returns `false`,
4265    `nil`, or no value, the match fails. Any extra values returned by the
4266    function become the values produced by the capture.
4267
4268    Parameters: ~
4269      • {patt}  (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
4270      • {fn}    (`fun(s: string, i: integer, ...: any)`) (position:
4271                boolean|integer, ...: any)
4272
4273    Return: ~
4274        (`vim.lpeg.Capture`)
4275
4276vim.lpeg.Cp()                                                  *vim.lpeg.Cp()*
4277    Creates a position capture. It matches the empty string and captures the
4278    position in the subject where the match occurs. The captured value is a
4279    number.
4280
4281    Example: >lua
4282        local I = lpeg.Cp()
4283        local function anywhere(p) return lpeg.P({I * p * I + 1 * lpeg.V(1)}) end
4284        local match_start, match_end = anywhere('world'):match('hello world!')
4285        assert(match_start == 7)
4286        assert(match_end == 12)
4287<
4288
4289    Return: ~
4290        (`vim.lpeg.Capture`)
4291
4292vim.lpeg.Cs({patt})                                            *vim.lpeg.Cs()*
4293    Creates a substitution capture. This function creates a substitution
4294    capture, which captures the substring of the subject that matches `patt`,
4295    with substitutions. For any capture inside `patt` with a value, the
4296    substring that matched the capture is replaced by the capture value (which
4297    should be a string). The final captured value is the string resulting from
4298    all replacements.
4299
4300    Example: >lua
4301        local function gsub (s, patt, repl)
4302          patt = lpeg.P(patt)
4303          patt = lpeg.Cs((patt / repl + 1) ^ 0)
4304          return lpeg.match(patt, s)
4305        end
4306        assert(gsub('Hello, xxx!', 'xxx', 'World') == 'Hello, World!')
4307<
4308
4309    Parameters: ~
4310      • {patt}  (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
4311
4312    Return: ~
4313        (`vim.lpeg.Capture`)
4314
4315vim.lpeg.Ct({patt})                                            *vim.lpeg.Ct()*
4316    Creates a table capture. This capture returns a table with all values from
4317    all anonymous captures made by `patt` inside this table in successive
4318    integer keys, starting at 1. Moreover, for each named capture group
4319    created by `patt`, the first value of the group is put into the table with
4320    the group name as its key. The captured value is only the table.
4321
4322    Parameters: ~
4323      • {patt}  (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
4324
4325    Return: ~
4326        (`vim.lpeg.Capture`)
4327
4328vim.lpeg.locale({tab})                                     *vim.lpeg.locale()*
4329    Returns a table with patterns for matching some character classes
4330    according to the current locale. The table has fields named `alnum`,
4331    `alpha`, `cntrl`, `digit`, `graph`, `lower`, `print`, `punct`, `space`,
4332    `upper`, and `xdigit`, each one containing a correspondent pattern. Each
4333    pattern matches any single character that belongs to its class. If called
4334    with an argument `table`, then it creates those fields inside the given
4335    table and returns that table.
4336
4337    Example: >lua
4338        lpeg.locale(lpeg)
4339        local space = lpeg.space ^ 0
4340        local name = lpeg.C(lpeg.alpha ^ 1) * space
4341        local sep = lpeg.S(',;') * space
4342        local pair = lpeg.Cg(name * '=' * space * name) * sep ^ -1
4343        local list = lpeg.Cf(lpeg.Ct('') * pair ^ 0, rawset)
4344        local t = list:match('a=b, c = hi; next = pi')
4345        assert(t.a == 'b')
4346        assert(t.c == 'hi')
4347        assert(t.next == 'pi')
4348        local locale = lpeg.locale()
4349        assert(type(locale.digit) == 'userdata')
4350<
4351
4352    Parameters: ~
4353      • {tab}  (`table?`)
4354
4355    Return: ~
4356        (`vim.lpeg.Locale`)
4357
4358vim.lpeg.match({pattern}, {subject}, {init}, {...})         *vim.lpeg.match()*
4359    Matches the given `pattern` against the `subject` string. If the match
4360    succeeds, returns the index in the subject of the first character after
4361    the match, or the captured values (if the pattern captured any value). An
4362    optional numeric argument `init` makes the match start at that position in
4363    the subject string. As usual in Lua libraries, a negative value counts
4364    from the end. Unlike typical pattern-matching functions, `match` works
4365    only in anchored mode; that is, it tries to match the pattern with a
4366    prefix of the given subject string (at position `init`), not with an
4367    arbitrary substring of the subject. So, if we want to find a pattern
4368    anywhere in a string, we must either write a loop in Lua or write a
4369    pattern that matches anywhere.
4370
4371    Example: >lua
4372        local pattern = lpeg.R('az') ^ 1 * -1
4373        assert(pattern:match('hello') == 6)
4374        assert(lpeg.match(pattern, 'hello') == 6)
4375        assert(pattern:match('1 hello') == nil)
4376<
4377
4378    Parameters: ~
4379      • {pattern}  (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
4380      • {subject}  (`string`)
4381      • {init}     (`integer?`)
4382      • {...}      (`any`)
4383
4384    Return: ~
4385        (`any`) ...
4386
4387vim.lpeg.P({value})                                             *vim.lpeg.P()*
4388    Converts the given value into a proper pattern. The following rules are
4389    applied:
4390    • If the argument is a pattern, it is returned unmodified.
4391    • If the argument is a string, it is translated to a pattern that matches
4392      the string literally.
4393    • If the argument is a non-negative number `n`, the result is a pattern
4394      that matches exactly `n` characters.
4395    • If the argument is a negative number `-n`, the result is a pattern that
4396      succeeds only if the input string has less than `n` characters left:
4397      `lpeg.P(-n)` is equivalent to `-lpeg.P(n)` (see the unary minus
4398      operation).
4399    • If the argument is a boolean, the result is a pattern that always
4400      succeeds or always fails (according to the boolean value), without
4401      consuming any input.
4402    • If the argument is a table, it is interpreted as a grammar (see
4403      Grammars).
4404    • If the argument is a function, returns a pattern equivalent to a
4405      match-time capture over the empty string.
4406
4407    Parameters: ~
4408      • {value}  (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
4409
4410    Return: ~
4411        (`vim.lpeg.Pattern`)
4412
4413vim.lpeg.R({...})                                               *vim.lpeg.R()*
4414    Returns a pattern that matches any single character belonging to one of
4415    the given ranges. Each `range` is a string `xy` of length 2, representing
4416    all characters with code between the codes of `x` and `y` (both
4417    inclusive). As an example, the pattern `lpeg.R('09')` matches any digit,
4418    and `lpeg.R('az', 'AZ')` matches any ASCII letter.
4419
4420    Example: >lua
4421        local pattern = lpeg.R('az') ^ 1 * -1
4422        assert(pattern:match('hello') == 6)
4423<
4424
4425    Parameters: ~
4426      • {...}  (`string`)
4427
4428    Return: ~
4429        (`vim.lpeg.Pattern`)
4430
4431vim.lpeg.S({string})                                            *vim.lpeg.S()*
4432    Returns a pattern that matches any single character that appears in the
4433    given string (the `S` stands for Set). As an example, the pattern
4434    `lpeg.S('+-*/')` matches any arithmetic operator. Note that, if `s` is a
4435    character (that is, a string of length 1), then `lpeg.P(s)` is equivalent
4436    to `lpeg.S(s)` which is equivalent to `lpeg.R(s..s)`. Note also that both
4437    `lpeg.S('')` and `lpeg.R()` are patterns that always fail.
4438
4439    Parameters: ~
4440      • {string}  (`string`)
4441
4442    Return: ~
4443        (`vim.lpeg.Pattern`)
4444
4445vim.lpeg.setmaxstack({max})                           *vim.lpeg.setmaxstack()*
4446    Sets a limit for the size of the backtrack stack used by LPeg to track
4447    calls and choices. The default limit is `400`. Most well-written patterns
4448    need little backtrack levels and therefore you seldom need to change this
4449    limit; before changing it you should try to rewrite your pattern to avoid
4450    the need for extra space. Nevertheless, a few useful patterns may
4451    overflow. Also, with recursive grammars, subjects with deep recursion may
4452    also need larger limits.
4453
4454    Parameters: ~
4455      • {max}  (`integer`)
4456
4457vim.lpeg.type({value})                                       *vim.lpeg.type()*
4458    Returns the string `"pattern"` if the given value is a pattern, otherwise
4459    `nil`.
4460
4461    Parameters: ~
4462      • {value}  (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
4463
4464    Return: ~
4465        (`"pattern"?`)
4466
4467vim.lpeg.V({v})                                                 *vim.lpeg.V()*
4468    Creates a non-terminal (a variable) for a grammar. This operation creates
4469    a non-terminal (a variable) for a grammar. The created non-terminal refers
4470    to the rule indexed by `v` in the enclosing grammar.
4471
4472    Example: >lua
4473        local b = lpeg.P({'(' * ((1 - lpeg.S '()') + lpeg.V(1)) ^ 0 * ')'})
4474        assert(b:match('((string))') == 11)
4475        assert(b:match('(') == nil)
4476<
4477
4478    Parameters: ~
4479      • {v}  (`boolean|string|number|function|table|thread|userdata|lightuserdata`)
4480
4481    Return: ~
4482        (`vim.lpeg.Pattern`)
4483
4484vim.lpeg.version()                                        *vim.lpeg.version()*
4485    Returns a string with the running version of LPeg.
4486
4487    Return: ~
4488        (`string`)
4489
4490
4491==============================================================================
4492Lua module: vim.mpack                                              *vim.mpack*
4493
4494This module provides encoding and decoding of Lua objects to and from
4495msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
4496
4497
4498vim.mpack.decode({str})                                   *vim.mpack.decode()*
4499    Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object.
4500
4501    Parameters: ~
4502      • {str}  (`string`)
4503
4504    Return: ~
4505        (`any`)
4506
4507vim.mpack.encode({obj})                                   *vim.mpack.encode()*
4508    Encodes (or "packs") Lua object {obj} as msgpack in a Lua string.
4509
4510    Parameters: ~
4511      • {obj}  (`any`)
4512
4513    Return: ~
4514        (`string`)
4515
4516
4517==============================================================================
4518Lua module: vim.net                                                  *vim.net*
4519
4520*vim.net.request.Response*
4521
4522    Fields: ~
4523      • {body}  (`string`) The HTTP body of the request
4524
4525
4526                                                           *vim.net.request()*
4527vim.net.request({method}, {url}, {opts}, {on_response})
4528    Makes an HTTP request to the given URL, asynchronously passing the result
4529    to the specified `on_response`, `outpath` or `outbuf`.
4530
4531    Examples: >lua
4532        -- Write response body to file.
4533        vim.net.request('https://neovim.io/charter/', {
4534          outpath = 'vision.html',
4535        })
4536
4537        -- Process the response.
4538        vim.net.request(
4539          'https://api.github.com/repos/neovim/neovim',
4540          {},
4541          function (err, res)
4542            if err then return end
4543            local stars = vim.json.decode(res.body).stargazers_count
4544            vim.print(('Neovim currently has %d stars'):format(stars))
4545          end
4546        )
4547
4548        -- Write to both file and current buffer, but cancel it.
4549        local job = vim.net.request('https://neovim.io/charter/', {
4550          outpath = 'vision.html',
4551          outbuf = 0,
4552        })
4553        job:close()
4554
4555        -- Add custom headers in the request.
4556        vim.net.request('https://neovim.io/charter/', {
4557          headers = { Authorization = 'Bearer XYZ' },
4558        })
4559
4560        -- POST request with body.
4561        vim.net.request('POST', 'https://example.com/api', {
4562          body = '{"key": "value"}',
4563          headers = {['Content-Type'] = 'application/json' }
4564        })
4565<
4566
4567    Parameters: ~
4568      • {method}       (`vim.net.HttpMethod`) (default: GET) The HTTP method
4569                       (GET, POST, PUT, PATCH, HEAD, DELETE).
4570      • {url}          (`string`) The URL for the request.
4571      • {opts}         (`table?`) A table with the following fields:
4572                       • {body}? (`string`) Request body for POST/PUT/PATCH
4573                         requests.
4574                       • {headers}? (`table<string, string>`) Custom headers
4575                         to send with the request. Supports basic key/value
4576                         headers and empty headers as supported by curl. Does
4577                         not support "@filename" style, internal header
4578                         deletion ("Header:").
4579                       • {outbuf}? (`integer`) Buffer to save the response
4580                         body to.
4581                       • {outpath}? (`string`) File path to save the response
4582                         body to.
4583                       • {retry}? (`integer`) Number of retries on transient
4584                         failures (default: 3).
4585                       • {verbose}? (`boolean`) Enables verbose output.
4586      • {on_response}  (`vim.net.request.ResponseFunc?`) Callback invoked on
4587                       request completion.
4588
4589    Overloads: ~
4590      • `fun(url: string, opts: vim.net.request.Opts, response: vim.net.request.ResponseFunc)`
4591      • `fun(method: vim.net.HttpMethod, url: string, opts: vim.net.request.Opts, response: vim.net.request.ResponseFunc)`
4592
4593    Return: ~
4594        (`{ close: fun() }`) Object with `close()` method which cancels the
4595        request.
4596
4597
4598==============================================================================
4599Lua module: vim.pos                                                  *vim.pos*
4600
4601EXPERIMENTAL: This API is unstable, do not use it. Its semantics are not yet
4602finalized. Subscribe to this issue to stay updated:
4603https://github.com/neovim/neovim/issues/25509
4604
4605Provides operations to compare, calculate, and convert positions represented
4606by |vim.Pos| objects.
4607
4608
4609*vim.Pos*
4610    Represents a buffer position based on |api-indexing| (0-indexed,
4611    end-exclusive ranges). Call `vim.pos()` to create a new `vim.Pos` by
4612    passing the {buf}, {row}, and {col} of a position.
4613
4614    Example: >lua
4615        local pos1 = vim.pos(0, 3, 5)
4616        local pos2 = vim.pos(0, 4, 0)
4617
4618        -- Operators are overloaded for comparing two `vim.Pos` objects.
4619        if pos1 < pos2 then
4620          print("pos1 comes before pos2")
4621        end
4622
4623        if pos1 ~= pos2 then
4624          print("pos1 and pos2 are different positions")
4625        end
4626<
4627
4628    It may include optional fields that enable additional capabilities, such
4629    as format conversions.
4630
4631    Fields: ~
4632      • {buf}  (`integer`) buffer handle.
4633      • {col}  (`integer`) 0-based byte index.
4634      • {row}  (`integer`) 0-based byte index.
4635
4636
4637cursor({buf}, {pos})                                        *vim.pos.cursor()*
4638    Creates a new |vim.Pos| from cursor position (see |api-indexing|).
4639
4640    If {pos} is omitted, the first argument is treated as {win} instead of
4641    {buf}, and the current cursor position of {win} is used. If {win} is also
4642    omitted, it defaults to the current window.
4643
4644    Example: >lua
4645        local buf = vim.api.nvim_win_get_buf(0)
4646        local cursor_pos = vim.api.nvim_win_get_cursor(0)
4647        local pos = vim.pos.cursor(buf, cursor_pos)
4648        -- This is equivalent:
4649        local pos = vim.pos.cursor(0)
4650<
4651
4652    Parameters: ~
4653      • {buf}  (`integer`)
4654      • {pos}  (`[integer, integer]`) (lnum, col) tuple
4655
4656    Overloads: ~
4657      • `fun(win?: integer): vim.Pos`
4658
4659    Return: ~
4660        (`vim.Pos`)
4661
4662extmark({buf}, {row}, {col})                               *vim.pos.extmark()*
4663    Creates a new |vim.Pos| from extmark position (see |api-indexing|).
4664
4665    Example: >lua
4666        local pos = vim.pos.extmark(0, 3, 5)
4667<
4668
4669    Parameters: ~
4670      • {buf}  (`integer`)
4671      • {row}  (`integer`)
4672      • {col}  (`integer`)
4673
4674    Return: ~
4675        (`vim.Pos`)
4676
4677lsp({buf}, {pos}, {position_encoding})                         *vim.pos.lsp()*
4678    Creates a new |vim.Pos| from `lsp.Position`.
4679
4680    Example: >lua
4681        local lsp_pos = {
4682          line = 3,
4683          character = 5
4684        }
4685
4686        local pos = vim.pos.lsp(0, lsp_pos, 'utf-16')
4687<
4688
4689    Parameters: ~
4690      • {buf}                (`integer`)
4691      • {pos}                (`lsp.Position`)
4692      • {position_encoding}  (`lsp.PositionEncodingKind`)
4693
4694    Return: ~
4695        (`vim.Pos`)
4696
4697mark({buf}, {lnum}, {col})                                    *vim.pos.mark()*
4698    Creates a new |vim.Pos| from mark position (see |api-indexing|).
4699
4700    Example: >lua
4701        local mark_info = vim.api.nvim_get_mark('M')
4702        local lnum, col, buf, name = unpack(mark_info)
4703
4704        if lnum == 0 and col == 0 and buf == 0 then
4705          return -- mark 'M' is not set.
4706        end
4707
4708        local pos = vim.pos.mark(buf, lnum, col)
4709<
4710
4711    Parameters: ~
4712      • {buf}   (`integer`)
4713      • {lnum}  (`integer`)
4714      • {col}   (`integer`)
4715
4716    Return: ~
4717        (`vim.Pos`)
4718
4719offset({buf}, {offset})                                     *vim.pos.offset()*
4720    Creates a new |vim.Pos| from buffer (bytes) offset.
4721
4722    Example: >lua
4723        local offset = vim.api.nvim_buf_get_offset(0, vim.api.nvim_buf_line_count(0))
4724        local pos = vim.pos.offset(0, offset)
4725<
4726
4727    Parameters: ~
4728      • {buf}     (`integer`)
4729      • {offset}  (`integer`)
4730
4731    Return: ~
4732        (`vim.Pos`)
4733
4734to_cursor({pos})                                         *vim.pos.to_cursor()*
4735    Converts |vim.Pos| to cursor position (see |api-indexing|).
4736
4737    Example: >lua
4738        local pos = vim.pos(0, 3, 5)
4739
4740        -- Convert to cursor position, you can call it in a method style.
4741        local cursor_pos = pos:to_cursor()
4742        vim.api.nvim_win_set_cursor(0, cursor_pos)
4743<
4744
4745    Parameters: ~
4746      • {pos}  (`vim.Pos`)
4747
4748    Return: ~
4749        (`[integer, integer]`) (lnum, col) tuple
4750
4751to_extmark({pos})                                       *vim.pos.to_extmark()*
4752    Converts |vim.Pos| to extmark position (see |api-indexing|).
4753
4754    Example: >lua
4755        local pos = vim.pos(0, 3, 5)
4756
4757        -- Convert to extmark position, you can call it in a method style.
4758        local extmark_pos = pos:to_extmark()
4759<
4760
4761    Parameters: ~
4762      • {pos}  (`vim.Pos`)
4763
4764    Return (multiple): ~
4765        (`integer`) row
4766        (`integer`) col
4767
4768to_lsp({pos}, {position_encoding})                          *vim.pos.to_lsp()*
4769    Converts |vim.Pos| to `lsp.Position`.
4770
4771    Example: >lua
4772        local pos = vim.pos(0, 3, 5)
4773
4774        -- Convert to LSP position, you can call it in a method style.
4775        local lsp_pos = pos:to_lsp('utf-16')
4776<
4777
4778    Parameters: ~
4779      • {pos}                (`vim.Pos`)
4780      • {position_encoding}  (`lsp.PositionEncodingKind`)
4781
4782    Return: ~
4783        (`lsp.Position`)
4784
4785to_mark({pos})                                             *vim.pos.to_mark()*
4786    Converts |vim.Pos| to mark position (see |api-indexing|).
4787
4788    Example: >lua
4789        local pos = vim.pos(0, 3, 5)
4790
4791        -- Convert to mark position, you can call it in a method style.
4792        local lnum, col = pos:to_mark()
4793        vim.api.nvim_buf_set_mark(0, 'M', lnum, col)
4794<
4795
4796    Parameters: ~
4797      • {pos}  (`vim.Pos`)
4798
4799    Return (multiple): ~
4800        (`integer`) lnum
4801        (`integer`) col
4802
4803to_offset({pos})                                         *vim.pos.to_offset()*
4804    Converts |vim.Pos| to buffer (bytes) offset.
4805
4806    Example: >lua
4807        local p1 = vim.pos(0, 3, 5)
4808        local p2 = vim.pos(0, 4, 0)
4809
4810        -- Convert to buffer offset, you can call it in a method style.
4811        local offset1 = p1:to_offset()
4812        local offset2 = p2:to_offset()
4813        -- Can be used to calculate the distance between two locations.
4814        local distance = offset2 - offset1
4815<
4816
4817    Parameters: ~
4818      • {pos}  (`vim.Pos`)
4819
4820    Return: ~
4821        (`integer`)
4822
4823
4824==============================================================================
4825Lua module: vim.range                                              *vim.range*
4826
4827EXPERIMENTAL: This API is unstable, do not use it. Its semantics are not yet
4828finalized. Subscribe to this issue to stay updated:
4829https://github.com/neovim/neovim/issues/25509
4830
4831Provides operations to compare, calculate, and convert ranges represented by
4832|vim.Range| objects.
4833
4834
4835*vim.Range*
4836    Represents a range based on |api-indexing| (0-indexed, end-exclusive).
4837    Call `vim.range()` to create a new range by passing start and end
4838    positions (|vim.Pos|).
4839
4840    Both positions must have the same optional fields, which may enable
4841    additional capabilities (such as format conversions).
4842
4843    Example: >lua
4844        local pos1 = vim.pos(0, 3, 5)
4845        local pos2 = vim.pos(0, 4, 0)
4846
4847        -- Create a range from two positions.
4848        local range1 = vim.range(pos1, pos2)
4849        -- Or create a range from four integers representing start and end positions.
4850        local range2 = vim.range(0, 3, 5, 4, 0)
4851
4852        -- Because `vim.Range` is end exclusive, `range1` and `range2` both represent
4853        -- a range starting at the row 3, column 5 and ending at where the row 3 ends
4854        -- (including the newline at the end of line 3).
4855
4856        -- Operators are overloaded for comparing two `vim.Pos` objects.
4857        if range1 == range2 then
4858          print("range1 and range2 are the same range")
4859        end
4860<
4861
4862    Fields: ~
4863      • {buf}        (`integer`) Optional buffer handle.
4864      • {end_col}    (`integer`) 0-based byte index.
4865      • {end_row}    (`integer`) 0-based byte index.
4866      • {start_col}  (`integer`) 0-based byte index.
4867      • {start_row}  (`integer`) 0-based byte index.
4868
4869
4870                                                         *vim.range.extmark()*
4871extmark({buf}, {start_row}, {start_col}, {end_row}, {end_col})
4872    Creates a new |vim.Range| from extmark range (see |api-indexing|).
4873
4874    Example: >lua
4875        local range = vim.range.extmark(0, 3, 5, 4, 0)
4876<
4877
4878    Parameters: ~
4879      • {buf}        (`integer`)
4880      • {start_row}  (`integer`)
4881      • {start_col}  (`integer`)
4882      • {end_row}    (`integer`)
4883      • {end_col}    (`integer`)
4884
4885    Return: ~
4886        (`vim.Range`)
4887
4888has({outer}, {inner})                                        *vim.range.has()*
4889    Checks whether {outer} range contains {inner} range or position.
4890
4891    Parameters: ~
4892      • {outer}  (`vim.Range`)
4893      • {inner}  (`vim.Range|vim.Pos`)
4894
4895    Return: ~
4896        (`boolean`) `true` if {outer} range fully contains {inner} range or
4897        position.
4898
4899intersect({r1}, {r2})                                  *vim.range.intersect()*
4900    Computes the common range shared by the given ranges.
4901
4902    Parameters: ~
4903      • {r1}  (`vim.Range`) First range to intersect.
4904      • {r2}  (`vim.Range`) Second range to intersect
4905
4906    Return: ~
4907        (`vim.Range?`) range that is present inside both `r1` and `r2`. `nil`
4908        if such range does not exist.
4909
4910is_empty({range})                                       *vim.range.is_empty()*
4911    Checks whether the given range is empty; i.e., start >= end.
4912
4913    Parameters: ~
4914      • {range}  (`vim.Range`)
4915
4916    Return: ~
4917        (`boolean`) `true` if the given range is empty.
4918
4919lsp({buf}, {range}, {position_encoding})                     *vim.range.lsp()*
4920    Creates a new |vim.Range| from `lsp.Range`.
4921
4922    Example: >lua
4923        local lsp_range = {
4924          ['start'] = { line = 3, character = 5 },
4925          ['end'] = { line = 4, character = 0 }
4926        }
4927
4928        local range = vim.range.lsp(0, lsp_range, 'utf-16')
4929<
4930
4931    Parameters: ~
4932      • {buf}                (`integer`)
4933      • {range}              (`lsp.Range`)
4934      • {position_encoding}  (`lsp.PositionEncodingKind`)
4935
4936    Return: ~
4937        (`vim.Range`)
4938
4939                                                            *vim.range.mark()*
4940mark({buf}, {start_lnum}, {start_col}, {end_lnum}, {end_col})
4941    Creates a new |vim.Range| from "mark-indexed" range (see |api-indexing|).
4942
4943    Example: >lua
4944        -- A range represented by marks may be end-inclusive (decided by 'selection' option).
4945        local start_lnum, start_col = unpack(api.nvim_buf_get_mark(bufnr, '<'))
4946        local end_lnum, end_col = unpack(api.nvim_buf_get_mark(bufnr, '>'))
4947
4948        -- Create an end-exclusive range.
4949        local range = vim.range.mark(0, start_lnum, start_col, end_lnum, end_col)
4950<
4951
4952    Parameters: ~
4953      • {buf}         (`integer`)
4954      • {start_lnum}  (`integer`)
4955      • {start_col}   (`integer`)
4956      • {end_lnum}    (`integer`)
4957      • {end_col}     (`integer`)
4958
4959    Return: ~
4960        (`vim.Range`)
4961
4962to_extmark({range})                                   *vim.range.to_extmark()*
4963    Converts |vim.Range| to extmark range (see |api-indexing|).
4964
4965    Example: >lua
4966        local range = vim.range(0, 3, 5, 4, 0)
4967
4968        -- Convert to extmark range, you can call it in a method style.
4969        local extmark_range = range:to_extmark()
4970<
4971
4972    Parameters: ~
4973      • {range}  (`vim.Range`)
4974
4975    Return (multiple): ~
4976        (`integer`) start_row
4977        (`integer`) start_col
4978        (`integer`) end_row
4979        (`integer`) end_col
4980
4981to_lsp({range}, {position_encoding})                      *vim.range.to_lsp()*
4982    Converts |vim.Range| to `lsp.Range`.
4983
4984    Example: >lua
4985        local range = vim.range(0, 3, 5, 4, 0)
4986
4987        -- Convert to LSP range, you can call it in a method style.
4988        local lsp_range = range:to_lsp('utf-16')
4989<
4990
4991    Parameters: ~
4992      • {range}              (`vim.Range`)
4993      • {position_encoding}  (`lsp.PositionEncodingKind`)
4994
4995    Return: ~
4996        (`lsp.Range`)
4997
4998to_mark({range})                                         *vim.range.to_mark()*
4999    Converts |vim.Range| to extmark range (see |api-indexing|).
5000
5001    Example: >lua
5002        local range = vim.range(0, 3, 5, 4, 0)
5003
5004        -- Convert to mark range, you can call it in a method style.
5005        local start_lnum, start_col, end_lnum, end_col = range:to_mark()
5006<
5007
5008    Parameters: ~
5009      • {range}  (`vim.Range`)
5010
5011    Return (multiple): ~
5012        (`integer`) start_lnum
5013        (`integer`) start_col
5014        (`integer`) end_lnum
5015        (`integer`) end_col
5016
5017
5018==============================================================================
5019Lua module: vim.re                                                    *vim.re*
5020
5021The `vim.re` module provides a conventional regex-like syntax for pattern
5022usage within LPeg |vim.lpeg|. (Unrelated to |vim.regex| which provides Vim
5023|regexp| from Lua.)
5024
5025See https://www.inf.puc-rio.br/~roberto/lpeg/re.html for the original
5026documentation including regex syntax and examples.
5027
5028
5029vim.re.compile({string}, {defs})                            *vim.re.compile()*
5030    Compiles the given {string} and returns an equivalent LPeg pattern. The
5031    given string may define either an expression or a grammar. The optional
5032    {defs} table provides extra Lua values to be used by the pattern.
5033
5034    Parameters: ~
5035      • {string}  (`string`)
5036      • {defs}    (`table?`)
5037
5038    Return: ~
5039        (`vim.lpeg.Pattern`)
5040
5041vim.re.find({subject}, {pattern}, {init})                      *vim.re.find()*
5042    Searches the given {pattern} in the given {subject}. If it finds a match,
5043    returns the index where this occurrence starts and the index where it
5044    ends. Otherwise, returns nil.
5045
5046    An optional numeric argument {init} makes the search starts at that
5047    position in the subject string. As usual in Lua libraries, a negative
5048    value counts from the end.
5049
5050    Parameters: ~
5051      • {subject}  (`string`)
5052      • {pattern}  (`vim.lpeg.Pattern|string`)
5053      • {init}     (`integer?`)
5054
5055    Return (multiple): ~
5056        (`integer?`) the index where the occurrence starts, nil if no match
5057        (`integer?`) the index where the occurrence ends, nil if no match
5058
5059vim.re.gsub({subject}, {pattern}, {replacement})               *vim.re.gsub()*
5060    Does a global substitution, replacing all occurrences of {pattern} in the
5061    given {subject} by {replacement}.
5062
5063    Parameters: ~
5064      • {subject}      (`string`)
5065      • {pattern}      (`vim.lpeg.Pattern|string`)
5066      • {replacement}  (`string`)
5067
5068    Return: ~
5069        (`string`)
5070
5071vim.re.match({subject}, {pattern}, {init})                    *vim.re.match()*
5072    Matches the given {pattern} against the given {subject}, returning all
5073    captures.
5074
5075    Parameters: ~
5076      • {subject}  (`string`)
5077      • {pattern}  (`vim.lpeg.Pattern|string`)
5078      • {init}     (`integer?`)
5079
5080    Return: ~
5081        (`integer|vim.lpeg.Capture?`)
5082
5083    See also: ~
5084      • vim.lpeg.match()
5085
5086vim.re.updatelocale()                                  *vim.re.updatelocale()*
5087    Updates the pre-defined character classes to the current locale.
5088
5089
5090==============================================================================
5091Lua module: vim.regex                                              *vim.regex*
5092
5093The `vim.regex` interface allows Lua code to use Vim regexes.
5094• Matches within a single line.
5095• Does not check for interrupts (CTRL-C), so can be used from an |api-fast|
5096  context.
5097
5098
5099                                                          *regex:match_line()*
5100regex:match_line({buf}, {line_idx}, {start}, {end_})
5101    Matches line at `line_idx` (zero-based) in buffer `buf`. Match is
5102    restricted to byte index range `start` and `end_` if given, otherwise see
5103    |regex:match_str()|. Returned byte indices are relative to `start` if
5104    given.
5105
5106    Parameters: ~
5107      • {buf}       (`integer`)
5108      • {line_idx}  (`integer`)
5109      • {start}     (`integer?`)
5110      • {end_}      (`integer?`)
5111
5112    Return (multiple): ~
5113        (`integer?`) match start (byte index) relative to `start`, or `nil` if
5114        no match
5115        (`integer?`) match end (byte index) relative to `start`, or `nil` if
5116        no match
5117
5118regex:match_str({str})                                     *regex:match_str()*
5119    Matches string `str` against this regex. To match the string precisely,
5120    surround the regex with "^" and "$". Returns the byte indices for the
5121    start and end of the match, or `nil` if there is no match. Because any
5122    integer is "truthy", `regex:match_str()` can be directly used as a
5123    condition in an if-statement.
5124
5125    Parameters: ~
5126      • {str}  (`string`)
5127
5128    Return (multiple): ~
5129        (`integer?`) match start (byte index), or `nil` if no match
5130        (`integer?`) match end (byte index), or `nil` if no match
5131
5132vim.regex({re})                                                  *vim.regex()*
5133    Parses the Vim regex `re` and returns a regex object. Regexes are "magic"
5134    and case-sensitive by default, regardless of 'magic' and 'ignorecase'.
5135    They can be controlled with flags, see |/magic| and |/ignorecase|.
5136
5137    Parameters: ~
5138      • {re}  (`string`)
5139
5140    Return: ~
5141        (`vim.regex`)
5142
5143
5144==============================================================================
5145Lua module: vim.secure                                            *vim.secure*
5146
5147vim.secure.read({path})                                    *vim.secure.read()*
5148    If {path} is a file: attempt to read the file, prompting the user if the
5149    file should be trusted.
5150
5151    If {path} is a directory: return true if the directory is trusted
5152    (non-recursive), prompting the user as necessary.
5153
5154    The user's choice is persisted in a trust database at
5155    $XDG_STATE_HOME/nvim/trust.
5156
5157    Attributes: ~
5158        Since: 0.9.0
5159
5160    Parameters: ~
5161      • {path}  (`string`) Path to a file or directory to read.
5162
5163    Return: ~
5164        (`boolean|string?`) If {path} is not trusted or does not exist,
5165        returns `nil`. Otherwise, returns the contents of {path} if it is a
5166        file, or true if {path} is a directory.
5167
5168    See also: ~
5169      • |:trust|
5170
5171vim.secure.trust({opts})                                  *vim.secure.trust()*
5172    Manage the trust database.
5173
5174    The trust database is located at |$XDG_STATE_HOME|/nvim/trust.
5175
5176    Attributes: ~
5177        Since: 0.9.0
5178
5179    Parameters: ~
5180      • {opts}  (`table`) A table with the following fields:
5181                • {action} (`'allow'|'deny'|'remove'`) One of:
5182                  • `'allow'` to add a file to the trust database and trust
5183                    it,
5184                  • `'deny'` to add a file to the trust database and deny it,
5185                  • `'remove'` to remove file from the trust database
5186                • {bufnr}? (`integer`) Buffer number to update. Mutually
5187                  exclusive with {path}.
5188                • {path}? (`string`) Path to a file to update. Mutually
5189                  exclusive with {bufnr}.
5190
5191    Return (multiple): ~
5192        (`boolean`) success true if operation was successful
5193        (`string`) msg full path if operation was successful, else error
5194        message
5195
5196
5197==============================================================================
5198Lua module: vim.snippet                                          *vim.snippet*
5199
5200Snippet expansion and navigation.
5201
5202Internal autocmds live in the `nvim.snippet` augroup. To disable them (e.g. to
5203manage sessions yourself), clear it: >lua
5204    vim.api.nvim_clear_autocmds({ group = 'nvim.snippet', buffer = 0 })
5205<
5206
5207Heads-up: |vim.snippet.jump()| re-registers them on every jump.
5208
5209
5210*vim.snippet.ActiveFilter*
5211
5212    Fields: ~
5213      • {direction}  (`vim.snippet.Direction`) Navigation direction. -1 for
5214                     previous, 1 for next.
5215
5216
5217vim.snippet.active({filter})                            *vim.snippet.active()*
5218    Returns `true` if there's an active snippet in the current buffer,
5219    applying the given filter if provided.
5220
5221    Parameters: ~
5222      • {filter}  (`vim.snippet.ActiveFilter?`) Filter to constrain the search
5223                  with:
5224                  • `direction` (vim.snippet.Direction): Navigation direction.
5225                    Will return `true` if the snippet can be jumped in the
5226                    given direction.
5227
5228    Return: ~
5229        (`boolean`)
5230
5231vim.snippet.expand({input})                             *vim.snippet.expand()*
5232    Expands the given snippet text. Refer to
5233    https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax
5234    for the specification of valid input.
5235
5236    Tabstops are highlighted with |hl-SnippetTabstop| and
5237    |hl-SnippetTabstopActive|.
5238
5239    Parameters: ~
5240      • {input}  (`string`)
5241
5242vim.snippet.jump({direction})                             *vim.snippet.jump()*
5243    Jumps to the next (or previous) placeholder in the current snippet, if
5244    possible.
5245
5246    By default `<Tab>` is setup to jump if a snippet is active. The default
5247    mapping looks like: >lua
5248        vim.keymap.set({ 'i', 's' }, '<Tab>', function()
5249           if vim.snippet.active({ direction = 1 }) then
5250             return '<Cmd>lua vim.snippet.jump(1)<CR>'
5251           else
5252             return '<Tab>'
5253           end
5254         end, { desc = '...', expr = true, silent = true })
5255<
5256
5257    Parameters: ~
5258      • {direction}  (`vim.snippet.Direction`) Navigation direction. -1 for
5259                     previous, 1 for next.
5260
5261vim.snippet.stop()                                        *vim.snippet.stop()*
5262    Exits the current snippet.
5263
5264
5265==============================================================================
5266Lua module: vim.spell                                              *vim.spell*
5267
5268vim.spell.check({str})                                     *vim.spell.check()*
5269    Check {str} for spelling errors. Similar to the Vimscript function
5270    |spellbadword()|.
5271
5272    Note: The behaviour of this function is dependent on: 'spelllang',
5273    'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to
5274    the buffer. Consider calling this with |nvim_buf_call()|.
5275
5276    Example: >lua
5277        vim.spell.check("the quik brown fox")
5278        -- =>
5279        -- {
5280        --     {'quik', 'bad', 5}
5281        -- }
5282<
5283
5284    Parameters: ~
5285      • {str}  (`string`)
5286
5287    Return: ~
5288        (`[string, 'bad'|'rare'|'local'|'caps', integer][]`) List of tuples
5289        with three items:
5290        • The badly spelled word.
5291        • The type of the spelling error: "bad" spelling mistake "rare" rare
5292          word "local" word only valid in another region "caps" word should
5293          start with Capital
5294        • The position in {str} where the word begins.
5295
5296
5297==============================================================================
5298Lua module: vim.system                                        *lua-vim-system*
5299
5300*vim.SystemCompleted*
5301
5302    Fields: ~
5303      • {code}     (`integer`)
5304      • {signal}   (`integer`)
5305      • {stderr}?  (`string`) `nil` if stderr is disabled or has a custom
5306                   handler.
5307      • {stdout}?  (`string`) `nil` if stdout is disabled or has a custom
5308                   handler.
5309
5310*vim.SystemObj*
5311
5312    Fields: ~
5313      • {cmd}         (`string[]`) Command name and args
5314      • {is_closing}  (`fun(self: vim.SystemObj): boolean`) See
5315                      |SystemObj:is_closing()|.
5316      • {kill}        (`fun(self: vim.SystemObj, signal: integer|string)`) See
5317                      |SystemObj:kill()|.
5318      • {pid}         (`integer`) Process ID
5319      • {wait}        (`fun(self: vim.SystemObj, timeout: integer?): vim.SystemCompleted`)
5320                      See |SystemObj:wait()|.
5321      • {write}       (`fun(self: vim.SystemObj, data: string[]|string?)`) See
5322                      |SystemObj:write()|.
5323
5324
5325SystemObj:is_closing()                                *SystemObj:is_closing()*
5326    Checks if the process handle is closing or already closed.
5327
5328    This method returns `true` if the underlying process handle is either
5329    `nil` or is in the process of closing. It is useful for determining
5330    whether it is safe to perform operations on the process handle.
5331
5332    Return: ~
5333        (`boolean`)
5334
5335SystemObj:kill({signal})                                    *SystemObj:kill()*
5336    Sends a signal to the process.
5337
5338    The signal can be specified as an integer or as a string.
5339
5340    Example: >lua
5341        local obj = vim.system({'sleep', '10'})
5342        obj:kill('sigterm') -- sends SIGTERM to the process
5343<
5344
5345    Parameters: ~
5346      • {signal}  (`integer|string`) Signal to send to the process. See
5347                  |luv-constants|.
5348
5349SystemObj:wait({timeout})                                   *SystemObj:wait()*
5350    Waits for the process to complete or until the specified timeout elapses.
5351
5352    This method blocks execution until the associated process has exited or
5353    the optional `timeout` (in milliseconds) has been reached. If the process
5354    does not exit before the timeout, it is forcefully terminated with SIGKILL
5355    (signal 9), and the exit code is set to 124.
5356
5357    If no `timeout` is provided, the method will wait indefinitely (or use the
5358    timeout specified in the options when the process was started).
5359
5360    Example: >lua
5361        local obj = vim.system({'echo', 'hello'}, { text = true })
5362        local result = obj:wait(1000) -- waits up to 1000ms
5363        print(result.code, result.signal, result.stdout, result.stderr)
5364<
5365
5366    Parameters: ~
5367      • {timeout}  (`integer?`)
5368
5369    Return: ~
5370        (`vim.SystemCompleted`)
5371
5372SystemObj:write({data})                                    *SystemObj:write()*
5373    Writes data to the stdin of the process or closes stdin.
5374
5375    If `data` is a list of strings, each string is written followed by a
5376    newline.
5377
5378    If `data` is a string, it is written as-is.
5379
5380    If `data` is `nil`, the write side of the stream is shut down and the pipe
5381    is closed.
5382
5383    Example: >lua
5384        local obj = vim.system({'cat'}, { stdin = true })
5385        obj:write({'hello', 'world'}) -- writes 'hello\nworld\n' to stdin
5386        obj:write(nil) -- closes stdin
5387<
5388
5389    Parameters: ~
5390      • {data}  (`string[]|string?`)
5391
5392vim.system({cmd}, {opts}, {on_exit})                            *vim.system()*
5393    Runs a system command or throws an error if {cmd} cannot be run.
5394
5395    The command runs directly (not in 'shell') so shell builtins such as
5396    "echo" in cmd.exe, cmdlets in powershell, or "help" in bash, will not work
5397    unless you actually invoke a shell: `vim.system({'bash', '-c', 'help'})`.
5398
5399    Examples: >lua
5400        local on_exit = function(obj)
5401          print(obj.code)
5402          print(obj.signal)
5403          print(obj.stdout)
5404          print(obj.stderr)
5405        end
5406
5407        -- Runs asynchronously:
5408        vim.system({'echo', 'hello'}, { text = true }, on_exit)
5409
5410        -- Runs synchronously:
5411        local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
5412        -- { code = 0, signal = 0, stdout = 'hello\n', stderr = '' }
5413<
5414
5415    See |uv.spawn()| for more details. Note: unlike |uv.spawn()|, vim.system
5416    throws an error if {cmd} cannot be run.
5417
5418    Parameters: ~
5419      • {cmd}      (`string[]`) Command to execute
5420      • {opts}     (`table?`) A table with the following fields:
5421                   • {clear_env}? (`boolean`) `env` defines the job
5422                     environment exactly, instead of merging current
5423                     environment. Note: if `env` is `nil`, the current
5424                     environment is used but without `NVIM` set.
5425                   • {cwd}? (`string`) Set the current working directory for
5426                     the sub-process.
5427                   • {detach}? (`boolean`) Spawn the child process in a
5428                     detached state - this will make it a process group
5429                     leader, and will effectively enable the child to keep
5430                     running after the parent exits. Note that the child
5431                     process will still keep the parent's event loop alive
5432                     unless the parent process calls |uv.unref()| on the
5433                     child's process handle.
5434                   • {env}? (`table<string,string|number>`) Set environment
5435                     variables for the new process. Inherits the current
5436                     environment with `NVIM` set to |v:servername|.
5437                   • {stderr}? (`fun(err:string?, data: string?)|boolean`,
5438                     default: `true`) Handle output from stderr.
5439                   • {stdin}? (`string|string[]|true`) If `true`, then a pipe
5440                     to stdin is opened and can be written to via the
5441                     `write()` method to SystemObj. If `string` or `string[]`
5442                     then will be written to stdin and closed.
5443                   • {stdout}? (`fun(err:string?, data: string?)|boolean`,
5444                     default: `true`) Handle output from stdout.
5445                   • {text}? (`boolean`) Handle stdout and stderr as text.
5446                     Normalizes line endings by replacing `\r\n` with `\n`.
5447                   • {timeout}? (`integer`) Run the command with a time limit
5448                     in ms. Upon timeout the process is sent the TERM signal
5449                     (15) and the exit code is set to 124.
5450      • {on_exit}  (`fun(out: vim.SystemCompleted)?`) Called when subprocess
5451                   exits. When provided, the command runs asynchronously. See
5452                   return of SystemObj:wait().
5453
5454    Overloads: ~
5455      • `fun(cmd: string[], on_exit: fun(out: vim.SystemCompleted)): vim.SystemObj`
5456
5457    Return: ~
5458        (`vim.SystemObj`)
5459
5460
5461==============================================================================
5462Lua module: vim.text                                                *vim.text*
5463
5464vim.text.diff({a}, {b}, {opts})                              *vim.text.diff()*
5465    Run diff on strings {a} and {b}. Any indices returned by this function,
5466    either directly or via callback arguments, are 1-based.
5467
5468    Examples: >lua
5469        vim.text.diff('a\n', 'b\nc\n')
5470        -- =>
5471        -- @@ -1 +1,2 @@
5472        -- -a
5473        -- +b
5474        -- +c
5475
5476        vim.text.diff('a\n', 'b\nc\n', {result_type = 'indices'})
5477        -- =>
5478        -- {
5479        --   {1, 1, 1, 2}
5480        -- }
5481<
5482
5483    Parameters: ~
5484      • {a}     (`string`) First string to compare
5485      • {b}     (`string`) Second string to compare
5486      • {opts}  (`table?`) Optional parameters:
5487                • {algorithm}? (`'myers'|'minimal'|'patience'|'histogram'`,
5488                  default: `'myers'`) Diff algorithm to use. Values:
5489                  • `myers`: the default algorithm
5490                  • `minimal`: spend extra time to generate the smallest
5491                    possible diff
5492                  • `patience`: patience diff algorithm
5493                  • `histogram`: histogram diff algorithm
5494                • {ctxlen}? (`integer`) Context length
5495                • {ignore_blank_lines}? (`boolean`) Ignore blank lines
5496                • {ignore_cr_at_eol}? (`boolean`) Ignore carriage return at
5497                  end-of-line
5498                • {ignore_whitespace}? (`boolean`) Ignore whitespace
5499                • {ignore_whitespace_change}? (`boolean`) Ignore whitespace
5500                  change
5501                • {ignore_whitespace_change_at_eol}? (`boolean`) Ignore
5502                  whitespace change at end-of-line.
5503                • {indent_heuristic}? (`boolean`) Use the indent heuristic for
5504                  the internal diff library.
5505                • {interhunkctxlen}? (`integer`) Inter hunk context length
5506                • {linematch}? (`boolean|integer`) Run linematch on the
5507                  resulting hunks from xdiff. When integer, only hunks upto
5508                  this size in lines are run through linematch. Requires
5509                  `result_type = indices`, ignored otherwise.
5510                • {on_hunk}?
5511                  (`fun(start_a: integer, count_a: integer, start_b: integer, count_b: integer): integer?`)
5512                  Invoked for each hunk in the diff. Return a negative number
5513                  to cancel the callback for any remaining hunks. Arguments:
5514                  • `start_a` (`integer`): Start line of hunk in {a}.
5515                  • `count_a` (`integer`): Hunk size in {a}.
5516                  • `start_b` (`integer`): Start line of hunk in {b}.
5517                  • `count_b` (`integer`): Hunk size in {b}.
5518                • {result_type}? (`'unified'|'indices'`, default: `'unified'`)
5519                  Form of the returned diff:
5520                  • `unified`: String in unified format.
5521                  • `indices`: Array of hunk locations. Note: This option is
5522                    ignored if `on_hunk` is used.
5523
5524    Return: ~
5525        (`string|integer[][]?`) See {opts.result_type}. `nil` if
5526        {opts.on_hunk} is given.
5527
5528vim.text.hexdecode({enc})                               *vim.text.hexdecode()*
5529    Hex decode a string.
5530
5531    Parameters: ~
5532      • {enc}  (`string`) String to decode
5533
5534    Return (multiple): ~
5535        (`string?`) Decoded string
5536        (`string?`) Error message, if any
5537
5538vim.text.hexencode({str})                               *vim.text.hexencode()*
5539    Hex encode a string.
5540
5541    Parameters: ~
5542      • {str}  (`string`) String to encode
5543
5544    Return: ~
5545        (`string`) Hex encoded string
5546
5547vim.text.indent({size}, {text}, {opts})                    *vim.text.indent()*
5548    Sets the indent (i.e. the common leading whitespace) of non-empty lines in
5549    `text` to `size` spaces/tabs.
5550
5551    Indent is calculated by number of consecutive indent chars.
5552    • The first indented, non-empty line decides the indent char (space/tab):
5553      • `SPC SPC TAB …` = two-space indent.
5554      • `TAB SPC …` = one-tab indent.
5555    • Set `opts.expandtab` to treat tabs as spaces.
5556
5557    To "dedent" (remove the common indent), pass `size=0`: >lua
5558        vim.print(vim.text.indent(0, ' a\n  b\n'))
5559<
5560
5561    To adjust relative-to an existing indent, call indent() twice: >lua
5562        local indented, old_indent = vim.text.indent(0, ' a\n b\n')
5563        indented = vim.text.indent(old_indent + 2, indented)
5564        vim.print(indented)
5565<
5566
5567    To ignore the final, blank line when calculating the indent, use gsub()
5568    before calling indent(): >lua
5569        local text = '  a\n  b\n '
5570        vim.print(vim.text.indent(0, (text:gsub('\n[\t ]+\n?$', '\n'))))
5571<
5572
5573    Parameters: ~
5574      • {size}  (`integer`) Number of spaces.
5575      • {text}  (`string`) Text to indent.
5576      • {opts}  (`{ expandtab?: integer }?`)
5577
5578    Return (multiple): ~
5579        (`string`) Indented text.
5580        (`integer`) Indent size before modification.
5581
5582
5583==============================================================================
5584Lua module: vim.ui                                                    *vim.ui*
5585
5586vim.ui.input({opts}, {on_confirm})                            *vim.ui.input()*
5587    Prompts the user for input, allowing arbitrary (potentially asynchronous)
5588    work until `on_confirm`.
5589
5590    Example: >lua
5591        local opts = { prompt = 'Enter value for shiftwidth: ', scope = 'buffer' }
5592        vim.ui.input(opts, function(input)
5593            vim.o.shiftwidth = tonumber(input)
5594        end)
5595<
5596
5597    Parameters: ~
5598      • {opts}        (`table?`) Additional options. See |input()|
5599                      • {completion}? (`string`) Specifies type of completion
5600                        supported for input. Supported types are the same that
5601                        can be supplied to a user-defined command using the
5602                        "-complete=" argument. See |:command-completion|
5603                      • {default}? (`string`) Default reply to the input
5604                      • {highlight}? (`function`) Function that will be used
5605                        for highlighting user inputs.
5606                      • {prompt}? (`string`) Text of the prompt
5607                      • {scope}?
5608                        (`'cursor'|'line'|'buffer'|'window'|'tabpage'|'editor'|'project'`)
5609                        Input scope, as in "This input is for something at
5610                        cursor/line/etc scope". Can be used by `vim.ui.input`
5611                        implementations to tweak behavior and presentation.
5612                        For example, the input may adjust the floating window
5613                        position: near the cursor if `cursor`, in window
5614                        corner if `buffer` or `window`, etc.
5615      • {on_confirm}  (`fun(input?: string)`) Called once the user confirms or
5616                      abort the input. `input` is what the user typed (it
5617                      might be an empty string if nothing was entered), or
5618                      `nil` if the user aborted the dialog.
5619
5620vim.ui.open({path}, {opt})                                     *vim.ui.open()*
5621    Opens `path` with the system default handler (macOS `open`, Windows
5622    `explorer.exe`, Linux `xdg-open`, …), or returns (but does not show) an
5623    error message on failure.
5624
5625    Can also be invoked with `:Open`.                                  *:Open*
5626
5627    Expands "~/" and environment variables in filesystem paths.
5628
5629    Examples: >lua
5630        -- Asynchronous.
5631        vim.ui.open("https://neovim.io/")
5632        vim.ui.open("~/path/to/file")
5633        -- Use the "osurl" command to handle the path or URL.
5634        vim.ui.open("gh#neovim/neovim!29490", { cmd = { 'osurl' } })
5635        -- Synchronous (wait until the process exits).
5636        local cmd, err = vim.ui.open("$VIMRUNTIME")
5637        if cmd then
5638          cmd:wait()
5639        end
5640<
5641
5642    Parameters: ~
5643      • {path}  (`string`) Path or URL to open
5644      • {opt}   (`table?`) Options
5645                • {cmd}? (`string[]`) Command used to open the path or URL.
5646
5647    Return (multiple): ~
5648        (`vim.SystemObj?`) Command object, or nil if not found.
5649        (`string?`) Error message on failure, or nil on success.
5650
5651    See also: ~
5652      • |vim.system()|
5653
5654vim.ui.progress_status()                            *vim.ui.progress_status()*
5655    Gets a status description summarizing currently running progress messages.
5656    Convenient for inclusion in 'statusline'.
5657
5658    Return: ~
5659        (`string`) Progress status
5660
5661vim.ui.select({items}, {opts}, {on_choice})                  *vim.ui.select()*
5662    Prompts the user to pick from a list of items, allowing arbitrary
5663    (potentially asynchronous) work until `on_choice`. This is the standard
5664    "picker" interface, used by |z=|, |:tselect|, etc.
5665
5666    Plugins may override `vim.ui.select` to provide a custom picker; they are
5667    expected to call the `format_item` and `preview_item` handlers (if any)
5668    provided by the caller. They may also use the `kind` hint (if provided by
5669    the caller) to decide how to handle some items.
5670
5671    Note: the default `vim.ui.select` currently doesn't support preview.
5672
5673    Example: >lua
5674        vim.ui.select({ 'tabs', 'spaces' }, {
5675          prompt = 'Select tabs or spaces:',
5676          format_item = function(item)
5677            return ('I choose %s!'):format(item)
5678          end,
5679          preview_item = function(item)
5680            local lines = { 'This is ' .. vim.inspect(item) }
5681            local buf = vim.api.nvim_create_buf(false, true)
5682            vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
5683            vim.bo[buf].bufhidden = 'wipe'
5684            return { buf = buf }
5685          end,
5686        }, function(choice)
5687          vim.o.expandtab = choice == 'spaces'
5688          vim.print(('Selected "%s" => expandtab=%s'):format(choice, vim.o.expandtab))
5689        end)
5690<
5691
5692    Parameters: ~
5693      • {items}      (`any[]`) Arbitrary items
5694      • {opts}       (`table`) Options
5695                     • {format_item}? (`fun(item: any):string`, default:
5696                       `tostring`) Decides how to format items when displayed
5697                       in the picker.
5698                     • {kind}? (`string`) Arbitrary hint string indicating the
5699                       item shape. The picker may wish to use this to infer
5700                       the structure or semantics of `items`, or the context
5701                       in which select() was called.
5702                     • {preview_item}?
5703                       (`fun(item: any):{buf?:integer, pos?:[integer,integer], pos_end?:[integer,integer]}`)
5704                       Decides how to preview an item by preparing a scratch
5705                       buffer with the item details (including text,
5706                       highlighting, etc.). When the picker decides to
5707                       "preview" an item, it should call this function. Must
5708                       return a table with these keys:
5709                       • {buf}? (`integer`) Buffer containing the previewed
5710                         item details, or nil if no preview should be shown.
5711                       • {pos}? (`[integer, integer]`) Specifies the
5712                         (1,0)-indexed cursor position in the preview buffer.
5713                         If nil, should be treated as `{ 1, 0 }`.
5714                       • {pos_end}? (`[integer, integer]`) Specifies the
5715                         (1,0)-indexed (end-exclusive) end position of the
5716                         preview range. If nil, no range is intended for a
5717                         preview.
5718                     • {prompt}? (`string`, default: `"Select one of:"`)
5719                       Prompt text.
5720      • {on_choice}  (`fun(item: T?, idx: integer?)`) Called once the user
5721                     made a choice. `idx` is the 1-based index of `item`
5722                     within `items`, or `nil` if the user aborted the dialog.
5723
5724
5725==============================================================================
5726Lua module: vim.ui.img                                            *vim.ui.img*
5727
5728EXPERIMENTAL: This API may change in the future. Its semantics are not yet
5729finalized.
5730
5731This provides a functional API for displaying images in Nvim. Currently
5732supports PNG images via the Kitty graphics protocol.
5733
5734To override the image backend, replace `vim.ui.img` with your own
5735implementation providing set/get/del.
5736
5737Examples: >lua
5738    -- Load image bytes from disk and display at row 5, column 10
5739    local id = vim.ui.img.set(
5740     vim.fn.readblob('/path/to/img.png'),
5741     { row = 5, col = 10, width = 40, height = 20, zindex = 50 }
5742    )
5743
5744    -- Update the image position
5745    vim.ui.img.set(id, { row = 8, col = 12 })
5746
5747    -- Retrieve the current image opts
5748    local opts = vim.ui.img.get(id)
5749
5750    -- Remove the image
5751    vim.ui.img.del(id)
5752
5753    -- Remove all images
5754    vim.ui.img.del(math.huge)
5755<
5756
5757
5758vim.ui.img.del({id})                                        *vim.ui.img.del()*
5759    Delete an image, or all images if `math.huge` is given as the id.
5760
5761    Parameters: ~
5762      • {id}  (`integer`) image id, or `math.huge` to delete all images
5763
5764    Return: ~
5765        (`boolean`) found true if any image existed
5766
5767vim.ui.img.get({id})                                        *vim.ui.img.get()*
5768    Get the opts for an image.
5769
5770    Parameters: ~
5771      • {id}  (`integer`)
5772
5773    Return: ~
5774        (`table?`) opts copy of image opts, or nil if not found
5775        • {col}? (`integer`) starting column (1-indexed)
5776        • {height}? (`integer`) height in cells
5777        • {row}? (`integer`) starting row (1-indexed)
5778        • {width}? (`integer`) width in cells
5779        • {zindex}? (`integer`) stacking order (higher = on top)
5780
5781vim.ui.img.set({data_or_id}, {opts})                        *vim.ui.img.set()*
5782    Display an image or update an existing one.
5783
5784    When {data_or_id} is a string, displays the image bytes at the position
5785    given by {opts}. Returns an integer id for later use.
5786
5787    When {data_or_id} is an integer (a previously returned id), updates the
5788    image with new {opts}.
5789
5790    Parameters: ~
5791      • {data_or_id}  (`string|integer`) image bytes (string) or existing id
5792                      (integer)
5793      • {opts}        (`table?`) A table with the following fields:
5794                      • {col}? (`integer`) starting column (1-indexed)
5795                      • {height}? (`integer`) height in cells
5796                      • {row}? (`integer`) starting row (1-indexed)
5797                      • {width}? (`integer`) width in cells
5798                      • {zindex}? (`integer`) stacking order (higher = on top)
5799
5800    Return: ~
5801        (`integer`) id
5802
5803
5804==============================================================================
5805Lua module: vim.uri                                                  *vim.uri*
5806
5807vim.uri_decode({str})                                       *vim.uri_decode()*
5808    URI-decodes a string containing percent escapes.
5809
5810    Parameters: ~
5811      • {str}  (`string`) string to decode
5812
5813    Return: ~
5814        (`string`) decoded string
5815
5816vim.uri_encode({str}, {rfc})                                *vim.uri_encode()*
5817    URI-encodes a string using percent escapes.
5818
5819    Parameters: ~
5820      • {str}  (`string`) string to encode
5821      • {rfc}  (`"rfc2396"|"rfc2732"|"rfc3986"?`)
5822
5823    Return: ~
5824        (`string`) encoded string
5825
5826vim.uri_from_bufnr({buf})                               *vim.uri_from_bufnr()*
5827    Gets a URI from a bufnr.
5828
5829    Parameters: ~
5830      • {buf}  (`integer`)
5831
5832    Return: ~
5833        (`string`) URI
5834
5835vim.uri_from_fname({path})                              *vim.uri_from_fname()*
5836    Gets a URI from a file path.
5837
5838    Parameters: ~
5839      • {path}  (`string`) Path to file
5840
5841    Return: ~
5842        (`string`) URI
5843
5844vim.uri_to_bufnr({uri})                                   *vim.uri_to_bufnr()*
5845    Gets the buffer for a uri. Creates a new unloaded buffer if no buffer for
5846    the uri already exists.
5847
5848    Parameters: ~
5849      • {uri}  (`string`)
5850
5851    Return: ~
5852        (`integer`) bufnr
5853
5854vim.uri_to_fname({uri})                                   *vim.uri_to_fname()*
5855    Gets a filename from a URI.
5856
5857    Parameters: ~
5858      • {uri}  (`string`)
5859
5860    Return: ~
5861        (`string`) filename or unchanged URI for non-file URIs
5862
5863
5864==============================================================================
5865Lua module: vim.version                                          *vim.version*
5866
5867The `vim.version` module provides functions for comparing versions and ranges
5868conforming to the https://semver.org spec. Plugins, and plugin managers, can
5869use this to check available tools and dependencies on the current system.
5870
5871Example: >lua
5872    local v = vim.version.parse(vim.system({'tmux', '-V'}):wait().stdout, {strict=false})
5873    if vim.version.gt(v, {3, 2, 0}) then
5874      -- ...
5875    end
5876<
5877
5878|vim.version()| returns the version of the current Nvim process.
5879
5880VERSION RANGE SPEC                                             *version-range*
5881
5882A version "range spec" defines a semantic version range which can be tested
5883against a version, using |vim.version.range()|.
5884
5885Supported range specs are shown in the following table. Note: suffixed
5886versions (1.2.3-rc1) are not matched. >
5887    1.2.3             is 1.2.3
5888    =1.2.3            is 1.2.3
5889    >1.2.3            greater than 1.2.3
5890    <1.2.3            before 1.2.3
5891    >=1.2.3           at least 1.2.3
5892    <=1.2.3           at most 1.2.3
5893    ~1.2.3            is >=1.2.3 <1.3.0       "reasonably close to 1.2.3"
5894    ^1.2.3            is >=1.2.3 <2.0.0       "compatible with 1.2.3"
5895    ^0.2.3            is >=0.2.3 <0.3.0       (0.x.x is special)
5896    ^0.0.1            is =0.0.1               (0.0.x is special)
5897    ^1.2              is >=1.2.0 <2.0.0       (like ^1.2.0)
5898    ~1.2              is >=1.2.0 <1.3.0       (like ~1.2.0)
5899    ^1                is >=1.0.0 <2.0.0       "compatible with 1"
5900    ~1                same                    "reasonably close to 1"
5901    1.x               same
5902    1.*               same
5903    1                 same
5904    *                 any version
5905    x                 same
5906
5907    1.2.3 - 2.3.4     is >=1.2.3 <2.3.4
5908
5909    Partial right: missing pieces treated as x (2.3 => 2.3.x).
5910    1.2.3 - 2.3       is >=1.2.3 <2.4.0
5911    1.2.3 - 2         is >=1.2.3 <3.0.0
5912
5913    Partial left: missing pieces treated as 0 (1.2 => 1.2.0).
5914    1.2 - 2.3.0       is 1.2.0 - 2.3.0
5915<
5916
5917
5918*vim.VersionRange*
5919
5920    Fields: ~
5921      • {from}  (`vim.Version`)
5922      • {has}   (`fun(self: vim.VersionRange, version: string|vim.Version): boolean`)
5923                See |VersionRange:has()|.
5924      • {to}?   (`vim.Version`)
5925
5926
5927VersionRange:has({version})                               *VersionRange:has()*
5928    Check if a version is in the range (inclusive `from`, exclusive `to`).
5929
5930    Example: >lua
5931        local r = vim.version.range('1.0.0 - 2.0.0')
5932        print(r:has('1.9.9'))       -- true
5933        print(r:has('2.0.0'))       -- false
5934        print(r:has(vim.version())) -- check against current Nvim version
5935<
5936
5937    Or use cmp(), le(), lt(), ge(), gt(), and/or eq() to compare a version
5938    against `.to` and `.from` directly: >lua
5939        local r = vim.version.range('1.0.0 - 2.0.0') -- >=1.0, <2.0
5940        print(vim.version.ge({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to))
5941<
5942
5943    Attributes: ~
5944        Since: 0.9.0
5945
5946    Parameters: ~
5947      • {version}  (`string|vim.Version`)
5948
5949    Return: ~
5950        (`boolean`)
5951
5952    See also: ~
5953      • https://github.com/npm/node-semver#ranges
5954
5955vim.version()                                                  *vim.version()*
5956    Returns the current Nvim version.
5957
5958    Return: ~
5959        (`vim.Version`)
5960
5961vim.version.cmp({v1}, {v2})                                *vim.version.cmp()*
5962    Parses and compares two version objects (the result of
5963    |vim.version.parse()|, or specified literally as a `{major, minor, patch}`
5964    tuple, e.g. `{1, 0, 3}`).
5965
5966    Example: >lua
5967        if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then
5968          -- ...
5969        end
5970        local v1 = vim.version.parse('1.0.3-pre')
5971        local v2 = vim.version.parse('0.2.1')
5972        if vim.version.cmp(v1, v2) == 0 then
5973          -- ...
5974        end
5975<
5976
5977    Note: ~
5978      • Per semver, build metadata is ignored when comparing two
5979        otherwise-equivalent versions.
5980
5981    Attributes: ~
5982        Since: 0.9.0
5983
5984    Parameters: ~
5985      • {v1}  (`vim.Version|number[]|string`) Version object.
5986      • {v2}  (`vim.Version|number[]|string`) Version to compare with `v1`.
5987
5988    Return: ~
5989        (`integer`) -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`.
5990
5991vim.version.eq({v1}, {v2})                                  *vim.version.eq()*
5992    Returns `true` if the given versions are equal. See |vim.version.cmp()|
5993    for usage.
5994
5995    Attributes: ~
5996        Since: 0.9.0
5997
5998    Parameters: ~
5999      • {v1}  (`vim.Version|number[]|string`)
6000      • {v2}  (`vim.Version|number[]|string`)
6001
6002    Return: ~
6003        (`boolean`)
6004
6005vim.version.ge({v1}, {v2})                                  *vim.version.ge()*
6006    Returns `true` if `v1 >= v2`. See |vim.version.cmp()| for usage.
6007
6008    Attributes: ~
6009        Since: 0.10.0
6010
6011    Parameters: ~
6012      • {v1}  (`vim.Version|number[]|string`)
6013      • {v2}  (`vim.Version|number[]|string`)
6014
6015    Return: ~
6016        (`boolean`)
6017
6018vim.version.gt({v1}, {v2})                                  *vim.version.gt()*
6019    Returns `true` if `v1 > v2`. See |vim.version.cmp()| for usage.
6020
6021    Attributes: ~
6022        Since: 0.9.0
6023
6024    Parameters: ~
6025      • {v1}  (`vim.Version|number[]|string`)
6026      • {v2}  (`vim.Version|number[]|string`)
6027
6028    Return: ~
6029        (`boolean`)
6030
6031vim.version.intersect({r1}, {r2})                    *vim.version.intersect()*
6032    Computes the common range shared by the given ranges.
6033
6034    Attributes: ~
6035        Since: 0.12.0
6036
6037    Parameters: ~
6038      • {r1}  (`vim.VersionRange`) First range to intersect.
6039      • {r2}  (`vim.VersionRange`) Second range to intersect.
6040
6041    Return: ~
6042        (`vim.VersionRange?`) Maximal range that is present inside both `r1`
6043        and `r2`. `nil` if such range does not exist.
6044
6045vim.version.last({versions})                              *vim.version.last()*
6046    TODO: generalize this, move to func.lua
6047
6048    Parameters: ~
6049      • {versions}  (`vim.Version[]`)
6050
6051    Return: ~
6052        (`vim.Version?`)
6053
6054vim.version.le({v1}, {v2})                                  *vim.version.le()*
6055    Returns `true` if `v1 <= v2`. See |vim.version.cmp()| for usage.
6056
6057    Attributes: ~
6058        Since: 0.10.0
6059
6060    Parameters: ~
6061      • {v1}  (`vim.Version|number[]|string`)
6062      • {v2}  (`vim.Version|number[]|string`)
6063
6064    Return: ~
6065        (`boolean`)
6066
6067vim.version.lt({v1}, {v2})                                  *vim.version.lt()*
6068    Returns `true` if `v1 < v2`. See |vim.version.cmp()| for usage.
6069
6070    Attributes: ~
6071        Since: 0.9.0
6072
6073    Parameters: ~
6074      • {v1}  (`vim.Version|number[]|string`)
6075      • {v2}  (`vim.Version|number[]|string`)
6076
6077    Return: ~
6078        (`boolean`)
6079
6080vim.version.parse({version}, {opts})                     *vim.version.parse()*
6081    Parses a semantic version string and returns a version object which can be
6082    used with other `vim.version` functions. For example "1.0.1-rc1+build.2"
6083    returns: >
6084        { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
6085<
6086
6087    Attributes: ~
6088        Since: 0.9.0
6089
6090    Parameters: ~
6091      • {version}  (`string`) Version string to parse.
6092      • {opts}     (`table?`) Options for parsing.
6093                   • {strict}? (`boolean`, default: `false`) If `true`, no
6094                     coercion is attempted on input not conforming to semver
6095                     v2.0.0. If `false`, `parse()` attempts to coerce input
6096                     such as "1.0", "0-x", "tmux 3.2a" into valid versions.
6097
6098    Return: ~
6099        (`vim.Version?`) `Version` object or `nil` if input is invalid.
6100
6101    See also: ~
6102      • https://semver.org/spec/v2.0.0.html
6103
6104vim.version.range({spec})                                *vim.version.range()*
6105    Parses a semver |version-range| "spec" and returns |vim.VersionRange|
6106    object:
6107
6108    Attributes: ~
6109        Since: 0.9.0
6110
6111    Parameters: ~
6112      • {spec}  (`string`) Version range "spec"
6113
6114    Return: ~
6115        (`vim.VersionRange?`)
6116
6117
6118==============================================================================
6119UI2                                                                      *ui2*
6120
6121WARNING: This is an experimental feature intended to replace the builtin
6122message + cmdline presentation layer.
6123
6124To enable this feature (default opts shown, see also 'messagesopt'): >lua
6125    require('vim._core.ui2').enable({
6126      enable = true, -- Whether to enable or disable the UI.
6127      msg = { -- Options related to the message module.
6128        ---@type string|table<string, 'cmd'|'msg'|'pager'> Default message target
6129        ---or table mapping |ui-messages| kinds, triggers and IDs to a target.
6130        ---Table keys are matched as a Lua pattern to the message ID. 'default'
6131        ---mapping applies to any omitted kind: { default = 'cmd', progress = 'msg' }.
6132        targets = 'cmd',
6133        dialog = { -- Options related to dialog window.
6134          height = 0.5, -- Maximum height.
6135        },
6136        msg = { -- Options related to msg window.
6137          height = 0.5, -- Maximum height.
6138        },
6139        pager = { -- Options related to message window.
6140          height = 0.999, -- Maximum height.
6141        },
6142      },
6143    })
6144<
6145
6146ui2 behavior is also configured by these 'messagesopt' items: "pager",
6147"timeout". Example: >vim
6148    set messagesopt+=maxheight:50,pager:<CR>,timeout:4000
6149<
6150
6151There are four special windows/buffers for presenting messages and cmdline:
6152• "cmd": Cmdline. Also used by default for messages, 'showcmd', 'showmode',
6153  'ruler'.
6154• "msg": Message window. Shows ephemeral messages; useful if 'cmdheight' is 0.
6155• "pager": Pager window. Shows |:messages|, allows navigating all messages.
6156• "dialog": Dialog window. Shows modal prompts that wait for user input.
6157
6158In each of the special buffers, 'filetype' is set as listed above ("cmd",
6159"msg", …). Handle the |FileType| event to configure any local options for
6160these windows/buffers.
6161
6162Unlike the legacy |hit-enter| prompt, messages exceeding 'cmdheight' are
6163collapsed, followed by a `[+x]` "spill" indicator, where `x` is number of
6164overflow lines. To see all messages, do either:
6165• |g<| at any time.
6166• Type the "pager" char (if configured in 'messagesopt'), immediately after an
6167  interactive |:| command.
6168
6169 vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: