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