1*if_lua.txt* For Vim version 8.2. Last change: 2019 Jul 21 2 3 4 VIM REFERENCE MANUAL by Luis Carvalho 5 6 7The Lua Interface to Vim *lua* *Lua* 8 91. Commands |lua-commands| 102. The vim module |lua-vim| 113. List userdata |lua-list| 124. Dict userdata |lua-dict| 135. Blob userdata |lua-blob| 146. Funcref userdata |lua-funcref| 157. Buffer userdata |lua-buffer| 168. Window userdata |lua-window| 179. luaeval() Vim function |lua-luaeval| 1810. Dynamic loading |lua-dynamic| 19 20{only available when Vim was compiled with the |+lua| feature} 21 22============================================================================== 231. Commands *lua-commands* 24 25 *:lua* 26:[range]lua {chunk} 27 Execute Lua chunk {chunk}. 28 29Examples: 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 43If [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 47This form of the |:lua| command is mainly useful for including Lua code 48in Vim scripts. 49 50Example: 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< 61To see what version of Lua you have: > 62 :lua print(_VERSION) 63 64If 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 77Examples: 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 92Examples: 93> 94 :luafile script.lua 95 :luafile % 96< 97 98All 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 Lua 100interpreter, each chunk has its own scope and so only global variables are 101shared between command calls. All Lua default libraries are available. In 102addition, Lua "print" function has its output redirected to the Vim message 103area, with arguments separated by a white space instead of a tab. 104 105Lua uses the "vim" module (see |lua-vim|) to issue commands to Vim 106and manage buffers (|lua-buffer|) and windows (|lua-window|). However, 107procedures that alter buffer content, open new buffers, and change cursor 108position are restricted when the command is executed in the |sandbox|. 109 110 111============================================================================== 1122. The vim module *lua-vim* 113 114Lua interfaces Vim through the "vim" module. The first and last line of the 115input range are stored in "vim.firstline" and "vim.lastline" respectively. The 116module also includes routines for buffer, window, and current line queries, 117Vim 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 short 157 name is "arg". In both cases, returns 'nil' 158 (nil value, not string) if the buffer is not 159 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 to 170 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({cmd}) Executes the vim (ex-mode) command {cmd}. 179 Examples: > 180 :lua vim.command"set tw=60" 181 :lua vim.command"normal ddp" 182< 183 vim.eval({expr}) Evaluates expression {expr} (see |expression|), 184 converts the result to Lua, and returns it. 185 Vim strings and numbers are directly converted 186 to Lua strings and numbers respectively. Vim 187 lists and dictionaries are converted to Lua 188 userdata (see |lua-list| and |lua-dict|). 189 Examples: > 190 :lua tw = vim.eval"&tw" 191 :lua print(vim.eval"{'a': 'one'}".a) 192< 193 vim.line() Returns the current line (without the trailing 194 <EOL>), a Lua string. 195 196 vim.beep() Beeps. 197 198 vim.open({fname}) Opens a new buffer for file {fname} and 199 returns it. Note that the buffer is not set as 200 current. 201 202 vim.call({name} [,{args}]) 203 Proxy to call Vim function named {name} with 204 arguments {args}. Example: > 205 :lua print(vim.call('has', 'timers')) 206< 207 vim.fn Proxy to call Vim functions. Proxy methods are 208 created on demand. Example: > 209 :lua print(vim.fn.has('timers')) 210< 211 212============================================================================== 2133. List userdata *lua-list* 214 215List userdata represent vim lists, and the interface tries to follow closely 216Vim's syntax for lists. Since lists are objects, changes in list references in 217Lua are reflected in Vim and vice-versa. A list "l" has the following 218properties and methods: 219 220Properties 221---------- 222 o "#l" is the number of items in list "l", equivalent to "len(l)" 223 in Vim. 224 o "l[k]" returns the k-th item in "l"; "l" is zero-indexed, as in Vim. 225 To modify the k-th item, simply do "l[k] = newitem"; in 226 particular, "l[k] = nil" removes the k-th item from "l". 227 o "l()" returns an iterator for "l". 228 229Methods 230------- 231 o "l:add(item)" appends "item" to the end of "l". 232 o "l:insert(item[, pos])" inserts "item" at (optional) 233 position "pos" in the list. The default value for "pos" is 0. 234 235Examples: 236> 237 :let l = [1, 'item'] 238 :lua l = vim.eval('l') -- same 'l' 239 :lua l:add(vim.list()) 240 :lua l[0] = math.pi 241 :echo l[0] " 3.141593 242 :lua l[0] = nil -- remove first item 243 :lua l:insert(true, 1) 244 :lua print(l, #l, l[0], l[1], l[-1]) 245 :lua for item in l() do print(item) end 246< 247 248============================================================================== 2494. Dict userdata *lua-dict* 250 251Similarly to list userdata, dict userdata represent vim dictionaries; since 252dictionaries are also objects, references are kept between Lua and Vim. A dict 253"d" has the following properties: 254 255Properties 256---------- 257 o "#d" is the number of items in dict "d", equivalent to "len(d)" 258 in Vim. 259 o "d.key" or "d['key']" returns the value at entry "key" in "d". 260 To modify the entry at this key, simply do "d.key = newvalue"; in 261 particular, "d.key = nil" removes the entry from "d". 262 o "d()" returns an iterator for "d" and is equivalent to "items(d)" in 263 Vim. 264 265Examples: 266> 267 :let d = {'n':10} 268 :lua d = vim.eval('d') -- same 'd' 269 :lua print(d, d.n, #d) 270 :let d.self = d 271 :lua for k, v in d() do print(d, k, v) end 272 :lua d.x = math.pi 273 :lua d.self = nil -- remove entry 274 :echo d 275< 276 277============================================================================== 2785. Blob userdata *lua-blob* 279 280Blob userdata represent vim blobs. A blob "b" has the following properties: 281 282Properties 283---------- 284 o "#b" is the length of blob "b", equivalent to "len(b)" in Vim. 285 o "b[k]" returns the k-th item in "b"; "b" is zero-indexed, as in Vim. 286 To modify the k-th item, simply do "b[k] = number"; in particular, 287 "b[#b] = number" can append a byte to tail. 288 289Methods 290------- 291 o "b:add(bytes)" appends "bytes" to the end of "b". 292 293Examples: 294> 295 :let b = 0z001122 296 :lua b = vim.eval('b') -- same 'b' 297 :lua print(b, b[0], #b) 298 :lua b[1] = 32 299 :lua b[#b] = 0x33 -- append a byte to tail 300 :lua b:add("\x80\x81\xfe\xff") 301 :echo b 302< 303 304============================================================================== 3056. Funcref userdata *lua-funcref* 306 307Funcref userdata represent funcref variables in Vim. Funcrefs that were 308defined with a "dict" attribute need to be obtained as a dictionary key 309in order to have "self" properly assigned to the dictionary (see examples 310below.) A funcref "f" has the following properties: 311 312Properties 313---------- 314 o "#f" is the name of the function referenced by "f" 315 o "f(...)" calls the function referenced by "f" (with arguments) 316 317Examples: 318> 319 :function I(x) 320 : return a:x 321 : endfunction 322 :let R = function('I') 323 :lua i1 = vim.funcref('I') 324 :lua i2 = vim.eval('R') 325 :lua print(#i1, #i2) -- both 'I' 326 :lua print(i1, i2, #i2(i1) == #i1(i2)) 327 :function Mylen() dict 328 : return len(self.data) 329 : endfunction 330 :let mydict = {'data': [0, 1, 2, 3]} 331 :lua d = vim.eval('mydict'); d.len = vim.funcref('Mylen') 332 :echo mydict.len() 333 :lua l = d.len -- assign d as 'self' 334 :lua print(l()) 335< 336 337============================================================================== 3387. Buffer userdata *lua-buffer* 339 340Buffer userdata represent vim buffers. A buffer userdata "b" has the following 341properties and methods: 342 343Properties 344---------- 345 o "b()" sets "b" as the current buffer. 346 o "#b" is the number of lines in buffer "b". 347 o "b[k]" represents line number k: "b[k] = newline" replaces line k 348 with string "newline" and "b[k] = nil" deletes line k. 349 o "b.name" contains the short name of buffer "b" (read-only). 350 o "b.fname" contains the full name of buffer "b" (read-only). 351 o "b.number" contains the position of buffer "b" in the buffer list 352 (read-only). 353 354Methods 355------- 356 o "b:insert(newline[, pos])" inserts string "newline" at (optional) 357 position "pos" in the buffer. The default value for "pos" is 358 "#b + 1". If "pos == 0" then "newline" becomes the first line in 359 the buffer. 360 o "b:next()" returns the buffer next to "b" in the buffer list. 361 o "b:previous()" returns the buffer previous to "b" in the buffer 362 list. 363 o "b:isvalid()" returns 'true' (boolean) if buffer "b" corresponds to 364 a "real" (not freed from memory) Vim buffer. 365 366Examples: 367> 368 :lua b = vim.buffer() -- current buffer 369 :lua print(b.name, b.number) 370 :lua b[1] = "first line" 371 :lua b:insert("FIRST!", 0) 372 :lua b[1] = nil -- delete top line 373 :lua for i=1,3 do b:insert(math.random()) end 374 :3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end 375 :lua vim.open"myfile"() -- open buffer and set it as current 376 377 function! ListBuffers() 378 lua << EOF 379 local b = vim.buffer(true) -- first buffer in list 380 while b ~= nil do 381 print(b.number, b.name, #b) 382 b = b:next() 383 end 384 vim.beep() 385 EOF 386 endfunction 387< 388 389============================================================================== 3908. Window userdata *lua-window* 391 392Window objects represent vim windows. A window userdata "w" has the following 393properties and methods: 394 395Properties 396---------- 397 o "w()" sets "w" as the current window. 398 o "w.buffer" contains the buffer of window "w" (read-only). 399 o "w.line" represents the cursor line position in window "w". 400 o "w.col" represents the cursor column position in window "w". 401 o "w.width" represents the width of window "w". 402 o "w.height" represents the height of window "w". 403 404Methods 405------- 406 o "w:next()" returns the window next to "w". 407 o "w:previous()" returns the window previous to "w". 408 o "w:isvalid()" returns 'true' (boolean) if window "w" corresponds to 409 a "real" (not freed from memory) Vim window. 410 411Examples: 412> 413 :lua w = vim.window() -- current window 414 :lua print(w.buffer.name, w.line, w.col) 415 :lua w.width = w.width + math.random(10) 416 :lua w.height = 2 * math.random() * w.height 417 :lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end 418 :lua print("There are " .. n .. " windows") 419< 420 421============================================================================== 4229. luaeval() Vim function *lua-luaeval* *lua-eval* 423 424The (dual) equivalent of "vim.eval" for passing Lua values to Vim is 425"luaeval". "luaeval" takes an expression string and an optional argument and 426returns the result of the expression. It is semantically equivalent in Lua to: 427> 428 local chunkheader = "local _A = select(1, ...) return " 429 function luaeval (expstr, arg) 430 local chunk = assert(loadstring(chunkheader .. expstr, "luaeval")) 431 return chunk(arg) -- return typval 432 end 433< 434Note that "_A" receives the argument to "luaeval". Lua numbers, strings, and 435list, dict, blob, and funcref userdata are converted to their Vim respective 436types, while Lua booleans are converted to numbers. An error is thrown if 437conversion of any of the remaining Lua types, including userdata other than 438lists, dicts, blobs, and funcrefs, is attempted. 439 440Examples: > 441 442 :echo luaeval('math.pi') 443 :lua a = vim.list():add('newlist') 444 :let a = luaeval('a') 445 :echo a[0] " 'newlist' 446 :function Rand(x,y) " random uniform between x and y 447 : return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y}) 448 : endfunction 449 :echo Rand(1,10) 450 451 452============================================================================== 45310. Dynamic loading *lua-dynamic* 454 455On MS-Windows and Unix the Lua library can be loaded dynamically. The 456|:version| output then includes |+lua/dyn|. 457 458This means that Vim will search for the Lua DLL or shared library file only 459when needed. When you don't use the Lua interface you don't need it, thus 460you can use Vim without this file. 461 462 463MS-Windows ~ 464 465To use the Lua interface the Lua DLL must be in your search path. In a 466console window type "path" to see what directories are used. The 'luadll' 467option can be also used to specify the Lua DLL. The version of the DLL must 468match the Lua version Vim was compiled with. 469 470 471Unix ~ 472 473The 'luadll' option can be used to specify the Lua shared library file instead 474of DYNAMIC_LUA_DLL file what was specified at compile time. The version of 475the shared library must match the Lua version Vim was compiled with. 476 477 478============================================================================== 479 vim:tw=78:ts=8:noet:ft=help:norl: 480