blob: d3576100e75b4b241086f9486618441e4ffc6168 [file] [log] [blame]
Bram Moolenaarb1c91982018-05-17 17:04:55 +02001*if_lua.txt* For Vim version 8.1. Last change: 2015 Oct 16
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
20{Vi does not have any of these commands}
21
22The Lua interface is available only when Vim was compiled with the
23|+lua| feature.
24
25==============================================================================
261. Commands *lua-commands*
27
28 *:lua*
29:[range]lua {chunk}
30 Execute Lua chunk {chunk}. {not in Vi}
31
32Examples:
33>
34 :lua print("Hello, Vim!")
35 :lua local curbuf = vim.buffer() curbuf[7] = "line #7"
36<
37
38:[range]lua << {endmarker}
39{script}
40{endmarker}
41 Execute Lua script {script}. {not in Vi}
42 Note: This command doesn't work when the Lua
43 feature wasn't compiled in. To avoid errors, see
44 |script-here|.
45
46{endmarker} must NOT be preceded by any white space. If {endmarker} is
47omitted from after the "<<", a dot '.' must be used after {script}, like
48for the |:append| and |:insert| commands.
49This form of the |:lua| command is mainly useful for including Lua code
50in Vim scripts.
51
52Example:
53>
54 function! CurrentLineInfo()
55 lua << EOF
56 local linenr = vim.window().line
57 local curline = vim.buffer()[linenr]
58 print(string.format("Current line [%d] has %d chars",
59 linenr, #curline))
60 EOF
61 endfunction
62<
Bram Moolenaarabd468e2016-09-08 22:22:43 +020063To see what version of Lua you have: >
64 :lua print(_VERSION)
65
66If you use LuaJIT you can also use this: >
67 :lua print(jit.version)
68<
Bram Moolenaar0ba04292010-07-14 23:23:17 +020069
70 *:luado*
Bram Moolenaar53bfca22012-04-13 23:04:47 +020071:[range]luado {body} Execute Lua function "function (line, linenr) {body}
72 end" for each line in the [range], with the function
73 argument being set to the text of each line in turn,
74 without a trailing <EOL>, and the current line number.
75 If the value returned by the function is a string it
76 becomes the text of the line in the current turn. The
77 default for [range] is the whole file: "1,$".
78 {not in Vi}
Bram Moolenaar0ba04292010-07-14 23:23:17 +020079
80Examples:
81>
82 :luado return string.format("%s\t%d", line:reverse(), #line)
83
84 :lua require"lpeg"
85 :lua -- balanced parenthesis grammar:
86 :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
87 :luado if bp:match(line) then return "-->\t" .. line end
88<
89
90 *:luafile*
91:[range]luafile {file}
92 Execute Lua script in {file}. {not in Vi}
93 The whole argument is used as a single file name.
94
95Examples:
96>
97 :luafile script.lua
98 :luafile %
99<
100
101All these commands execute a Lua chunk from either the command line (:lua and
102:luado) or a file (:luafile) with the given line [range]. Similarly to the Lua
103interpreter, each chunk has its own scope and so only global variables are
Bram Moolenaar1dced572012-04-05 16:54:08 +0200104shared between command calls. All Lua default libraries are available. In
105addition, Lua "print" function has its output redirected to the Vim message
106area, with arguments separated by a white space instead of a tab.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200107
Bram Moolenaar9855d6b2010-07-18 14:34:51 +0200108Lua uses the "vim" module (see |lua-vim|) to issue commands to Vim
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200109and manage buffers (|lua-buffer|) and windows (|lua-window|). However,
110procedures that alter buffer content, open new buffers, and change cursor
Bram Moolenaar9855d6b2010-07-18 14:34:51 +0200111position are restricted when the command is executed in the |sandbox|.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200112
113
114==============================================================================
1152. The vim module *lua-vim*
116
117Lua interfaces Vim through the "vim" module. The first and last line of the
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200118input range are stored in "vim.firstline" and "vim.lastline" respectively. The
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200119module also includes routines for buffer, window, and current line queries,
120Vim evaluation and command execution, and others.
121
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200122 vim.list([arg]) Returns an empty list or, if "arg" is a Lua
123 table with numeric keys 1, ..., n (a
124 "sequence"), returns a list l such that l[i] =
125 arg[i] for i = 1, ..., n (see |List|).
126 Non-numeric keys are not used to initialize
127 the list. See also |lua-eval| for conversion
128 rules. Example: >
Bram Moolenaarfd358112018-07-07 23:21:31 +0200129 :lua t = {math.pi, false, say = 'hi'}
130 :echo luaeval('vim.list(t)')
131 :" [3.141593, v:false], 'say' is ignored
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200132<
133 vim.dict([arg]) Returns an empty dictionary or, if "arg" is a
134 Lua table, returns a dict d such that d[k] =
135 arg[k] for all string keys k in "arg" (see
136 |Dictionary|). Number keys are converted to
137 strings. Keys that are not strings are not
138 used to initialize the dictionary. See also
139 |lua-eval| for conversion rules. Example: >
Bram Moolenaarfd358112018-07-07 23:21:31 +0200140 :lua t = {math.pi, false, say = 'hi'}
141 :echo luaeval('vim.dict(t)')
142 :" {'1': 3.141593, '2': v:false,
143 :" 'say': 'hi'}
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200144<
Bram Moolenaarb7828692019-03-23 13:57:02 +0100145 vim.blob([arg]) Returns an empty blob or, if "arg" is a Lua
146 string, returns a blob b such that b is
147 equivalent to "arg" as a byte string.
148 Examples: >
149 :lua s = "12ab\x00\x80\xfe\xff"
150 :echo luaeval('vim.blob(s)')
151 :" 0z31326162.0080FEFF
152<
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200153 vim.funcref({name}) Returns a Funcref to function {name} (see
Bram Moolenaarfd358112018-07-07 23:21:31 +0200154 |Funcref|). It is equivalent to Vim's
155 function().
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200156
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200157 vim.buffer([arg]) If "arg" is a number, returns buffer with
158 number "arg" in the buffer list or, if "arg"
159 is a string, returns buffer whose full or short
160 name is "arg". In both cases, returns 'nil'
161 (nil value, not string) if the buffer is not
162 found. Otherwise, if "toboolean(arg)" is
163 'true' returns the first buffer in the buffer
164 list or else the current buffer.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200165
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200166 vim.window([arg]) If "arg" is a number, returns window with
167 number "arg" or 'nil' (nil value, not string)
168 if not found. Otherwise, if "toboolean(arg)"
169 is 'true' returns the first window or else the
170 current window.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200171
Bram Moolenaar1dced572012-04-05 16:54:08 +0200172 vim.type({arg}) Returns the type of {arg}. It is equivalent to
173 Lua's "type" function, but returns "list",
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200174 "dict", "funcref", "buffer", or "window" if
175 {arg} is a list, dictionary, funcref, buffer,
176 or window, respectively. Examples: >
Bram Moolenaar1dced572012-04-05 16:54:08 +0200177 :lua l = vim.list()
178 :lua print(type(l), vim.type(l))
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200179 :" list
Bram Moolenaar1dced572012-04-05 16:54:08 +0200180<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200181 vim.command({cmd}) Executes the vim (ex-mode) command {cmd}.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200182 Examples: >
183 :lua vim.command"set tw=60"
184 :lua vim.command"normal ddp"
185<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200186 vim.eval({expr}) Evaluates expression {expr} (see |expression|),
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200187 converts the result to Lua, and returns it.
188 Vim strings and numbers are directly converted
189 to Lua strings and numbers respectively. Vim
190 lists and dictionaries are converted to Lua
Bram Moolenaar1dced572012-04-05 16:54:08 +0200191 userdata (see |lua-list| and |lua-dict|).
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200192 Examples: >
193 :lua tw = vim.eval"&tw"
194 :lua print(vim.eval"{'a': 'one'}".a)
195<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200196 vim.line() Returns the current line (without the trailing
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200197 <EOL>), a Lua string.
198
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200199 vim.beep() Beeps.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200200
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200201 vim.open({fname}) Opens a new buffer for file {fname} and
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200202 returns it. Note that the buffer is not set as
203 current.
204
205
206==============================================================================
Bram Moolenaar1dced572012-04-05 16:54:08 +02002073. List userdata *lua-list*
208
209List userdata represent vim lists, and the interface tries to follow closely
210Vim's syntax for lists. Since lists are objects, changes in list references in
211Lua are reflected in Vim and vice-versa. A list "l" has the following
212properties and methods:
213
214Properties
215----------
216 o "#l" is the number of items in list "l", equivalent to "len(l)"
217 in Vim.
218 o "l[k]" returns the k-th item in "l"; "l" is zero-indexed, as in Vim.
219 To modify the k-th item, simply do "l[k] = newitem"; in
220 particular, "l[k] = nil" removes the k-th item from "l".
221 o "l()" returns an iterator for "l".
222
223Methods
224-------
225 o "l:add(item)" appends "item" to the end of "l".
226 o "l:insert(item[, pos])" inserts "item" at (optional)
227 position "pos" in the list. The default value for "pos" is 0.
228
229Examples:
230>
231 :let l = [1, 'item']
232 :lua l = vim.eval('l') -- same 'l'
233 :lua l:add(vim.list())
234 :lua l[0] = math.pi
235 :echo l[0] " 3.141593
236 :lua l[0] = nil -- remove first item
237 :lua l:insert(true, 1)
238 :lua print(l, #l, l[0], l[1], l[-1])
239 :lua for item in l() do print(item) end
240<
241
242==============================================================================
2434. Dict userdata *lua-dict*
244
245Similarly to list userdata, dict userdata represent vim dictionaries; since
246dictionaries are also objects, references are kept between Lua and Vim. A dict
247"d" has the following properties:
248
249Properties
250----------
251 o "#d" is the number of items in dict "d", equivalent to "len(d)"
252 in Vim.
253 o "d.key" or "d['key']" returns the value at entry "key" in "d".
254 To modify the entry at this key, simply do "d.key = newvalue"; in
255 particular, "d.key = nil" removes the entry from "d".
256 o "d()" returns an iterator for "d" and is equivalent to "items(d)" in
257 Vim.
258
259Examples:
260>
261 :let d = {'n':10}
262 :lua d = vim.eval('d') -- same 'd'
263 :lua print(d, d.n, #d)
264 :let d.self = d
265 :lua for k, v in d() do print(d, k, v) end
266 :lua d.x = math.pi
267 :lua d.self = nil -- remove entry
268 :echo d
269<
270
271==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +01002725. Blob userdata *lua-blob*
273
274Blob userdata represent vim blobs. A blob "b" has the following properties:
275
276Properties
277----------
278 o "#b" is the length of blob "b", equivalent to "len(b)" in Vim.
279 o "b[k]" returns the k-th item in "b"; "b" is zero-indexed, as in Vim.
280 To modify the k-th item, simply do "b[k] = number"; in particular,
281 "b[#b] = number" can append a byte to tail.
282
283Methods
284-------
285 o "b:add(bytes)" appends "bytes" to the end of "b".
286
287Examples:
288>
289 :let b = 0z001122
290 :lua b = vim.eval('b') -- same 'b'
291 :lua print(b, b[0], #b)
292 :lua b[1] = 32
293 :lua b[#b] = 0x33 -- append a byte to tail
294 :lua b:add("\x80\x81\xfe\xff")
295 :echo b
296<
297
298==============================================================================
2996. Funcref userdata *lua-funcref*
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200300
301Funcref userdata represent funcref variables in Vim. Funcrefs that were
302defined with a "dict" attribute need to be obtained as a dictionary key
303in order to have "self" properly assigned to the dictionary (see examples
304below.) A funcref "f" has the following properties:
305
306Properties
307----------
308 o "#f" is the name of the function referenced by "f"
309 o "f(...)" calls the function referenced by "f" (with arguments)
310
311Examples:
312>
313 :function I(x)
314 : return a:x
315 : endfunction
316 :let R = function('I')
317 :lua i1 = vim.funcref('I')
318 :lua i2 = vim.eval('R')
319 :lua print(#i1, #i2) -- both 'I'
320 :lua print(i1, i2, #i2(i1) == #i1(i2))
321 :function Mylen() dict
322 : return len(self.data)
323 : endfunction
324 :let mydict = {'data': [0, 1, 2, 3]}
325 :lua d = vim.eval('mydict'); d.len = vim.funcref('Mylen')
326 :echo mydict.len()
327 :lua l = d.len -- assign d as 'self'
328 :lua print(l())
329<
330
331==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +01003327. Buffer userdata *lua-buffer*
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200333
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200334Buffer userdata represent vim buffers. A buffer userdata "b" has the following
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200335properties and methods:
336
337Properties
338----------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200339 o "b()" sets "b" as the current buffer.
340 o "#b" is the number of lines in buffer "b".
341 o "b[k]" represents line number k: "b[k] = newline" replaces line k
342 with string "newline" and "b[k] = nil" deletes line k.
343 o "b.name" contains the short name of buffer "b" (read-only).
344 o "b.fname" contains the full name of buffer "b" (read-only).
345 o "b.number" contains the position of buffer "b" in the buffer list
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200346 (read-only).
347
348Methods
349-------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200350 o "b:insert(newline[, pos])" inserts string "newline" at (optional)
351 position "pos" in the buffer. The default value for "pos" is
352 "#b + 1". If "pos == 0" then "newline" becomes the first line in
353 the buffer.
354 o "b:next()" returns the buffer next to "b" in the buffer list.
355 o "b:previous()" returns the buffer previous to "b" in the buffer
356 list.
357 o "b:isvalid()" returns 'true' (boolean) if buffer "b" corresponds to
358 a "real" (not freed from memory) Vim buffer.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200359
360Examples:
361>
362 :lua b = vim.buffer() -- current buffer
363 :lua print(b.name, b.number)
364 :lua b[1] = "first line"
365 :lua b:insert("FIRST!", 0)
366 :lua b[1] = nil -- delete top line
367 :lua for i=1,3 do b:insert(math.random()) end
368 :3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end
369 :lua vim.open"myfile"() -- open buffer and set it as current
370
371 function! ListBuffers()
372 lua << EOF
373 local b = vim.buffer(true) -- first buffer in list
374 while b ~= nil do
375 print(b.number, b.name, #b)
376 b = b:next()
377 end
378 vim.beep()
379 EOF
380 endfunction
381<
382
383==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +01003848. Window userdata *lua-window*
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200385
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200386Window objects represent vim windows. A window userdata "w" has the following
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200387properties and methods:
388
389Properties
390----------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200391 o "w()" sets "w" as the current window.
392 o "w.buffer" contains the buffer of window "w" (read-only).
393 o "w.line" represents the cursor line position in window "w".
394 o "w.col" represents the cursor column position in window "w".
395 o "w.width" represents the width of window "w".
396 o "w.height" represents the height of window "w".
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200397
398Methods
399-------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200400 o "w:next()" returns the window next to "w".
401 o "w:previous()" returns the window previous to "w".
402 o "w:isvalid()" returns 'true' (boolean) if window "w" corresponds to
403 a "real" (not freed from memory) Vim window.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200404
405Examples:
406>
407 :lua w = vim.window() -- current window
408 :lua print(w.buffer.name, w.line, w.col)
409 :lua w.width = w.width + math.random(10)
410 :lua w.height = 2 * math.random() * w.height
411 :lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end
412 :lua print("There are " .. n .. " windows")
413<
414
415==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +01004169. luaeval() Vim function *lua-luaeval* *lua-eval*
Bram Moolenaar1dced572012-04-05 16:54:08 +0200417
418The (dual) equivalent of "vim.eval" for passing Lua values to Vim is
419"luaeval". "luaeval" takes an expression string and an optional argument and
420returns the result of the expression. It is semantically equivalent in Lua to:
421>
422 local chunkheader = "local _A = select(1, ...) return "
423 function luaeval (expstr, arg)
424 local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
425 return chunk(arg) -- return typval
426 end
427<
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200428Note that "_A" receives the argument to "luaeval". Lua numbers, strings, and
Bram Moolenaarb7828692019-03-23 13:57:02 +0100429list, dict, blob, and funcref userdata are converted to their Vim respective
430types, while Lua booleans are converted to numbers. An error is thrown if
431conversion of any of the remaining Lua types, including userdata other than
432lists, dicts, blobs, and funcrefs, is attempted.
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200433
434Examples: >
Bram Moolenaar1dced572012-04-05 16:54:08 +0200435
436 :echo luaeval('math.pi')
437 :lua a = vim.list():add('newlist')
438 :let a = luaeval('a')
439 :echo a[0] " 'newlist'
440 :function Rand(x,y) " random uniform between x and y
441 : return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
442 : endfunction
443 :echo Rand(1,10)
444
445
446==============================================================================
Bram Moolenaarb7828692019-03-23 13:57:02 +010044710. Dynamic loading *lua-dynamic*
Bram Moolenaard94464e2015-11-02 15:28:18 +0100448
449On MS-Windows and Unix the Lua library can be loaded dynamically. The
450|:version| output then includes |+lua/dyn|.
451
452This means that Vim will search for the Lua DLL or shared library file only
453when needed. When you don't use the Lua interface you don't need it, thus
454you can use Vim without this file.
455
Bram Moolenaard94464e2015-11-02 15:28:18 +0100456
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100457MS-Windows ~
458
459To use the Lua interface the Lua DLL must be in your search path. In a
460console window type "path" to see what directories are used. The 'luadll'
461option can be also used to specify the Lua DLL. The version of the DLL must
462match the Lua version Vim was compiled with.
463
464
465Unix ~
466
467The 'luadll' option can be used to specify the Lua shared library file instead
468of DYNAMIC_LUA_DLL file what was specified at compile time. The version of
469the shared library must match the Lua version Vim was compiled with.
Bram Moolenaard94464e2015-11-02 15:28:18 +0100470
471
472==============================================================================
Bram Moolenaar1dced572012-04-05 16:54:08 +0200473 vim:tw=78:ts=8:noet:ft=help:norl: