if_lua.txt (18655B)
1 *if_lua.txt* For Vim version 9.2. Last change: 2026 Sep 29 2 3 4 VIM REFERENCE MANUAL by Luis Carvalho 5 6 7 The Lua Interface to Vim *lua* *Lua* 8 9 1. Commands |lua-commands| 10 2. The vim module |lua-vim| 11 3. List userdata |lua-list| 12 4. Dict userdata |lua-dict| 13 5. Blob userdata |lua-blob| 14 6. Funcref userdata |lua-funcref| 15 7. Buffer userdata |lua-buffer| 16 8. Window userdata |lua-window| 17 9. luaeval() Vim function |lua-luaeval| 18 10. Dynamic loading |lua-dynamic| 19 20 {only available when Vim was compiled with the |+lua| feature} 21 22 ============================================================================== 23 1. Commands *lua-commands* 24 25 *:lua* 26 :[range]lua {chunk} 27 Execute Lua chunk {chunk}. 28 29 Examples: 30 > 31 :lua print("Hello, Vim!") 32 :lua local curbuf = vim.buffer() curbuf[7] = "line #7" 33 < 34 35 :[range]lua << [trim] [{endmarker}] 36 {script} 37 {endmarker} 38 Execute Lua script {script}. 39 Note: This command doesn't work when the Lua 40 feature wasn't compiled in. To avoid errors, see 41 |script-here|. 42 43 If [endmarker] is omitted from after the "<<", a dot '.' must be used after 44 {script}, like for the |:append| and |:insert| commands. Refer to 45 |:let-heredoc| for more information. 46 47 This form of the |:lua| command is mainly useful for including Lua code 48 in Vim scripts. 49 50 Example: 51 > 52 function! CurrentLineInfo() 53 lua << EOF 54 local linenr = vim.window().line 55 local curline = vim.buffer()[linenr] 56 print(string.format("Current line [%d] has %d chars", 57 linenr, #curline)) 58 EOF 59 endfunction 60 < 61 To see what version of Lua you have: > 62 :lua print(_VERSION) 63 64 If you use LuaJIT you can also use this: > 65 :lua print(jit.version) 66 < 67 68 *:luado* 69 :[range]luado {body} Execute Lua function "function (line, linenr) {body} 70 end" for each line in the [range], with the function 71 argument being set to the text of each line in turn, 72 without a trailing <EOL>, and the current line number. 73 If the value returned by the function is a string it 74 becomes the text of the line in the current turn. The 75 default for [range] is the whole file: "1,$". 76 77 Examples: 78 > 79 :luado return string.format("%s\t%d", line:reverse(), #line) 80 81 :lua require"lpeg" 82 :lua -- balanced parenthesis grammar: 83 :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" } 84 :luado if bp:match(line) then return "-->\t" .. line end 85 < 86 87 *:luafile* 88 :[range]luafile {file} 89 Execute Lua script in {file}. 90 The whole argument is used as a single file name. 91 92 Examples: 93 > 94 :luafile script.lua 95 :luafile % 96 < 97 98 All these commands execute a Lua chunk from either the command line (:lua and 99 :luado) or a file (:luafile) with the given line [range]. Similarly to the 100 Lua interpreter, each chunk has its own scope and so only global variables are 101 shared between command calls. All Lua default libraries are available. In 102 addition, Lua "print" function has its output redirected to the Vim message 103 area, with arguments separated by a white space instead of a tab. 104 105 Lua uses the "vim" module (see |lua-vim|) to issue commands to Vim 106 and manage buffers (|lua-buffer|) and windows (|lua-window|). However, 107 procedures that alter buffer content, open new buffers, and change cursor 108 position are restricted when the command is executed in the |sandbox|. 109 110 111 ============================================================================== 112 2. The vim module *lua-vim* 113 114 Lua interfaces Vim through the "vim" module. The first and last line of the 115 input range are stored in "vim.firstline" and "vim.lastline" respectively. 116 The module also includes routines for buffer, window, and current line 117 queries, Vim evaluation and command execution, and others. 118 119 vim.list([arg]) Returns an empty list or, if "arg" is a Lua 120 table with numeric keys 1, ..., n (a 121 "sequence"), returns a list l such that l[i] = 122 arg[i] for i = 1, ..., n (see |List|). 123 Non-numeric keys are not used to initialize 124 the list. See also |lua-eval| for conversion 125 rules. Example: > 126 :lua t = {math.pi, false, say = 'hi'} 127 :echo luaeval('vim.list(t)') 128 :" [3.141593, v:false], 'say' is ignored 129 < 130 vim.dict([arg]) Returns an empty dictionary or, if "arg" is a 131 Lua table, returns a dict d such that d[k] = 132 arg[k] for all string keys k in "arg" (see 133 |Dictionary|). Number keys are converted to 134 strings. Keys that are not strings are not 135 used to initialize the dictionary. See also 136 |lua-eval| for conversion rules. Example: > 137 :lua t = {math.pi, false, say = 'hi'} 138 :echo luaeval('vim.dict(t)') 139 :" {'1': 3.141593, '2': v:false, 140 :" 'say': 'hi'} 141 < 142 vim.blob([arg]) Returns an empty blob or, if "arg" is a Lua 143 string, returns a blob b such that b is 144 equivalent to "arg" as a byte string. 145 Examples: > 146 :lua s = "12ab\x00\x80\xfe\xff" 147 :echo luaeval('vim.blob(s)') 148 :" 0z31326162.0080FEFF 149 < 150 vim.funcref({name}) Returns a Funcref to function {name} (see 151 |Funcref|). It is equivalent to Vim's 152 function(). 153 154 vim.buffer([arg]) If "arg" is a number, returns buffer with 155 number "arg" in the buffer list or, if "arg" 156 is a string, returns buffer whose full or 157 short name is "arg". In both cases, returns 158 'nil' (nil value, not string) if the buffer is 159 not found. Otherwise, if "toboolean(arg)" is 160 'true' returns the first buffer in the buffer 161 list or else the current buffer. 162 163 vim.window([arg]) If "arg" is a number, returns window with 164 number "arg" or 'nil' (nil value, not string) 165 if not found. Otherwise, if "toboolean(arg)" 166 is 'true' returns the first window or else the 167 current window. 168 169 vim.type({arg}) Returns the type of {arg}. It is equivalent 170 to Lua's "type" function, but returns "list", 171 "dict", "funcref", "buffer", or "window" if 172 {arg} is a list, dictionary, funcref, buffer, 173 or window, respectively. Examples: > 174 :lua l = vim.list() 175 :lua print(type(l), vim.type(l)) 176 :" list 177 < 178 vim.command({cmds}) Executes one or more lines of Ex-mode commands 179 in {cmds}. 180 Examples: > 181 :lua vim.command"set tw=60" 182 :lua vim.command"normal ddp" 183 lua << trim END 184 vim.command([[ 185 new Myfile.js 186 call search('start') 187 ]]) 188 END 189 < 190 vim.eval({expr}) Evaluates expression {expr} (see |expression|), 191 converts the result to Lua, and returns it. 192 Vim strings and numbers are directly converted 193 to Lua strings and numbers respectively. Vim 194 lists and dictionaries are converted to Lua 195 userdata (see |lua-list| and |lua-dict|). 196 Examples: > 197 :lua tw = vim.eval"&tw" 198 :lua print(vim.eval"{'a': 'one'}".a) 199 < 200 vim.line() Returns the current line (without the trailing 201 <EOL>), a Lua string. 202 203 vim.beep() Beeps. 204 205 vim.open({fname}) Opens a new buffer for file {fname} and 206 returns it. Note that the buffer is not set 207 as current. 208 209 vim.call({name} [, {args}]) 210 Proxy to call Vim function named {name} with 211 arguments {args}. Example: > 212 :lua print(vim.call('has', 'timers')) 213 < 214 vim.fn Proxy to call Vim functions. Proxy methods 215 are created on demand. Example: > 216 :lua print(vim.fn.has('timers')) 217 < 218 vim.lua_version The Lua version Vim was compiled with, in the 219 form {major}.{minor}.{patch}, e.g. "5.1.4". 220 221 vim.version() Returns a Lua table with the Vim version. 222 The table will have the following keys: 223 major - major Vim version. 224 minor - minor Vim version. 225 patch - latest patch included. 226 227 *lua-vim-variables* 228 The Vim editor global dictionaries |g:| |w:| |b:| |t:| |v:| can be accessed 229 from Lua conveniently and idiomatically by referencing the `vim.*` Lua tables 230 described below. In this way you can easily read and modify global Vim script 231 variables from Lua. 232 233 Example: > 234 235 vim.g.foo = 5 -- Set the g:foo Vim script variable. 236 print(vim.g.foo) -- Get and print the g:foo Vim script variable. 237 vim.g.foo = nil -- Delete (:unlet) the Vim script variable. 238 239 vim.g *vim.g* 240 Global (|g:|) editor variables. 241 Key with no value returns `nil`. 242 243 vim.b *vim.b* 244 Buffer-scoped (|b:|) variables for the current buffer. 245 Invalid or unset key returns `nil`. 246 247 vim.w *vim.w* 248 Window-scoped (|w:|) variables for the current window. 249 Invalid or unset key returns `nil`. 250 251 vim.t *vim.t* 252 Tabpage-scoped (|t:|) variables for the current tabpage. 253 Invalid or unset key returns `nil`. 254 255 vim.v *vim.v* 256 |v:| variables. 257 Invalid or unset key returns `nil`. 258 259 ============================================================================== 260 3. List userdata *lua-list* 261 262 List userdata represent vim lists, and the interface tries to follow closely 263 Vim's syntax for lists. Since lists are objects, changes in list references 264 in Lua are reflected in Vim and vice-versa. A list "l" has the following 265 properties and methods: 266 267 NOTE: In patch 8.2.1066 array indexes were changed from zero-based to 268 one-based. You can check with: > 269 if has("patch-8.2.1066") 270 271 Properties 272 ---------- 273 o "#l" is the number of items in list "l", equivalent to "len(l)" 274 in Vim. 275 o "l[k]" returns the k-th item in "l"; "l" is one-indexed, as in Lua. 276 To modify the k-th item, simply do "l[k] = newitem"; in 277 particular, "l[k] = nil" removes the k-th item from "l". Item can 278 be added to the end of the list by "l[#l + 1] = newitem" 279 o "l()" returns an iterator for "l". 280 o "table.insert(l, newitem)" inserts an item at the end of the list. 281 (only Lua 5.3 and later) 282 o "table.insert(l, position, newitem)" inserts an item at the 283 specified position. "position" is one-indexed. (only Lua 5.3 and 284 later) 285 o "table.remove(l, position)" removes an item at the specified 286 position. "position" is one-indexed. 287 288 289 Methods 290 ------- 291 o "l:add(item)" appends "item" to the end of "l". 292 o "l:insert(item[, pos])" inserts "item" at (optional) 293 position "pos" in the list. The default value for "pos" is 0. 294 295 Examples: 296 > 297 :let l = [1, 'item'] 298 :lua l = vim.eval('l') -- same 'l' 299 :lua l:add(vim.list()) 300 :lua l[1] = math.pi 301 :echo l[0] " 3.141593 302 :lua l[1] = nil -- remove first item 303 :lua l:insert(true, 1) 304 :lua print(l, #l, l[1], l[2]) 305 :lua l[#l + 1] = 'value' 306 :lua table.insert(l, 100) 307 :lua table.insert(l, 2, 200) 308 :lua table.remove(l, 1) 309 :lua for item in l() do print(item) end 310 311 ============================================================================== 312 4. Dict userdata *lua-dict* 313 314 Similarly to list userdata, dict userdata represent vim dictionaries; since 315 dictionaries are also objects, references are kept between Lua and Vim. A 316 dict "d" has the following properties: 317 318 Properties 319 ---------- 320 o "#d" is the number of items in dict "d", equivalent to "len(d)" 321 in Vim. 322 o "d.key" or "d['key']" returns the value at entry "key" in "d". 323 To modify the entry at this key, simply do "d.key = newvalue"; in 324 particular, "d.key = nil" removes the entry from "d". 325 o "d()" returns an iterator for "d" and is equivalent to "items(d)" in 326 Vim. 327 328 Examples: 329 > 330 :let d = {'n':10} 331 :lua d = vim.eval('d') -- same 'd' 332 :lua print(d, d.n, #d) 333 :let d.self = d 334 :lua for k, v in d() do print(d, k, v) end 335 :lua d.x = math.pi 336 :lua d.self = nil -- remove entry 337 :echo d 338 < 339 340 ============================================================================== 341 5. Blob userdata *lua-blob* 342 343 Blob userdata represent vim blobs. A blob "b" has the following properties: 344 345 Properties 346 ---------- 347 o "#b" is the length of blob "b", equivalent to "len(b)" in Vim. 348 o "b[k]" returns the k-th item in "b"; "b" is zero-indexed, as in Vim. 349 A negative "k" counts from the end, also as in Vim, thus "b[-1]" is 350 the last item. To modify the k-th item, simply do 351 "b[k] = number"; "b[#b] = number" can append a byte to tail. 352 353 Methods 354 ------- 355 o "b:add(bytes)" appends "bytes" to the end of "b". 356 357 Examples: 358 > 359 :let b = 0z001122 360 :lua b = vim.eval('b') -- same 'b' 361 :lua print(b, b[0], #b) 362 :lua b[1] = 32 363 :lua b[#b] = 0x33 -- append a byte to tail 364 :lua b:add("\x80\x81\xfe\xff") 365 :echo b 366 < 367 368 ============================================================================== 369 6. Funcref userdata *lua-funcref* 370 371 Funcref userdata represent funcref variables in Vim. Funcrefs that were 372 defined with a "dict" attribute need to be obtained as a dictionary key 373 in order to have "self" properly assigned to the dictionary (see examples 374 below.) A funcref "f" has the following properties: 375 376 Properties 377 ---------- 378 o "#f" is the name of the function referenced by "f" 379 o "f(...)" calls the function referenced by "f" (with arguments) 380 381 Examples: 382 > 383 :function I(x) 384 : return a:x 385 : endfunction 386 :let R = function('I') 387 :lua i1 = vim.funcref('I') 388 :lua i2 = vim.eval('R') 389 :lua print(#i1, #i2) -- both 'I' 390 :lua print(i1, i2, #i2(i1) == #i1(i2)) 391 :function Mylen() dict 392 : return len(self.data) 393 : endfunction 394 :let mydict = {'data': [0, 1, 2, 3]} 395 :lua d = vim.eval('mydict'); d.len = vim.funcref('Mylen') 396 :echo mydict.len() 397 :lua l = d.len -- assign d as 'self' 398 :lua print(l()) 399 < 400 Lua functions and closures are automatically converted to a Vim |Funcref| and 401 can be accessed in Vim scripts. Example: 402 > 403 lua <<EOF 404 vim.fn.timer_start(1000, function(timer) 405 print('timer callback') 406 end) 407 EOF 408 409 ============================================================================== 410 7. Buffer userdata *lua-buffer* 411 412 Buffer userdata represent vim buffers. A buffer userdata "b" has the 413 following properties and methods: 414 415 Properties 416 ---------- 417 o "b()" sets "b" as the current buffer. 418 o "#b" is the number of lines in buffer "b". 419 o "b[k]" represents line number k: "b[k] = newline" replaces line k 420 with string "newline" and "b[k] = nil" deletes line k. 421 o "b.name" contains the short name of buffer "b" (read-only). 422 o "b.fname" contains the full name of buffer "b" (read-only). 423 o "b.number" contains the position of buffer "b" in the buffer list 424 (read-only). 425 426 Methods 427 ------- 428 o "b:insert(newline[, pos])" inserts string "newline" at (optional) 429 position "pos" in the buffer. The default value for "pos" is 430 "#b + 1". If "pos == 0" then "newline" becomes the first line in 431 the buffer. 432 o "b:next()" returns the buffer next to "b" in the buffer list. 433 o "b:previous()" returns the buffer previous to "b" in the buffer 434 list. 435 o "b:isvalid()" returns 'true' (boolean) if buffer "b" corresponds to 436 a "real" (not freed from memory) Vim buffer. 437 438 Examples: 439 > 440 :lua b = vim.buffer() -- current buffer 441 :lua print(b.name, b.number) 442 :lua b[1] = "first line" 443 :lua b:insert("FIRST!", 0) 444 :lua b[1] = nil -- delete top line 445 :lua for i=1,3 do b:insert(math.random()) end 446 :3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end 447 :lua vim.open"myfile"() -- open buffer and set it as current 448 449 function! ListBuffers() 450 lua << EOF 451 local b = vim.buffer(true) -- first buffer in list 452 while b ~= nil do 453 print(b.number, b.name, #b) 454 b = b:next() 455 end 456 vim.beep() 457 EOF 458 endfunction 459 < 460 461 ============================================================================== 462 8. Window userdata *lua-window* 463 464 Window objects represent vim windows. A window userdata "w" has the following 465 properties and methods: 466 467 Properties 468 ---------- 469 o "w()" sets "w" as the current window. 470 o "w.buffer" contains the buffer of window "w" (read-only). 471 o "w.line" represents the cursor line position in window "w". 472 o "w.col" represents the cursor column position in window "w". 473 o "w.width" represents the width of window "w". 474 o "w.height" represents the height of window "w". 475 476 Methods 477 ------- 478 o "w:next()" returns the window next to "w". 479 o "w:previous()" returns the window previous to "w". 480 o "w:isvalid()" returns 'true' (boolean) if window "w" corresponds to 481 a "real" (not freed from memory) Vim window. 482 483 Examples: 484 > 485 :lua w = vim.window() -- current window 486 :lua print(w.buffer.name, w.line, w.col) 487 :lua w.width = w.width + math.random(10) 488 :lua w.height = 2 * math.random() * w.height 489 :lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end 490 :lua print("There are " .. n .. " windows") 491 < 492 493 ============================================================================== 494 9. luaeval() Vim function *lua-luaeval* *lua-eval* 495 496 The (dual) equivalent of "vim.eval" for passing Lua values to Vim is 497 "luaeval". "luaeval" takes an expression string and an optional argument and 498 returns the result of the expression. It is semantically equivalent in Lua 499 to: 500 > 501 local chunkheader = "local _A = select(1, ...) return " 502 function luaeval (expstr, arg) 503 local chunk = assert(loadstring(chunkheader .. expstr, "luaeval")) 504 return chunk(arg) -- return typval 505 end 506 < 507 Note that "_A" receives the argument to "luaeval". Lua numbers, strings, and 508 list, dict, blob, and funcref userdata are converted to their Vim respective 509 types, while Lua booleans are converted to numbers. An error is thrown if 510 conversion of any of the remaining Lua types, including userdata other than 511 lists, dicts, blobs, and funcrefs, is attempted. 512 513 Examples: > 514 515 :echo luaeval('math.pi') 516 :lua a = vim.list():add('newlist') 517 :let a = luaeval('a') 518 :echo a[0] " 'newlist' 519 :function Rand(x,y) " random uniform between x and y 520 : return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y}) 521 : endfunction 522 :echo Rand(1,10) 523 524 525 ============================================================================== 526 10. Dynamic loading *lua-dynamic* 527 528 On MS-Windows and Unix the Lua library can be loaded dynamically. The 529 |:version| output then includes |+lua/dyn|. 530 531 This means that Vim will search for the Lua DLL or shared library file only 532 when needed. When you don't use the Lua interface you don't need it, thus 533 you can use Vim without this file. 534 535 536 MS-Windows ~ 537 538 To use the Lua interface the Lua DLL must be in your search path. In a 539 console window type "path" to see what directories are used. The 'luadll' 540 option can be also used to specify the Lua DLL. The version of the DLL must 541 match the Lua version Vim was compiled with. 542 543 544 Unix ~ 545 546 The 'luadll' option can be used to specify the Lua shared library file instead 547 of DYNAMIC_LUA_DLL file what was specified at compile time. The version of 548 the shared library must match the Lua version Vim was compiled with. 549 550 551 ============================================================================== 552 vim:tw=78:ts=8:noet:ft=help:norl: