blob: 2b322ddbae4f6180e5140c88624b501203933195 [file] [log] [blame]
Bram Moolenaar7cba6c02013-09-05 22:13:31 +02001*if_lua.txt* For Vim version 7.4. Last change: 2013 Sep 04
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 Moolenaar0ba04292010-07-14 23:23:17 +020017
18{Vi does not have any of these commands}
19
20The Lua interface is available only when Vim was compiled with the
21|+lua| feature.
22
23==============================================================================
241. Commands *lua-commands*
25
26 *:lua*
27:[range]lua {chunk}
28 Execute Lua chunk {chunk}. {not in Vi}
29
30Examples:
31>
32 :lua print("Hello, Vim!")
33 :lua local curbuf = vim.buffer() curbuf[7] = "line #7"
34<
35
36:[range]lua << {endmarker}
37{script}
38{endmarker}
39 Execute Lua script {script}. {not in Vi}
40 Note: This command doesn't work when the Lua
41 feature wasn't compiled in. To avoid errors, see
42 |script-here|.
43
44{endmarker} must NOT be preceded by any white space. If {endmarker} is
45omitted from after the "<<", a dot '.' must be used after {script}, like
46for the |:append| and |:insert| commands.
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<
61
62 *:luado*
Bram Moolenaar53bfca22012-04-13 23:04:47 +020063:[range]luado {body} Execute Lua function "function (line, linenr) {body}
64 end" for each line in the [range], with the function
65 argument being set to the text of each line in turn,
66 without a trailing <EOL>, and the current line number.
67 If the value returned by the function is a string it
68 becomes the text of the line in the current turn. The
69 default for [range] is the whole file: "1,$".
70 {not in Vi}
Bram Moolenaar0ba04292010-07-14 23:23:17 +020071
72Examples:
73>
74 :luado return string.format("%s\t%d", line:reverse(), #line)
75
76 :lua require"lpeg"
77 :lua -- balanced parenthesis grammar:
78 :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
79 :luado if bp:match(line) then return "-->\t" .. line end
80<
81
82 *:luafile*
83:[range]luafile {file}
84 Execute Lua script in {file}. {not in Vi}
85 The whole argument is used as a single file name.
86
87Examples:
88>
89 :luafile script.lua
90 :luafile %
91<
92
93All these commands execute a Lua chunk from either the command line (:lua and
94:luado) or a file (:luafile) with the given line [range]. Similarly to the Lua
95interpreter, each chunk has its own scope and so only global variables are
Bram Moolenaar1dced572012-04-05 16:54:08 +020096shared between command calls. All Lua default libraries are available. In
97addition, Lua "print" function has its output redirected to the Vim message
98area, with arguments separated by a white space instead of a tab.
Bram Moolenaar0ba04292010-07-14 23:23:17 +020099
Bram Moolenaar9855d6b2010-07-18 14:34:51 +0200100Lua uses the "vim" module (see |lua-vim|) to issue commands to Vim
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200101and manage buffers (|lua-buffer|) and windows (|lua-window|). However,
102procedures that alter buffer content, open new buffers, and change cursor
Bram Moolenaar9855d6b2010-07-18 14:34:51 +0200103position are restricted when the command is executed in the |sandbox|.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200104
105
106==============================================================================
1072. The vim module *lua-vim*
108
109Lua interfaces Vim through the "vim" module. The first and last line of the
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200110input range are stored in "vim.firstline" and "vim.lastline" respectively. The
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200111module also includes routines for buffer, window, and current line queries,
112Vim evaluation and command execution, and others.
113
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200114 vim.list([arg]) Returns an empty list or, if "arg" is a Lua
115 table with numeric keys 1, ..., n (a
116 "sequence"), returns a list l such that l[i] =
117 arg[i] for i = 1, ..., n (see |List|).
118 Non-numeric keys are not used to initialize
119 the list. See also |lua-eval| for conversion
120 rules. Example: >
121 :lua t = {math.pi, false, say = 'hi'}
122 :echo luaeval('vim.list(t)')
123 :" [3.141593, 0], 'say' is ignored
124<
125 vim.dict([arg]) Returns an empty dictionary or, if "arg" is a
126 Lua table, returns a dict d such that d[k] =
127 arg[k] for all string keys k in "arg" (see
128 |Dictionary|). Number keys are converted to
129 strings. Keys that are not strings are not
130 used to initialize the dictionary. See also
131 |lua-eval| for conversion rules. Example: >
132 :lua t = {math.pi, false, say = 'hi'}
133 :echo luaeval('vim.dict(t)')
134 :" {'say': 'hi'}, numeric keys ignored
135<
136 vim.funcref({name}) Returns a Funcref to function {name} (see
137 |Funcref|). It is equivalent to Vim's
Bram Moolenaar7cba6c02013-09-05 22:13:31 +0200138 "function". NOT IMPLEMENTED YET
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200139
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200140 vim.buffer([arg]) If "arg" is a number, returns buffer with
141 number "arg" in the buffer list or, if "arg"
142 is a string, returns buffer whose full or short
143 name is "arg". In both cases, returns 'nil'
144 (nil value, not string) if the buffer is not
145 found. Otherwise, if "toboolean(arg)" is
146 'true' returns the first buffer in the buffer
147 list or else the current buffer.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200148
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200149 vim.window([arg]) If "arg" is a number, returns window with
150 number "arg" or 'nil' (nil value, not string)
151 if not found. Otherwise, if "toboolean(arg)"
152 is 'true' returns the first window or else the
153 current window.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200154
Bram Moolenaar1dced572012-04-05 16:54:08 +0200155 vim.type({arg}) Returns the type of {arg}. It is equivalent to
156 Lua's "type" function, but returns "list",
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200157 "dict", "funcref", "buffer", or "window" if
158 {arg} is a list, dictionary, funcref, buffer,
159 or window, respectively. Examples: >
Bram Moolenaar1dced572012-04-05 16:54:08 +0200160 :lua l = vim.list()
161 :lua print(type(l), vim.type(l))
162 :" userdata list
163<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200164 vim.command({cmd}) Executes the vim (ex-mode) command {cmd}.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200165 Examples: >
166 :lua vim.command"set tw=60"
167 :lua vim.command"normal ddp"
168<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200169 vim.eval({expr}) Evaluates expression {expr} (see |expression|),
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200170 converts the result to Lua, and returns it.
171 Vim strings and numbers are directly converted
172 to Lua strings and numbers respectively. Vim
173 lists and dictionaries are converted to Lua
Bram Moolenaar1dced572012-04-05 16:54:08 +0200174 userdata (see |lua-list| and |lua-dict|).
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200175 Examples: >
176 :lua tw = vim.eval"&tw"
177 :lua print(vim.eval"{'a': 'one'}".a)
178<
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200179 vim.line() Returns the current line (without the trailing
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200180 <EOL>), a Lua string.
181
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200182 vim.beep() Beeps.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200183
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200184 vim.open({fname}) Opens a new buffer for file {fname} and
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200185 returns it. Note that the buffer is not set as
186 current.
187
188
189==============================================================================
Bram Moolenaar1dced572012-04-05 16:54:08 +02001903. List userdata *lua-list*
191
192List userdata represent vim lists, and the interface tries to follow closely
193Vim's syntax for lists. Since lists are objects, changes in list references in
194Lua are reflected in Vim and vice-versa. A list "l" has the following
195properties and methods:
196
197Properties
198----------
199 o "#l" is the number of items in list "l", equivalent to "len(l)"
200 in Vim.
201 o "l[k]" returns the k-th item in "l"; "l" is zero-indexed, as in Vim.
202 To modify the k-th item, simply do "l[k] = newitem"; in
203 particular, "l[k] = nil" removes the k-th item from "l".
204 o "l()" returns an iterator for "l".
205
206Methods
207-------
208 o "l:add(item)" appends "item" to the end of "l".
209 o "l:insert(item[, pos])" inserts "item" at (optional)
210 position "pos" in the list. The default value for "pos" is 0.
211
212Examples:
213>
214 :let l = [1, 'item']
215 :lua l = vim.eval('l') -- same 'l'
216 :lua l:add(vim.list())
217 :lua l[0] = math.pi
218 :echo l[0] " 3.141593
219 :lua l[0] = nil -- remove first item
220 :lua l:insert(true, 1)
221 :lua print(l, #l, l[0], l[1], l[-1])
222 :lua for item in l() do print(item) end
223<
224
225==============================================================================
2264. Dict userdata *lua-dict*
227
228Similarly to list userdata, dict userdata represent vim dictionaries; since
229dictionaries are also objects, references are kept between Lua and Vim. A dict
230"d" has the following properties:
231
232Properties
233----------
234 o "#d" is the number of items in dict "d", equivalent to "len(d)"
235 in Vim.
236 o "d.key" or "d['key']" returns the value at entry "key" in "d".
237 To modify the entry at this key, simply do "d.key = newvalue"; in
238 particular, "d.key = nil" removes the entry from "d".
239 o "d()" returns an iterator for "d" and is equivalent to "items(d)" in
240 Vim.
241
242Examples:
243>
244 :let d = {'n':10}
245 :lua d = vim.eval('d') -- same 'd'
246 :lua print(d, d.n, #d)
247 :let d.self = d
248 :lua for k, v in d() do print(d, k, v) end
249 :lua d.x = math.pi
250 :lua d.self = nil -- remove entry
251 :echo d
252<
253
254==============================================================================
Bram Moolenaar52b91d82013-06-15 21:39:51 +02002555. Funcref userdata *lua-funcref*
256
257Funcref userdata represent funcref variables in Vim. Funcrefs that were
258defined with a "dict" attribute need to be obtained as a dictionary key
259in order to have "self" properly assigned to the dictionary (see examples
260below.) A funcref "f" has the following properties:
261
262Properties
263----------
264 o "#f" is the name of the function referenced by "f"
265 o "f(...)" calls the function referenced by "f" (with arguments)
266
267Examples:
268>
269 :function I(x)
270 : return a:x
271 : endfunction
272 :let R = function('I')
273 :lua i1 = vim.funcref('I')
274 :lua i2 = vim.eval('R')
275 :lua print(#i1, #i2) -- both 'I'
276 :lua print(i1, i2, #i2(i1) == #i1(i2))
277 :function Mylen() dict
278 : return len(self.data)
279 : endfunction
280 :let mydict = {'data': [0, 1, 2, 3]}
281 :lua d = vim.eval('mydict'); d.len = vim.funcref('Mylen')
282 :echo mydict.len()
283 :lua l = d.len -- assign d as 'self'
284 :lua print(l())
285<
286
287==============================================================================
2886. Buffer userdata *lua-buffer*
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200289
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200290Buffer userdata represent vim buffers. A buffer userdata "b" has the following
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200291properties and methods:
292
293Properties
294----------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200295 o "b()" sets "b" as the current buffer.
296 o "#b" is the number of lines in buffer "b".
297 o "b[k]" represents line number k: "b[k] = newline" replaces line k
298 with string "newline" and "b[k] = nil" deletes line k.
299 o "b.name" contains the short name of buffer "b" (read-only).
300 o "b.fname" contains the full name of buffer "b" (read-only).
301 o "b.number" contains the position of buffer "b" in the buffer list
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200302 (read-only).
303
304Methods
305-------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200306 o "b:insert(newline[, pos])" inserts string "newline" at (optional)
307 position "pos" in the buffer. The default value for "pos" is
308 "#b + 1". If "pos == 0" then "newline" becomes the first line in
309 the buffer.
310 o "b:next()" returns the buffer next to "b" in the buffer list.
311 o "b:previous()" returns the buffer previous to "b" in the buffer
312 list.
313 o "b:isvalid()" returns 'true' (boolean) if buffer "b" corresponds to
314 a "real" (not freed from memory) Vim buffer.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200315
316Examples:
317>
318 :lua b = vim.buffer() -- current buffer
319 :lua print(b.name, b.number)
320 :lua b[1] = "first line"
321 :lua b:insert("FIRST!", 0)
322 :lua b[1] = nil -- delete top line
323 :lua for i=1,3 do b:insert(math.random()) end
324 :3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end
325 :lua vim.open"myfile"() -- open buffer and set it as current
326
327 function! ListBuffers()
328 lua << EOF
329 local b = vim.buffer(true) -- first buffer in list
330 while b ~= nil do
331 print(b.number, b.name, #b)
332 b = b:next()
333 end
334 vim.beep()
335 EOF
336 endfunction
337<
338
339==============================================================================
Bram Moolenaar52b91d82013-06-15 21:39:51 +02003407. Window userdata *lua-window*
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200341
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200342Window objects represent vim windows. A window userdata "w" has the following
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200343properties and methods:
344
345Properties
346----------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200347 o "w()" sets "w" as the current window.
348 o "w.buffer" contains the buffer of window "w" (read-only).
349 o "w.line" represents the cursor line position in window "w".
350 o "w.col" represents the cursor column position in window "w".
351 o "w.width" represents the width of window "w".
352 o "w.height" represents the height of window "w".
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200353
354Methods
355-------
Bram Moolenaar2334b6d2010-07-22 21:32:16 +0200356 o "w:next()" returns the window next to "w".
357 o "w:previous()" returns the window previous to "w".
358 o "w:isvalid()" returns 'true' (boolean) if window "w" corresponds to
359 a "real" (not freed from memory) Vim window.
Bram Moolenaar0ba04292010-07-14 23:23:17 +0200360
361Examples:
362>
363 :lua w = vim.window() -- current window
364 :lua print(w.buffer.name, w.line, w.col)
365 :lua w.width = w.width + math.random(10)
366 :lua w.height = 2 * math.random() * w.height
367 :lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end
368 :lua print("There are " .. n .. " windows")
369<
370
371==============================================================================
Bram Moolenaar52b91d82013-06-15 21:39:51 +02003728. The luaeval function *lua-luaeval* *lua-eval*
Bram Moolenaar1dced572012-04-05 16:54:08 +0200373
374The (dual) equivalent of "vim.eval" for passing Lua values to Vim is
375"luaeval". "luaeval" takes an expression string and an optional argument and
376returns the result of the expression. It is semantically equivalent in Lua to:
377>
378 local chunkheader = "local _A = select(1, ...) return "
379 function luaeval (expstr, arg)
380 local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
381 return chunk(arg) -- return typval
382 end
383<
Bram Moolenaar52b91d82013-06-15 21:39:51 +0200384Note that "_A" receives the argument to "luaeval". Lua numbers, strings, and
385list, dict, and funcref userdata are converted to their Vim respective types,
386while Lua booleans are converted to numbers. An error is thrown if conversion
387of any of the remaining Lua types, including userdata other than lists, dicts,
388and funcrefs, is attempted.
389
390Examples: >
Bram Moolenaar1dced572012-04-05 16:54:08 +0200391
392 :echo luaeval('math.pi')
393 :lua a = vim.list():add('newlist')
394 :let a = luaeval('a')
395 :echo a[0] " 'newlist'
396 :function Rand(x,y) " random uniform between x and y
397 : return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
398 : endfunction
399 :echo Rand(1,10)
400
401
402==============================================================================
403 vim:tw=78:ts=8:noet:ft=help:norl: