blob: ad20b014a351eb4bfee9f3a75454fa99ebea6d96 [file] [log] [blame]
Bram Moolenaar98056532019-12-12 14:18:35 +01001*if_lua.txt* For Vim version 8.2. Last change: 2019 Jul 21
Bram Moolenaar0ba04292010-07-14 23:23:17 +02002
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|
Bram Moolenaar1dced572012-04-05 16:54:08 +0200113. List userdata |lua-list|
124. Dict userdata |lua-dict|
Bram Moolenaarb7828692019-03-23 13:57:02 +0100135. 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|
Bram Moolenaar0ba04292010-07-14 23:23:17 +020019
Bram Moolenaar25c9c682019-05-05 18:13:34 +020020{only available when Vim was compiled with the |+lua| feature}
Bram Moolenaar0ba04292010-07-14 23:23:17 +020021
22==============================================================================
231. Commands *lua-commands*
24
25 *:lua*
26:[range]lua {chunk}
Bram Moolenaar25c9c682019-05-05 18:13:34 +020027 Execute Lua chunk {chunk}.
Bram Moolenaar0ba04292010-07-14 23:23:17 +020028
29Examples:
30>
31 :lua print("Hello, Vim!")
32 :lua local curbuf = vim.buffer() curbuf[7] = "line #7"
33<
34
Bram Moolenaar54775062019-07-31 21:07:14 +020035:[range]lua << [endmarker]
Bram Moolenaar0ba04292010-07-14 23:23:17 +020036{script}
37{endmarker}
Bram Moolenaar25c9c682019-05-05 18:13:34 +020038 Execute Lua script {script}.
Bram Moolenaar0ba04292010-07-14 23:23:17 +020039 Note: This command doesn't work when the Lua
40 feature wasn't compiled in. To avoid errors, see
41 |script-here|.
42
Bram Moolenaar54775062019-07-31 21:07:14 +020043The {endmarker} must NOT be preceded by any white space.
44
45If [endmarker] is omitted from after the "<<", a dot '.' must be used after
46{script}, like for the |:append| and |:insert| commands.
47
Bram Moolenaar0ba04292010-07-14 23:23:17 +020048This form of the |:lua| command is mainly useful for including Lua code
49in Vim scripts.
50
51Example:
52>
53 function! CurrentLineInfo()
54 lua << EOF
55 local linenr = vim.window().line
56 local curline = vim.buffer()[linenr]
57 print(string.format("Current line [%d] has %d chars",
58 linenr, #curline))
59 EOF
60 endfunction
61<
Bram Moolenaarabd468e2016-09-08 22:22:43 +020062To see what version of Lua you have: >
63 :lua print(_VERSION)
64
65If you use LuaJIT you can also use this: >
66 :lua print(jit.version)
67<
Bram Moolenaar0ba04292010-07-14 23:23:17 +020068
69 *:luado*
Bram Moolenaar53bfca22012-04-13 23:04:47 +020070:[range]luado {body} Execute Lua function "function (line, linenr) {body}
71 end" for each line in the [range], with the function
72 argument being set to the text of each line in turn,
73 without a trailing <EOL>, and the current line number.
74 If the value returned by the function is a string it
75 becomes the text of the line in the current turn. The
76 default for [range] is the whole file: "1,$".
Bram Moolenaar0ba04292010-07-14 23:23:17 +020077
78Examples:
79>
80 :luado return string.format("%s\t%d", line:reverse(), #line)
81
82 :lua require"lpeg"
83 :lua -- balanced parenthesis grammar:
84 :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
85 :luado if bp:match(line) then return "-->\t" .. line end
86<
87
88 *:luafile*
89:[range]luafile {file}
Bram Moolenaar25c9c682019-05-05 18:13:34 +020090 Execute Lua script in {file}.
Bram Moolenaar0ba04292010-07-14 23:23:17 +020091 The whole argument is used as a single file name.
92
93Examples:
94>
95 :luafile script.lua
96 :luafile %
97<
98
99All these commands execute a Lua chunk from either the command line (:lua and
100:luado) or a file (:luafile) with the given line [range]. Similarly to the Lua
101interpreter, each chunk has its own scope and so only global variables are
Bram Moolenaar1dced572012-04-05 16:54:08 +0200102shared between command calls. All Lua default libraries are available. In
103addition, Lua "print" function has its output redirected to the Vim message
104area, with arguments separated by a white space instead of a tab.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200105
Bram Moolenaar9855d6b2010-07-18 14:34:51 +0200106Lua uses the "vim" module (see |lua-vim|) to issue commands to Vim
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200107and manage buffers (|lua-buffer|) and windows (|lua-window|). However,
108procedures that alter buffer content, open new buffers, and change cursor
Bram Moolenaar9855d6b2010-07-18 14:34:51 +0200109position are restricted when the command is executed in the |sandbox|.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200110
111
112==============================================================================
1132. The vim module *lua-vim*
114
115Lua interfaces Vim through the "vim" module. The first and last line of the
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200116input range are stored in "vim.firstline" and "vim.lastline" respectively. The
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200117module also includes routines for buffer, window, and current line queries,
118Vim evaluation and command execution, and others.
119
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200120 vim.list([arg]) Returns an empty list or, if "arg" is a Lua
121 table with numeric keys 1, ..., n (a
122 "sequence"), returns a list l such that l[i] =
123 arg[i] for i = 1, ..., n (see |List|).
124 Non-numeric keys are not used to initialize
125 the list. See also |lua-eval| for conversion
126 rules. Example: >
Bram Moolenaarfd358112018-07-07 23:21:31 +0200127 :lua t = {math.pi, false, say = 'hi'}
128 :echo luaeval('vim.list(t)')
129 :" [3.141593, v:false], 'say' is ignored
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200130<
131 vim.dict([arg]) Returns an empty dictionary or, if "arg" is a
132 Lua table, returns a dict d such that d[k] =
133 arg[k] for all string keys k in "arg" (see
134 |Dictionary|). Number keys are converted to
135 strings. Keys that are not strings are not
136 used to initialize the dictionary. See also
137 |lua-eval| for conversion rules. Example: >
Bram Moolenaarfd358112018-07-07 23:21:31 +0200138 :lua t = {math.pi, false, say = 'hi'}
139 :echo luaeval('vim.dict(t)')
140 :" {'1': 3.141593, '2': v:false,
141 :" 'say': 'hi'}
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200142<
Bram Moolenaarb7828692019-03-23 13:57:02 +0100143 vim.blob([arg]) Returns an empty blob or, if "arg" is a Lua
144 string, returns a blob b such that b is
145 equivalent to "arg" as a byte string.
146 Examples: >
147 :lua s = "12ab\x00\x80\xfe\xff"
148 :echo luaeval('vim.blob(s)')
149 :" 0z31326162.0080FEFF
150<
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200151 vim.funcref({name}) Returns a Funcref to function {name} (see
Bram Moolenaarfd358112018-07-07 23:21:31 +0200152 |Funcref|). It is equivalent to Vim's
153 function().
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200154
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200155 vim.buffer([arg]) If "arg" is a number, returns buffer with
156 number "arg" in the buffer list or, if "arg"
157 is a string, returns buffer whose full or short
158 name is "arg". In both cases, returns 'nil'
159 (nil value, not string) if the buffer is not
160 found. Otherwise, if "toboolean(arg)" is
161 'true' returns the first buffer in the buffer
162 list or else the current buffer.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200163
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200164 vim.window([arg]) If "arg" is a number, returns window with
165 number "arg" or 'nil' (nil value, not string)
166 if not found. Otherwise, if "toboolean(arg)"
167 is 'true' returns the first window or else the
168 current window.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200169
Bram Moolenaar1dced572012-04-05 16:54:08 +0200170 vim.type({arg}) Returns the type of {arg}. It is equivalent to
171 Lua's "type" function, but returns "list",
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200172 "dict", "funcref", "buffer", or "window" if
173 {arg} is a list, dictionary, funcref, buffer,
174 or window, respectively. Examples: >
Bram Moolenaar1dced572012-04-05 16:54:08 +0200175 :lua l = vim.list()
176 :lua print(type(l), vim.type(l))
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200177 :" list
Bram Moolenaar1dced572012-04-05 16:54:08 +0200178<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200179 vim.command({cmd}) Executes the vim (ex-mode) command {cmd}.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200180 Examples: >
181 :lua vim.command"set tw=60"
182 :lua vim.command"normal ddp"
183<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200184 vim.eval({expr}) Evaluates expression {expr} (see |expression|),
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200185 converts the result to Lua, and returns it.
186 Vim strings and numbers are directly converted
187 to Lua strings and numbers respectively. Vim
188 lists and dictionaries are converted to Lua
Bram Moolenaar1dced572012-04-05 16:54:08 +0200189 userdata (see |lua-list| and |lua-dict|).
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200190 Examples: >
191 :lua tw = vim.eval"&tw"
192 :lua print(vim.eval"{'a': 'one'}".a)
193<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200194 vim.line() Returns the current line (without the trailing
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200195 <EOL>), a Lua string.
196
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200197 vim.beep() Beeps.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200198
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200199 vim.open({fname}) Opens a new buffer for file {fname} and
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200200 returns it. Note that the buffer is not set as
201 current.
202
203
204==============================================================================
Bram Moolenaar1dced572012-04-05 16:54:08 +02002053. List userdata *lua-list*
206
207List userdata represent vim lists, and the interface tries to follow closely
208Vim's syntax for lists. Since lists are objects, changes in list references in
209Lua are reflected in Vim and vice-versa. A list "l" has the following
210properties and methods:
211
212Properties
213----------
214 o "#l" is the number of items in list "l", equivalent to "len(l)"
215 in Vim.
216 o "l[k]" returns the k-th item in "l"; "l" is zero-indexed, as in Vim.
217 To modify the k-th item, simply do "l[k] = newitem"; in
218 particular, "l[k] = nil" removes the k-th item from "l".
219 o "l()" returns an iterator for "l".
220
221Methods
222-------
223 o "l:add(item)" appends "item" to the end of "l".
224 o "l:insert(item[, pos])" inserts "item" at (optional)
225 position "pos" in the list. The default value for "pos" is 0.
226
227Examples:
228>
229 :let l = [1, 'item']
230 :lua l = vim.eval('l') -- same 'l'
231 :lua l:add(vim.list())
232 :lua l[0] = math.pi
233 :echo l[0] " 3.141593
234 :lua l[0] = nil -- remove first item
235 :lua l:insert(true, 1)
236 :lua print(l, #l, l[0], l[1], l[-1])
237 :lua for item in l() do print(item) end
238<
239
240==============================================================================
2414. Dict userdata *lua-dict*
242
243Similarly to list userdata, dict userdata represent vim dictionaries; since
244dictionaries are also objects, references are kept between Lua and Vim. A dict
245"d" has the following properties:
246
247Properties
248----------
249 o "#d" is the number of items in dict "d", equivalent to "len(d)"
250 in Vim.
251 o "d.key" or "d['key']" returns the value at entry "key" in "d".
252 To modify the entry at this key, simply do "d.key = newvalue"; in
253 particular, "d.key = nil" removes the entry from "d".
254 o "d()" returns an iterator for "d" and is equivalent to "items(d)" in
255 Vim.
256
257Examples:
258>
259 :let d = {'n':10}
260 :lua d = vim.eval('d') -- same 'd'
261 :lua print(d, d.n, #d)
262 :let d.self = d
263 :lua for k, v in d() do print(d, k, v) end
264 :lua d.x = math.pi
265 :lua d.self = nil -- remove entry
266 :echo d
267<
268
269==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +01002705. Blob userdata *lua-blob*
271
272Blob userdata represent vim blobs. A blob "b" has the following properties:
273
274Properties
275----------
276 o "#b" is the length of blob "b", equivalent to "len(b)" in Vim.
277 o "b[k]" returns the k-th item in "b"; "b" is zero-indexed, as in Vim.
278 To modify the k-th item, simply do "b[k] = number"; in particular,
279 "b[#b] = number" can append a byte to tail.
280
281Methods
282-------
283 o "b:add(bytes)" appends "bytes" to the end of "b".
284
285Examples:
286>
287 :let b = 0z001122
288 :lua b = vim.eval('b') -- same 'b'
289 :lua print(b, b[0], #b)
290 :lua b[1] = 32
291 :lua b[#b] = 0x33 -- append a byte to tail
292 :lua b:add("\x80\x81\xfe\xff")
293 :echo b
294<
295
296==============================================================================
2976. Funcref userdata *lua-funcref*
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200298
299Funcref userdata represent funcref variables in Vim. Funcrefs that were
300defined with a "dict" attribute need to be obtained as a dictionary key
301in order to have "self" properly assigned to the dictionary (see examples
302below.) A funcref "f" has the following properties:
303
304Properties
305----------
306 o "#f" is the name of the function referenced by "f"
307 o "f(...)" calls the function referenced by "f" (with arguments)
308
309Examples:
310>
311 :function I(x)
312 : return a:x
313 : endfunction
314 :let R = function('I')
315 :lua i1 = vim.funcref('I')
316 :lua i2 = vim.eval('R')
317 :lua print(#i1, #i2) -- both 'I'
318 :lua print(i1, i2, #i2(i1) == #i1(i2))
319 :function Mylen() dict
320 : return len(self.data)
321 : endfunction
322 :let mydict = {'data': [0, 1, 2, 3]}
323 :lua d = vim.eval('mydict'); d.len = vim.funcref('Mylen')
324 :echo mydict.len()
325 :lua l = d.len -- assign d as 'self'
326 :lua print(l())
327<
328
329==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +01003307. Buffer userdata *lua-buffer*
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200331
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200332Buffer userdata represent vim buffers. A buffer userdata "b" has the following
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200333properties and methods:
334
335Properties
336----------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200337 o "b()" sets "b" as the current buffer.
338 o "#b" is the number of lines in buffer "b".
339 o "b[k]" represents line number k: "b[k] = newline" replaces line k
340 with string "newline" and "b[k] = nil" deletes line k.
341 o "b.name" contains the short name of buffer "b" (read-only).
342 o "b.fname" contains the full name of buffer "b" (read-only).
343 o "b.number" contains the position of buffer "b" in the buffer list
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200344 (read-only).
345
346Methods
347-------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200348 o "b:insert(newline[, pos])" inserts string "newline" at (optional)
349 position "pos" in the buffer. The default value for "pos" is
350 "#b + 1". If "pos == 0" then "newline" becomes the first line in
351 the buffer.
352 o "b:next()" returns the buffer next to "b" in the buffer list.
353 o "b:previous()" returns the buffer previous to "b" in the buffer
354 list.
355 o "b:isvalid()" returns 'true' (boolean) if buffer "b" corresponds to
356 a "real" (not freed from memory) Vim buffer.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200357
358Examples:
359>
360 :lua b = vim.buffer() -- current buffer
361 :lua print(b.name, b.number)
362 :lua b[1] = "first line"
363 :lua b:insert("FIRST!", 0)
364 :lua b[1] = nil -- delete top line
365 :lua for i=1,3 do b:insert(math.random()) end
366 :3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end
367 :lua vim.open"myfile"() -- open buffer and set it as current
368
369 function! ListBuffers()
370 lua << EOF
371 local b = vim.buffer(true) -- first buffer in list
372 while b ~= nil do
373 print(b.number, b.name, #b)
374 b = b:next()
375 end
376 vim.beep()
377 EOF
378 endfunction
379<
380
381==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +01003828. Window userdata *lua-window*
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200383
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200384Window objects represent vim windows. A window userdata "w" has the following
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200385properties and methods:
386
387Properties
388----------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200389 o "w()" sets "w" as the current window.
390 o "w.buffer" contains the buffer of window "w" (read-only).
391 o "w.line" represents the cursor line position in window "w".
392 o "w.col" represents the cursor column position in window "w".
393 o "w.width" represents the width of window "w".
394 o "w.height" represents the height of window "w".
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200395
396Methods
397-------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200398 o "w:next()" returns the window next to "w".
399 o "w:previous()" returns the window previous to "w".
400 o "w:isvalid()" returns 'true' (boolean) if window "w" corresponds to
401 a "real" (not freed from memory) Vim window.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200402
403Examples:
404>
405 :lua w = vim.window() -- current window
406 :lua print(w.buffer.name, w.line, w.col)
407 :lua w.width = w.width + math.random(10)
408 :lua w.height = 2 * math.random() * w.height
409 :lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end
410 :lua print("There are " .. n .. " windows")
411<
412
413==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +01004149. luaeval() Vim function *lua-luaeval* *lua-eval*
Bram Moolenaar1dced572012-04-05 16:54:08 +0200415
416The (dual) equivalent of "vim.eval" for passing Lua values to Vim is
417"luaeval". "luaeval" takes an expression string and an optional argument and
418returns the result of the expression. It is semantically equivalent in Lua to:
419>
420 local chunkheader = "local _A = select(1, ...) return "
421 function luaeval (expstr, arg)
422 local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
423 return chunk(arg) -- return typval
424 end
425<
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200426Note that "_A" receives the argument to "luaeval". Lua numbers, strings, and
Bram Moolenaarb7828692019-03-23 13:57:02 +0100427list, dict, blob, and funcref userdata are converted to their Vim respective
428types, while Lua booleans are converted to numbers. An error is thrown if
429conversion of any of the remaining Lua types, including userdata other than
430lists, dicts, blobs, and funcrefs, is attempted.
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200431
432Examples: >
Bram Moolenaar1dced572012-04-05 16:54:08 +0200433
434 :echo luaeval('math.pi')
435 :lua a = vim.list():add('newlist')
436 :let a = luaeval('a')
437 :echo a[0] " 'newlist'
438 :function Rand(x,y) " random uniform between x and y
439 : return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
440 : endfunction
441 :echo Rand(1,10)
442
443
444==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +010044510. Dynamic loading *lua-dynamic*
Bram Moolenaard94464e2015-11-02 15:28:18 +0100446
447On MS-Windows and Unix the Lua library can be loaded dynamically. The
448|:version| output then includes |+lua/dyn|.
449
450This means that Vim will search for the Lua DLL or shared library file only
451when needed. When you don't use the Lua interface you don't need it, thus
452you can use Vim without this file.
453
Bram Moolenaard94464e2015-11-02 15:28:18 +0100454
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100455MS-Windows ~
456
457To use the Lua interface the Lua DLL must be in your search path. In a
458console window type "path" to see what directories are used. The 'luadll'
459option can be also used to specify the Lua DLL. The version of the DLL must
460match the Lua version Vim was compiled with.
461
462
463Unix ~
464
465The 'luadll' option can be used to specify the Lua shared library file instead
466of DYNAMIC_LUA_DLL file what was specified at compile time. The version of
467the shared library must match the Lua version Vim was compiled with.
Bram Moolenaard94464e2015-11-02 15:28:18 +0100468
469
470==============================================================================
Bram Moolenaar1dced572012-04-05 16:54:08 +0200471 vim:tw=78:ts=8:noet:ft=help:norl: