xref: /vim-8.2.3635/runtime/doc/if_lua.txt (revision fb094e14)
1*if_lua.txt*    For Vim version 8.0.  Last change: 2015 Oct 16
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. Funcref userdata		|lua-funcref|
146. Buffer userdata		|lua-buffer|
157. Window userdata		|lua-window|
168. The luaeval function		|lua-luaeval|
179. Dynamic loading		|lua-dynamic|
18
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<
62To 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<
68
69							*:luado*
70:[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}
78
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
103shared 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.
106
107Lua uses the "vim" module (see |lua-vim|) to issue commands to Vim
108and manage buffers (|lua-buffer|) and windows (|lua-window|). However,
109procedures that alter buffer content, open new buffers, and change cursor
110position are restricted when the command is executed in the |sandbox|.
111
112
113==============================================================================
1142. The vim module					*lua-vim*
115
116Lua interfaces Vim through the "vim" module. The first and last line of the
117input range are stored in "vim.firstline" and "vim.lastline" respectively. The
118module also includes routines for buffer, window, and current line queries,
119Vim evaluation and command execution, and others.
120
121	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: >
128					:lua t = {math.pi, false, say = 'hi'}
129					:echo luaeval('vim.list(t)')
130					:" [3.141593, 0], 'say' is ignored
131<
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: >
139					:lua t = {math.pi, false, say = 'hi'}
140					:echo luaeval('vim.dict(t)')
141					:" {'say': 'hi'}, numeric keys ignored
142<
143	vim.funcref({name})	Returns a Funcref to function {name} (see
144				|Funcref|). It is equivalent to Vim's
145				"function". NOT IMPLEMENTED YET
146
147	vim.buffer([arg])	If "arg" is a number, returns buffer with
148				number "arg" in the buffer list or, if "arg"
149				is a string, returns buffer whose full or short
150				name is "arg". In both cases, returns 'nil'
151				(nil value, not string) if the buffer is not
152				found. Otherwise, if "toboolean(arg)" is
153				'true' returns the first buffer in the buffer
154				list or else the current buffer.
155
156	vim.window([arg])	If "arg" is a number, returns window with
157				number "arg" or 'nil' (nil value, not string)
158				if not found. Otherwise, if "toboolean(arg)"
159				is 'true' returns the first window or else the
160				current window.
161
162	vim.type({arg})		Returns the type of {arg}. It is equivalent to
163				Lua's "type" function, but returns "list",
164				"dict", "funcref", "buffer", or "window" if
165				{arg} is a list, dictionary, funcref, buffer,
166				or window, respectively. Examples: >
167					:lua l = vim.list()
168					:lua print(type(l), vim.type(l))
169					:" userdata list
170<
171	vim.command({cmd})	Executes the vim (ex-mode) command {cmd}.
172				Examples: >
173					:lua vim.command"set tw=60"
174					:lua vim.command"normal ddp"
175<
176	vim.eval({expr})	Evaluates expression {expr} (see |expression|),
177				converts the result to Lua, and returns it.
178				Vim strings and numbers are directly converted
179				to Lua strings and numbers respectively. Vim
180				lists and dictionaries are converted to Lua
181				userdata (see |lua-list| and |lua-dict|).
182				Examples: >
183					:lua tw = vim.eval"&tw"
184					:lua print(vim.eval"{'a': 'one'}".a)
185<
186	vim.line()		Returns the current line (without the trailing
187				<EOL>), a Lua string.
188
189	vim.beep()		Beeps.
190
191	vim.open({fname})	Opens a new buffer for file {fname} and
192				returns it. Note that the buffer is not set as
193				current.
194
195
196==============================================================================
1973. List userdata					*lua-list*
198
199List userdata represent vim lists, and the interface tries to follow closely
200Vim's syntax for lists. Since lists are objects, changes in list references in
201Lua are reflected in Vim and vice-versa. A list "l" has the following
202properties and methods:
203
204Properties
205----------
206	o "#l" is the number of items in list "l", equivalent to "len(l)"
207	    in Vim.
208	o "l[k]" returns the k-th item in "l"; "l" is zero-indexed, as in Vim.
209	    To modify the k-th item, simply do "l[k] = newitem"; in
210	    particular, "l[k] = nil" removes the k-th item from "l".
211	o "l()" returns an iterator for "l".
212
213Methods
214-------
215	o "l:add(item)" appends "item" to the end of "l".
216	o "l:insert(item[, pos])" inserts "item" at (optional)
217	    position "pos" in the list. The default value for "pos" is 0.
218
219Examples:
220>
221	:let l = [1, 'item']
222	:lua l = vim.eval('l') -- same 'l'
223	:lua l:add(vim.list())
224	:lua l[0] = math.pi
225	:echo l[0] " 3.141593
226	:lua l[0] = nil -- remove first item
227	:lua l:insert(true, 1)
228	:lua print(l, #l, l[0], l[1], l[-1])
229	:lua for item in l() do print(item) end
230<
231
232==============================================================================
2334. Dict userdata					*lua-dict*
234
235Similarly to list userdata, dict userdata represent vim dictionaries; since
236dictionaries are also objects, references are kept between Lua and Vim. A dict
237"d" has the following properties:
238
239Properties
240----------
241	o "#d" is the number of items in dict "d", equivalent to "len(d)"
242	    in Vim.
243	o "d.key" or "d['key']" returns the value at entry "key" in "d".
244	    To modify the entry at this key, simply do "d.key = newvalue"; in
245	    particular, "d.key = nil" removes the entry from "d".
246	o "d()" returns an iterator for "d" and is equivalent to "items(d)" in
247	    Vim.
248
249Examples:
250>
251	:let d = {'n':10}
252	:lua d = vim.eval('d') -- same 'd'
253	:lua print(d, d.n, #d)
254	:let d.self = d
255	:lua for k, v in d() do print(d, k, v) end
256	:lua d.x = math.pi
257	:lua d.self = nil -- remove entry
258	:echo d
259<
260
261==============================================================================
2625. Funcref userdata					*lua-funcref*
263
264Funcref userdata represent funcref variables in Vim. Funcrefs that were
265defined with a "dict" attribute need to be obtained as a dictionary key
266in order to have "self" properly assigned to the dictionary (see examples
267below.) A funcref "f" has the following properties:
268
269Properties
270----------
271	o "#f" is the name of the function referenced by "f"
272	o "f(...)" calls the function referenced by "f" (with arguments)
273
274Examples:
275>
276	:function I(x)
277	:  return a:x
278	:  endfunction
279	:let R = function('I')
280	:lua i1 = vim.funcref('I')
281	:lua i2 = vim.eval('R')
282	:lua print(#i1, #i2) -- both 'I'
283	:lua print(i1, i2, #i2(i1) == #i1(i2))
284	:function Mylen() dict
285	:  return len(self.data)
286	:  endfunction
287	:let mydict = {'data': [0, 1, 2, 3]}
288	:lua d = vim.eval('mydict'); d.len = vim.funcref('Mylen')
289	:echo mydict.len()
290	:lua l = d.len -- assign d as 'self'
291	:lua print(l())
292<
293
294==============================================================================
2956. Buffer userdata					*lua-buffer*
296
297Buffer userdata represent vim buffers. A buffer userdata "b" has the following
298properties and methods:
299
300Properties
301----------
302	o "b()" sets "b" as the current buffer.
303	o "#b" is the number of lines in buffer "b".
304	o "b[k]" represents line number k: "b[k] = newline" replaces line k
305	    with string "newline" and "b[k] = nil" deletes line k.
306	o "b.name" contains the short name of buffer "b" (read-only).
307	o "b.fname" contains the full name of buffer "b" (read-only).
308	o "b.number" contains the position of buffer "b" in the buffer list
309	    (read-only).
310
311Methods
312-------
313	o "b:insert(newline[, pos])" inserts string "newline" at (optional)
314	    position "pos" in the buffer. The default value for "pos" is
315	    "#b + 1". If "pos == 0" then "newline" becomes the first line in
316	    the buffer.
317	o "b:next()" returns the buffer next to "b" in the buffer list.
318	o "b:previous()" returns the buffer previous to "b" in the buffer
319	    list.
320	o "b:isvalid()" returns 'true' (boolean) if buffer "b" corresponds to
321	    a "real" (not freed from memory) Vim buffer.
322
323Examples:
324>
325	:lua b = vim.buffer() -- current buffer
326	:lua print(b.name, b.number)
327	:lua b[1] = "first line"
328	:lua b:insert("FIRST!", 0)
329	:lua b[1] = nil -- delete top line
330	:lua for i=1,3 do b:insert(math.random()) end
331	:3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end
332	:lua vim.open"myfile"() -- open buffer and set it as current
333
334	function! ListBuffers()
335	lua << EOF
336	local b = vim.buffer(true) -- first buffer in list
337	while b ~= nil do
338		print(b.number, b.name, #b)
339		b = b:next()
340	end
341	vim.beep()
342	EOF
343	endfunction
344<
345
346==============================================================================
3477. Window userdata					*lua-window*
348
349Window objects represent vim windows. A window userdata "w" has the following
350properties and methods:
351
352Properties
353----------
354	o "w()" sets "w" as the current window.
355	o "w.buffer" contains the buffer of window "w" (read-only).
356	o "w.line" represents the cursor line position in window "w".
357	o "w.col" represents the cursor column position in window "w".
358	o "w.width" represents the width of window "w".
359	o "w.height" represents the height of window "w".
360
361Methods
362-------
363	o "w:next()" returns the window next to "w".
364	o "w:previous()" returns the window previous to "w".
365	o "w:isvalid()" returns 'true' (boolean) if window "w" corresponds to
366	    a "real" (not freed from memory) Vim window.
367
368Examples:
369>
370	:lua w = vim.window() -- current window
371	:lua print(w.buffer.name, w.line, w.col)
372	:lua w.width = w.width + math.random(10)
373	:lua w.height = 2 * math.random() * w.height
374	:lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end
375	:lua print("There are " .. n .. " windows")
376<
377
378==============================================================================
3798. The luaeval function					*lua-luaeval* *lua-eval*
380
381The (dual) equivalent of "vim.eval" for passing Lua values to Vim is
382"luaeval". "luaeval" takes an expression string and an optional argument and
383returns the result of the expression. It is semantically equivalent in Lua to:
384>
385	local chunkheader = "local _A = select(1, ...) return "
386	function luaeval (expstr, arg)
387	    local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
388	    return chunk(arg) -- return typval
389	end
390<
391Note that "_A" receives the argument to "luaeval". Lua numbers, strings, and
392list, dict, and funcref userdata are converted to their Vim respective types,
393while Lua booleans are converted to numbers. An error is thrown if conversion
394of any of the remaining Lua types, including userdata other than lists, dicts,
395and funcrefs, is attempted.
396
397Examples: >
398
399	:echo luaeval('math.pi')
400	:lua a = vim.list():add('newlist')
401	:let a = luaeval('a')
402	:echo a[0] " 'newlist'
403	:function Rand(x,y) " random uniform between x and y
404	:  return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
405	:  endfunction
406	:echo Rand(1,10)
407
408
409==============================================================================
4109. Dynamic loading				    *lua-dynamic*
411
412On MS-Windows and Unix the Lua library can be loaded dynamically.  The
413|:version| output then includes |+lua/dyn|.
414
415This means that Vim will search for the Lua DLL or shared library file only
416when needed.  When you don't use the Lua interface you don't need it, thus
417you can use Vim without this file.
418
419
420MS-Windows ~
421
422To use the Lua interface the Lua DLL must be in your search path.  In a
423console window type "path" to see what directories are used.  The 'luadll'
424option can be also used to specify the Lua DLL.  The version of the DLL must
425match the Lua version Vim was compiled with.
426
427
428Unix ~
429
430The 'luadll' option can be used to specify the Lua shared library file instead
431of DYNAMIC_LUA_DLL file what was specified at compile time.  The version of
432the shared library must match the Lua version Vim was compiled with.
433
434
435==============================================================================
436 vim:tw=78:ts=8:noet:ft=help:norl:
437