blob: a68f972f677858d72faa3a08ce9da3927fa3fb0a [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 Moolenaar52b91d82013-06-15 21:39:51 +0200135. Funcref userdata |lua-funcref|
146. Buffer userdata |lua-buffer|
157. Window userdata |lua-window|
168. The luaeval function |lua-luaeval|
Bram Moolenaard94464e2015-11-02 15:28:18 +0100179. Dynamic loading |lua-dynamic|
Bram Moolenaar0ba04292010-07-14 23:23:17 +020018
19{Vi does not have any of these commands}
20
21The Lua interface is available only when Vim was compiled with the
22|+lua| feature.
23
24==============================================================================
251. Commands *lua-commands*
26
27 *:lua*
28:[range]lua {chunk}
29 Execute Lua chunk {chunk}. {not in Vi}
30
31Examples:
32>
33 :lua print("Hello, Vim!")
34 :lua local curbuf = vim.buffer() curbuf[7] = "line #7"
35<
36
37:[range]lua << {endmarker}
38{script}
39{endmarker}
40 Execute Lua script {script}. {not in Vi}
41 Note: This command doesn't work when the Lua
42 feature wasn't compiled in. To avoid errors, see
43 |script-here|.
44
45{endmarker} must NOT be preceded by any white space. If {endmarker} is
46omitted from after the "<<", a dot '.' must be used after {script}, like
47for the |:append| and |:insert| commands.
48This 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,$".
77 {not in Vi}
Bram Moolenaar0ba04292010-07-14 23:23:17 +020078
79Examples:
80>
81 :luado return string.format("%s\t%d", line:reverse(), #line)
82
83 :lua require"lpeg"
84 :lua -- balanced parenthesis grammar:
85 :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
86 :luado if bp:match(line) then return "-->\t" .. line end
87<
88
89 *:luafile*
90:[range]luafile {file}
91 Execute Lua script in {file}. {not in Vi}
92 The whole argument is used as a single file name.
93
94Examples:
95>
96 :luafile script.lua
97 :luafile %
98<
99
100All these commands execute a Lua chunk from either the command line (:lua and
101:luado) or a file (:luafile) with the given line [range]. Similarly to the Lua
102interpreter, each chunk has its own scope and so only global variables are
Bram Moolenaar1dced572012-04-05 16:54:08 +0200103shared between command calls. All Lua default libraries are available. In
104addition, Lua "print" function has its output redirected to the Vim message
105area, with arguments separated by a white space instead of a tab.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200106
Bram Moolenaar9855d6b2010-07-18 14:34:51 +0200107Lua uses the "vim" module (see |lua-vim|) to issue commands to Vim
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200108and manage buffers (|lua-buffer|) and windows (|lua-window|). However,
109procedures that alter buffer content, open new buffers, and change cursor
Bram Moolenaar9855d6b2010-07-18 14:34:51 +0200110position are restricted when the command is executed in the |sandbox|.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200111
112
113==============================================================================
1142. The vim module *lua-vim*
115
116Lua interfaces Vim through the "vim" module. The first and last line of the
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200117input range are stored in "vim.firstline" and "vim.lastline" respectively. The
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200118module also includes routines for buffer, window, and current line queries,
119Vim evaluation and command execution, and others.
120
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200121 vim.list([arg]) Returns an empty list or, if "arg" is a Lua
122 table with numeric keys 1, ..., n (a
123 "sequence"), returns a list l such that l[i] =
124 arg[i] for i = 1, ..., n (see |List|).
125 Non-numeric keys are not used to initialize
126 the list. See also |lua-eval| for conversion
127 rules. Example: >
Bram Moolenaarfd358112018-07-07 23:21:31 +0200128 :lua t = {math.pi, false, say = 'hi'}
129 :echo luaeval('vim.list(t)')
130 :" [3.141593, v:false], 'say' is ignored
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200131<
132 vim.dict([arg]) Returns an empty dictionary or, if "arg" is a
133 Lua table, returns a dict d such that d[k] =
134 arg[k] for all string keys k in "arg" (see
135 |Dictionary|). Number keys are converted to
136 strings. Keys that are not strings are not
137 used to initialize the dictionary. See also
138 |lua-eval| for conversion rules. Example: >
Bram Moolenaarfd358112018-07-07 23:21:31 +0200139 :lua t = {math.pi, false, say = 'hi'}
140 :echo luaeval('vim.dict(t)')
141 :" {'1': 3.141593, '2': v:false,
142 :" 'say': 'hi'}
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200143<
144 vim.funcref({name}) Returns a Funcref to function {name} (see
Bram Moolenaarfd358112018-07-07 23:21:31 +0200145 |Funcref|). It is equivalent to Vim's
146 function().
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200147
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200148 vim.buffer([arg]) If "arg" is a number, returns buffer with
149 number "arg" in the buffer list or, if "arg"
150 is a string, returns buffer whose full or short
151 name is "arg". In both cases, returns 'nil'
152 (nil value, not string) if the buffer is not
153 found. Otherwise, if "toboolean(arg)" is
154 'true' returns the first buffer in the buffer
155 list or else the current buffer.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200156
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200157 vim.window([arg]) If "arg" is a number, returns window with
158 number "arg" or 'nil' (nil value, not string)
159 if not found. Otherwise, if "toboolean(arg)"
160 is 'true' returns the first window or else the
161 current window.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200162
Bram Moolenaar1dced572012-04-05 16:54:08 +0200163 vim.type({arg}) Returns the type of {arg}. It is equivalent to
164 Lua's "type" function, but returns "list",
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200165 "dict", "funcref", "buffer", or "window" if
166 {arg} is a list, dictionary, funcref, buffer,
167 or window, respectively. Examples: >
Bram Moolenaar1dced572012-04-05 16:54:08 +0200168 :lua l = vim.list()
169 :lua print(type(l), vim.type(l))
Bram Moolenaar2f362bf2018-07-01 19:49:27 +0200170 :" list
Bram Moolenaar1dced572012-04-05 16:54:08 +0200171<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200172 vim.command({cmd}) Executes the vim (ex-mode) command {cmd}.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200173 Examples: >
174 :lua vim.command"set tw=60"
175 :lua vim.command"normal ddp"
176<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200177 vim.eval({expr}) Evaluates expression {expr} (see |expression|),
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200178 converts the result to Lua, and returns it.
179 Vim strings and numbers are directly converted
180 to Lua strings and numbers respectively. Vim
181 lists and dictionaries are converted to Lua
Bram Moolenaar1dced572012-04-05 16:54:08 +0200182 userdata (see |lua-list| and |lua-dict|).
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200183 Examples: >
184 :lua tw = vim.eval"&tw"
185 :lua print(vim.eval"{'a': 'one'}".a)
186<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200187 vim.line() Returns the current line (without the trailing
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200188 <EOL>), a Lua string.
189
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200190 vim.beep() Beeps.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200191
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200192 vim.open({fname}) Opens a new buffer for file {fname} and
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200193 returns it. Note that the buffer is not set as
194 current.
195
196
197==============================================================================
Bram Moolenaar1dced572012-04-05 16:54:08 +02001983. List userdata *lua-list*
199
200List userdata represent vim lists, and the interface tries to follow closely
201Vim's syntax for lists. Since lists are objects, changes in list references in
202Lua are reflected in Vim and vice-versa. A list "l" has the following
203properties and methods:
204
205Properties
206----------
207 o "#l" is the number of items in list "l", equivalent to "len(l)"
208 in Vim.
209 o "l[k]" returns the k-th item in "l"; "l" is zero-indexed, as in Vim.
210 To modify the k-th item, simply do "l[k] = newitem"; in
211 particular, "l[k] = nil" removes the k-th item from "l".
212 o "l()" returns an iterator for "l".
213
214Methods
215-------
216 o "l:add(item)" appends "item" to the end of "l".
217 o "l:insert(item[, pos])" inserts "item" at (optional)
218 position "pos" in the list. The default value for "pos" is 0.
219
220Examples:
221>
222 :let l = [1, 'item']
223 :lua l = vim.eval('l') -- same 'l'
224 :lua l:add(vim.list())
225 :lua l[0] = math.pi
226 :echo l[0] " 3.141593
227 :lua l[0] = nil -- remove first item
228 :lua l:insert(true, 1)
229 :lua print(l, #l, l[0], l[1], l[-1])
230 :lua for item in l() do print(item) end
231<
232
233==============================================================================
2344. Dict userdata *lua-dict*
235
236Similarly to list userdata, dict userdata represent vim dictionaries; since
237dictionaries are also objects, references are kept between Lua and Vim. A dict
238"d" has the following properties:
239
240Properties
241----------
242 o "#d" is the number of items in dict "d", equivalent to "len(d)"
243 in Vim.
244 o "d.key" or "d['key']" returns the value at entry "key" in "d".
245 To modify the entry at this key, simply do "d.key = newvalue"; in
246 particular, "d.key = nil" removes the entry from "d".
247 o "d()" returns an iterator for "d" and is equivalent to "items(d)" in
248 Vim.
249
250Examples:
251>
252 :let d = {'n':10}
253 :lua d = vim.eval('d') -- same 'd'
254 :lua print(d, d.n, #d)
255 :let d.self = d
256 :lua for k, v in d() do print(d, k, v) end
257 :lua d.x = math.pi
258 :lua d.self = nil -- remove entry
259 :echo d
260<
261
262==============================================================================
Bram Moolenaar52b91d82013-06-15 21:39:51 +02002635. Funcref userdata *lua-funcref*
264
265Funcref userdata represent funcref variables in Vim. Funcrefs that were
266defined with a "dict" attribute need to be obtained as a dictionary key
267in order to have "self" properly assigned to the dictionary (see examples
268below.) A funcref "f" has the following properties:
269
270Properties
271----------
272 o "#f" is the name of the function referenced by "f"
273 o "f(...)" calls the function referenced by "f" (with arguments)
274
275Examples:
276>
277 :function I(x)
278 : return a:x
279 : endfunction
280 :let R = function('I')
281 :lua i1 = vim.funcref('I')
282 :lua i2 = vim.eval('R')
283 :lua print(#i1, #i2) -- both 'I'
284 :lua print(i1, i2, #i2(i1) == #i1(i2))
285 :function Mylen() dict
286 : return len(self.data)
287 : endfunction
288 :let mydict = {'data': [0, 1, 2, 3]}
289 :lua d = vim.eval('mydict'); d.len = vim.funcref('Mylen')
290 :echo mydict.len()
291 :lua l = d.len -- assign d as 'self'
292 :lua print(l())
293<
294
295==============================================================================
2966. Buffer userdata *lua-buffer*
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200297
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200298Buffer userdata represent vim buffers. A buffer userdata "b" has the following
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200299properties and methods:
300
301Properties
302----------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200303 o "b()" sets "b" as the current buffer.
304 o "#b" is the number of lines in buffer "b".
305 o "b[k]" represents line number k: "b[k] = newline" replaces line k
306 with string "newline" and "b[k] = nil" deletes line k.
307 o "b.name" contains the short name of buffer "b" (read-only).
308 o "b.fname" contains the full name of buffer "b" (read-only).
309 o "b.number" contains the position of buffer "b" in the buffer list
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200310 (read-only).
311
312Methods
313-------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200314 o "b:insert(newline[, pos])" inserts string "newline" at (optional)
315 position "pos" in the buffer. The default value for "pos" is
316 "#b + 1". If "pos == 0" then "newline" becomes the first line in
317 the buffer.
318 o "b:next()" returns the buffer next to "b" in the buffer list.
319 o "b:previous()" returns the buffer previous to "b" in the buffer
320 list.
321 o "b:isvalid()" returns 'true' (boolean) if buffer "b" corresponds to
322 a "real" (not freed from memory) Vim buffer.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200323
324Examples:
325>
326 :lua b = vim.buffer() -- current buffer
327 :lua print(b.name, b.number)
328 :lua b[1] = "first line"
329 :lua b:insert("FIRST!", 0)
330 :lua b[1] = nil -- delete top line
331 :lua for i=1,3 do b:insert(math.random()) end
332 :3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end
333 :lua vim.open"myfile"() -- open buffer and set it as current
334
335 function! ListBuffers()
336 lua << EOF
337 local b = vim.buffer(true) -- first buffer in list
338 while b ~= nil do
339 print(b.number, b.name, #b)
340 b = b:next()
341 end
342 vim.beep()
343 EOF
344 endfunction
345<
346
347==============================================================================
Bram Moolenaar52b91d82013-06-15 21:39:51 +02003487. Window userdata *lua-window*
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200349
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200350Window objects represent vim windows. A window userdata "w" has the following
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200351properties and methods:
352
353Properties
354----------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200355 o "w()" sets "w" as the current window.
356 o "w.buffer" contains the buffer of window "w" (read-only).
357 o "w.line" represents the cursor line position in window "w".
358 o "w.col" represents the cursor column position in window "w".
359 o "w.width" represents the width of window "w".
360 o "w.height" represents the height of window "w".
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200361
362Methods
363-------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200364 o "w:next()" returns the window next to "w".
365 o "w:previous()" returns the window previous to "w".
366 o "w:isvalid()" returns 'true' (boolean) if window "w" corresponds to
367 a "real" (not freed from memory) Vim window.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200368
369Examples:
370>
371 :lua w = vim.window() -- current window
372 :lua print(w.buffer.name, w.line, w.col)
373 :lua w.width = w.width + math.random(10)
374 :lua w.height = 2 * math.random() * w.height
375 :lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end
376 :lua print("There are " .. n .. " windows")
377<
378
379==============================================================================
Bram Moolenaar52b91d82013-06-15 21:39:51 +02003808. The luaeval function *lua-luaeval* *lua-eval*
Bram Moolenaar1dced572012-04-05 16:54:08 +0200381
382The (dual) equivalent of "vim.eval" for passing Lua values to Vim is
383"luaeval". "luaeval" takes an expression string and an optional argument and
384returns the result of the expression. It is semantically equivalent in Lua to:
385>
386 local chunkheader = "local _A = select(1, ...) return "
387 function luaeval (expstr, arg)
388 local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
389 return chunk(arg) -- return typval
390 end
391<
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200392Note that "_A" receives the argument to "luaeval". Lua numbers, strings, and
393list, dict, and funcref userdata are converted to their Vim respective types,
394while Lua booleans are converted to numbers. An error is thrown if conversion
395of any of the remaining Lua types, including userdata other than lists, dicts,
396and funcrefs, is attempted.
397
398Examples: >
Bram Moolenaar1dced572012-04-05 16:54:08 +0200399
400 :echo luaeval('math.pi')
401 :lua a = vim.list():add('newlist')
402 :let a = luaeval('a')
403 :echo a[0] " 'newlist'
404 :function Rand(x,y) " random uniform between x and y
405 : return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
406 : endfunction
407 :echo Rand(1,10)
408
409
410==============================================================================
Bram Moolenaard94464e2015-11-02 15:28:18 +01004119. Dynamic loading *lua-dynamic*
412
413On MS-Windows and Unix the Lua library can be loaded dynamically. The
414|:version| output then includes |+lua/dyn|.
415
416This means that Vim will search for the Lua DLL or shared library file only
417when needed. When you don't use the Lua interface you don't need it, thus
418you can use Vim without this file.
419
Bram Moolenaard94464e2015-11-02 15:28:18 +0100420
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100421MS-Windows ~
422
423To use the Lua interface the Lua DLL must be in your search path. In a
424console window type "path" to see what directories are used. The 'luadll'
425option can be also used to specify the Lua DLL. The version of the DLL must
426match the Lua version Vim was compiled with.
427
428
429Unix ~
430
431The 'luadll' option can be used to specify the Lua shared library file instead
432of DYNAMIC_LUA_DLL file what was specified at compile time. The version of
433the shared library must match the Lua version Vim was compiled with.
Bram Moolenaard94464e2015-11-02 15:28:18 +0100434
435
436==============================================================================
Bram Moolenaar1dced572012-04-05 16:54:08 +0200437 vim:tw=78:ts=8:noet:ft=help:norl: