if_lua.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. *if_lua.txt* For Vim version 9.0. Last change: 2021 Aug 06
  2. VIM REFERENCE MANUAL by Luis Carvalho
  3. The Lua Interface to Vim *lua* *Lua*
  4. 1. Commands |lua-commands|
  5. 2. The vim module |lua-vim|
  6. 3. List userdata |lua-list|
  7. 4. Dict userdata |lua-dict|
  8. 5. Blob userdata |lua-blob|
  9. 6. Funcref userdata |lua-funcref|
  10. 7. Buffer userdata |lua-buffer|
  11. 8. Window userdata |lua-window|
  12. 9. luaeval() Vim function |lua-luaeval|
  13. 10. Dynamic loading |lua-dynamic|
  14. {only available when Vim was compiled with the |+lua| feature}
  15. ==============================================================================
  16. 1. Commands *lua-commands*
  17. *:lua*
  18. :[range]lua {chunk}
  19. Execute Lua chunk {chunk}.
  20. Examples:
  21. >
  22. :lua print("Hello, Vim!")
  23. :lua local curbuf = vim.buffer() curbuf[7] = "line #7"
  24. <
  25. :[range]lua << [trim] [{endmarker}]
  26. {script}
  27. {endmarker}
  28. Execute Lua script {script}.
  29. Note: This command doesn't work when the Lua
  30. feature wasn't compiled in. To avoid errors, see
  31. |script-here|.
  32. If [endmarker] is omitted from after the "<<", a dot '.' must be used after
  33. {script}, like for the |:append| and |:insert| commands. Refer to
  34. |:let-heredoc| for more information.
  35. This form of the |:lua| command is mainly useful for including Lua code
  36. in Vim scripts.
  37. Example:
  38. >
  39. function! CurrentLineInfo()
  40. lua << EOF
  41. local linenr = vim.window().line
  42. local curline = vim.buffer()[linenr]
  43. print(string.format("Current line [%d] has %d chars",
  44. linenr, #curline))
  45. EOF
  46. endfunction
  47. <
  48. To see what version of Lua you have: >
  49. :lua print(_VERSION)
  50. If you use LuaJIT you can also use this: >
  51. :lua print(jit.version)
  52. <
  53. *:luado*
  54. :[range]luado {body} Execute Lua function "function (line, linenr) {body}
  55. end" for each line in the [range], with the function
  56. argument being set to the text of each line in turn,
  57. without a trailing <EOL>, and the current line number.
  58. If the value returned by the function is a string it
  59. becomes the text of the line in the current turn. The
  60. default for [range] is the whole file: "1,$".
  61. Examples:
  62. >
  63. :luado return string.format("%s\t%d", line:reverse(), #line)
  64. :lua require"lpeg"
  65. :lua -- balanced parenthesis grammar:
  66. :lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
  67. :luado if bp:match(line) then return "-->\t" .. line end
  68. <
  69. *:luafile*
  70. :[range]luafile {file}
  71. Execute Lua script in {file}.
  72. The whole argument is used as a single file name.
  73. Examples:
  74. >
  75. :luafile script.lua
  76. :luafile %
  77. <
  78. All these commands execute a Lua chunk from either the command line (:lua and
  79. :luado) or a file (:luafile) with the given line [range]. Similarly to the Lua
  80. interpreter, each chunk has its own scope and so only global variables are
  81. shared between command calls. All Lua default libraries are available. In
  82. addition, Lua "print" function has its output redirected to the Vim message
  83. area, with arguments separated by a white space instead of a tab.
  84. Lua uses the "vim" module (see |lua-vim|) to issue commands to Vim
  85. and manage buffers (|lua-buffer|) and windows (|lua-window|). However,
  86. procedures that alter buffer content, open new buffers, and change cursor
  87. position are restricted when the command is executed in the |sandbox|.
  88. ==============================================================================
  89. 2. The vim module *lua-vim*
  90. Lua interfaces Vim through the "vim" module. The first and last line of the
  91. input range are stored in "vim.firstline" and "vim.lastline" respectively. The
  92. module also includes routines for buffer, window, and current line queries,
  93. Vim evaluation and command execution, and others.
  94. vim.list([arg]) Returns an empty list or, if "arg" is a Lua
  95. table with numeric keys 1, ..., n (a
  96. "sequence"), returns a list l such that l[i] =
  97. arg[i] for i = 1, ..., n (see |List|).
  98. Non-numeric keys are not used to initialize
  99. the list. See also |lua-eval| for conversion
  100. rules. Example: >
  101. :lua t = {math.pi, false, say = 'hi'}
  102. :echo luaeval('vim.list(t)')
  103. :" [3.141593, v:false], 'say' is ignored
  104. <
  105. vim.dict([arg]) Returns an empty dictionary or, if "arg" is a
  106. Lua table, returns a dict d such that d[k] =
  107. arg[k] for all string keys k in "arg" (see
  108. |Dictionary|). Number keys are converted to
  109. strings. Keys that are not strings are not
  110. used to initialize the dictionary. See also
  111. |lua-eval| for conversion rules. Example: >
  112. :lua t = {math.pi, false, say = 'hi'}
  113. :echo luaeval('vim.dict(t)')
  114. :" {'1': 3.141593, '2': v:false,
  115. :" 'say': 'hi'}
  116. <
  117. vim.blob([arg]) Returns an empty blob or, if "arg" is a Lua
  118. string, returns a blob b such that b is
  119. equivalent to "arg" as a byte string.
  120. Examples: >
  121. :lua s = "12ab\x00\x80\xfe\xff"
  122. :echo luaeval('vim.blob(s)')
  123. :" 0z31326162.0080FEFF
  124. <
  125. vim.funcref({name}) Returns a Funcref to function {name} (see
  126. |Funcref|). It is equivalent to Vim's
  127. function().
  128. vim.buffer([arg]) If "arg" is a number, returns buffer with
  129. number "arg" in the buffer list or, if "arg"
  130. is a string, returns buffer whose full or short
  131. name is "arg". In both cases, returns 'nil'
  132. (nil value, not string) if the buffer is not
  133. found. Otherwise, if "toboolean(arg)" is
  134. 'true' returns the first buffer in the buffer
  135. list or else the current buffer.
  136. vim.window([arg]) If "arg" is a number, returns window with
  137. number "arg" or 'nil' (nil value, not string)
  138. if not found. Otherwise, if "toboolean(arg)"
  139. is 'true' returns the first window or else the
  140. current window.
  141. vim.type({arg}) Returns the type of {arg}. It is equivalent to
  142. Lua's "type" function, but returns "list",
  143. "dict", "funcref", "buffer", or "window" if
  144. {arg} is a list, dictionary, funcref, buffer,
  145. or window, respectively. Examples: >
  146. :lua l = vim.list()
  147. :lua print(type(l), vim.type(l))
  148. :" list
  149. <
  150. vim.command({cmds}) Executes one or more lines of Ex-mode commands
  151. in {cmds}.
  152. Examples: >
  153. :lua vim.command"set tw=60"
  154. :lua vim.command"normal ddp"
  155. lua << trim END
  156. vim.command([[
  157. new Myfile.js
  158. call search('start')
  159. ]])
  160. END
  161. <
  162. vim.eval({expr}) Evaluates expression {expr} (see |expression|),
  163. converts the result to Lua, and returns it.
  164. Vim strings and numbers are directly converted
  165. to Lua strings and numbers respectively. Vim
  166. lists and dictionaries are converted to Lua
  167. userdata (see |lua-list| and |lua-dict|).
  168. Examples: >
  169. :lua tw = vim.eval"&tw"
  170. :lua print(vim.eval"{'a': 'one'}".a)
  171. <
  172. vim.line() Returns the current line (without the trailing
  173. <EOL>), a Lua string.
  174. vim.beep() Beeps.
  175. vim.open({fname}) Opens a new buffer for file {fname} and
  176. returns it. Note that the buffer is not set as
  177. current.
  178. vim.call({name} [, {args}])
  179. Proxy to call Vim function named {name} with
  180. arguments {args}. Example: >
  181. :lua print(vim.call('has', 'timers'))
  182. <
  183. vim.fn Proxy to call Vim functions. Proxy methods are
  184. created on demand. Example: >
  185. :lua print(vim.fn.has('timers'))
  186. <
  187. vim.lua_version The Lua version Vim was compiled with, in the
  188. form {major}.{minor}.{patch}, e.g. "5.1.4".
  189. vim.version() Returns a Lua table with the Vim version.
  190. The table will have the following keys:
  191. major - major Vim version.
  192. minor - minor Vim version.
  193. patch - latest patch included.
  194. *lua-vim-variables*
  195. The Vim editor global dictionaries |g:| |w:| |b:| |t:| |v:| can be accessed
  196. from Lua conveniently and idiomatically by referencing the `vim.*` Lua tables
  197. described below. In this way you can easily read and modify global Vim script
  198. variables from Lua.
  199. Example: >
  200. vim.g.foo = 5 -- Set the g:foo Vim script variable.
  201. print(vim.g.foo) -- Get and print the g:foo Vim script variable.
  202. vim.g.foo = nil -- Delete (:unlet) the Vim script variable.
  203. vim.g *vim.g*
  204. Global (|g:|) editor variables.
  205. Key with no value returns `nil`.
  206. vim.b *vim.b*
  207. Buffer-scoped (|b:|) variables for the current buffer.
  208. Invalid or unset key returns `nil`.
  209. vim.w *vim.w*
  210. Window-scoped (|w:|) variables for the current window.
  211. Invalid or unset key returns `nil`.
  212. vim.t *vim.t*
  213. Tabpage-scoped (|t:|) variables for the current tabpage.
  214. Invalid or unset key returns `nil`.
  215. vim.v *vim.v*
  216. |v:| variables.
  217. Invalid or unset key returns `nil`.
  218. ==============================================================================
  219. 3. List userdata *lua-list*
  220. List userdata represent vim lists, and the interface tries to follow closely
  221. Vim's syntax for lists. Since lists are objects, changes in list references in
  222. Lua are reflected in Vim and vice-versa. A list "l" has the following
  223. properties and methods:
  224. NOTE: In patch 8.2.1066 array indexes were changed from zero-based to
  225. one-based. You can check with: >
  226. if has("patch-8.2.1066")
  227. Properties
  228. ----------
  229. o "#l" is the number of items in list "l", equivalent to "len(l)"
  230. in Vim.
  231. o "l[k]" returns the k-th item in "l"; "l" is one-indexed, as in Lua.
  232. To modify the k-th item, simply do "l[k] = newitem"; in
  233. particular, "l[k] = nil" removes the k-th item from "l". Item can
  234. be added to the end of the list by "l[#l + 1] = newitem"
  235. o "l()" returns an iterator for "l".
  236. o "table.insert(l, newitem)" inserts an item at the end of the list.
  237. (only Lua 5.3 and later)
  238. o "table.insert(l, position, newitem)" inserts an item at the
  239. specified position. "position" is one-indexed. (only Lua 5.3 and
  240. later)
  241. o "table.remove(l, position)" removes an item at the specified
  242. position. "position" is one-indexed.
  243. Methods
  244. -------
  245. o "l:add(item)" appends "item" to the end of "l".
  246. o "l:insert(item[, pos])" inserts "item" at (optional)
  247. position "pos" in the list. The default value for "pos" is 0.
  248. Examples:
  249. >
  250. :let l = [1, 'item']
  251. :lua l = vim.eval('l') -- same 'l'
  252. :lua l:add(vim.list())
  253. :lua l[1] = math.pi
  254. :echo l[0] " 3.141593
  255. :lua l[1] = nil -- remove first item
  256. :lua l:insert(true, 1)
  257. :lua print(l, #l, l[1], l[2])
  258. :lua l[#l + 1] = 'value'
  259. :lua table.insert(l, 100)
  260. :lua table.insert(l, 2, 200)
  261. :lua table.remove(l, 1)
  262. :lua for item in l() do print(item) end
  263. ==============================================================================
  264. 4. Dict userdata *lua-dict*
  265. Similarly to list userdata, dict userdata represent vim dictionaries; since
  266. dictionaries are also objects, references are kept between Lua and Vim. A dict
  267. "d" has the following properties:
  268. Properties
  269. ----------
  270. o "#d" is the number of items in dict "d", equivalent to "len(d)"
  271. in Vim.
  272. o "d.key" or "d['key']" returns the value at entry "key" in "d".
  273. To modify the entry at this key, simply do "d.key = newvalue"; in
  274. particular, "d.key = nil" removes the entry from "d".
  275. o "d()" returns an iterator for "d" and is equivalent to "items(d)" in
  276. Vim.
  277. Examples:
  278. >
  279. :let d = {'n':10}
  280. :lua d = vim.eval('d') -- same 'd'
  281. :lua print(d, d.n, #d)
  282. :let d.self = d
  283. :lua for k, v in d() do print(d, k, v) end
  284. :lua d.x = math.pi
  285. :lua d.self = nil -- remove entry
  286. :echo d
  287. <
  288. ==============================================================================
  289. 5. Blob userdata *lua-blob*
  290. Blob userdata represent vim blobs. A blob "b" has the following properties:
  291. Properties
  292. ----------
  293. o "#b" is the length of blob "b", equivalent to "len(b)" in Vim.
  294. o "b[k]" returns the k-th item in "b"; "b" is zero-indexed, as in Vim.
  295. To modify the k-th item, simply do "b[k] = number"; in particular,
  296. "b[#b] = number" can append a byte to tail.
  297. Methods
  298. -------
  299. o "b:add(bytes)" appends "bytes" to the end of "b".
  300. Examples:
  301. >
  302. :let b = 0z001122
  303. :lua b = vim.eval('b') -- same 'b'
  304. :lua print(b, b[0], #b)
  305. :lua b[1] = 32
  306. :lua b[#b] = 0x33 -- append a byte to tail
  307. :lua b:add("\x80\x81\xfe\xff")
  308. :echo b
  309. <
  310. ==============================================================================
  311. 6. Funcref userdata *lua-funcref*
  312. Funcref userdata represent funcref variables in Vim. Funcrefs that were
  313. defined with a "dict" attribute need to be obtained as a dictionary key
  314. in order to have "self" properly assigned to the dictionary (see examples
  315. below.) A funcref "f" has the following properties:
  316. Properties
  317. ----------
  318. o "#f" is the name of the function referenced by "f"
  319. o "f(...)" calls the function referenced by "f" (with arguments)
  320. Examples:
  321. >
  322. :function I(x)
  323. : return a:x
  324. : endfunction
  325. :let R = function('I')
  326. :lua i1 = vim.funcref('I')
  327. :lua i2 = vim.eval('R')
  328. :lua print(#i1, #i2) -- both 'I'
  329. :lua print(i1, i2, #i2(i1) == #i1(i2))
  330. :function Mylen() dict
  331. : return len(self.data)
  332. : endfunction
  333. :let mydict = {'data': [0, 1, 2, 3]}
  334. :lua d = vim.eval('mydict'); d.len = vim.funcref('Mylen')
  335. :echo mydict.len()
  336. :lua l = d.len -- assign d as 'self'
  337. :lua print(l())
  338. <
  339. Lua functions and closures are automatically converted to a Vim |Funcref| and
  340. can be accessed in Vim scripts. Example:
  341. >
  342. lua <<EOF
  343. vim.fn.timer_start(1000, function(timer)
  344. print('timer callback')
  345. end)
  346. EOF
  347. ==============================================================================
  348. 7. Buffer userdata *lua-buffer*
  349. Buffer userdata represent vim buffers. A buffer userdata "b" has the following
  350. properties and methods:
  351. Properties
  352. ----------
  353. o "b()" sets "b" as the current buffer.
  354. o "#b" is the number of lines in buffer "b".
  355. o "b[k]" represents line number k: "b[k] = newline" replaces line k
  356. with string "newline" and "b[k] = nil" deletes line k.
  357. o "b.name" contains the short name of buffer "b" (read-only).
  358. o "b.fname" contains the full name of buffer "b" (read-only).
  359. o "b.number" contains the position of buffer "b" in the buffer list
  360. (read-only).
  361. Methods
  362. -------
  363. o "b:insert(newline[, pos])" inserts string "newline" at (optional)
  364. position "pos" in the buffer. The default value for "pos" is
  365. "#b + 1". If "pos == 0" then "newline" becomes the first line in
  366. the buffer.
  367. o "b:next()" returns the buffer next to "b" in the buffer list.
  368. o "b:previous()" returns the buffer previous to "b" in the buffer
  369. list.
  370. o "b:isvalid()" returns 'true' (boolean) if buffer "b" corresponds to
  371. a "real" (not freed from memory) Vim buffer.
  372. Examples:
  373. >
  374. :lua b = vim.buffer() -- current buffer
  375. :lua print(b.name, b.number)
  376. :lua b[1] = "first line"
  377. :lua b:insert("FIRST!", 0)
  378. :lua b[1] = nil -- delete top line
  379. :lua for i=1,3 do b:insert(math.random()) end
  380. :3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end
  381. :lua vim.open"myfile"() -- open buffer and set it as current
  382. function! ListBuffers()
  383. lua << EOF
  384. local b = vim.buffer(true) -- first buffer in list
  385. while b ~= nil do
  386. print(b.number, b.name, #b)
  387. b = b:next()
  388. end
  389. vim.beep()
  390. EOF
  391. endfunction
  392. <
  393. ==============================================================================
  394. 8. Window userdata *lua-window*
  395. Window objects represent vim windows. A window userdata "w" has the following
  396. properties and methods:
  397. Properties
  398. ----------
  399. o "w()" sets "w" as the current window.
  400. o "w.buffer" contains the buffer of window "w" (read-only).
  401. o "w.line" represents the cursor line position in window "w".
  402. o "w.col" represents the cursor column position in window "w".
  403. o "w.width" represents the width of window "w".
  404. o "w.height" represents the height of window "w".
  405. Methods
  406. -------
  407. o "w:next()" returns the window next to "w".
  408. o "w:previous()" returns the window previous to "w".
  409. o "w:isvalid()" returns 'true' (boolean) if window "w" corresponds to
  410. a "real" (not freed from memory) Vim window.
  411. Examples:
  412. >
  413. :lua w = vim.window() -- current window
  414. :lua print(w.buffer.name, w.line, w.col)
  415. :lua w.width = w.width + math.random(10)
  416. :lua w.height = 2 * math.random() * w.height
  417. :lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end
  418. :lua print("There are " .. n .. " windows")
  419. <
  420. ==============================================================================
  421. 9. luaeval() Vim function *lua-luaeval* *lua-eval*
  422. The (dual) equivalent of "vim.eval" for passing Lua values to Vim is
  423. "luaeval". "luaeval" takes an expression string and an optional argument and
  424. returns the result of the expression. It is semantically equivalent in Lua to:
  425. >
  426. local chunkheader = "local _A = select(1, ...) return "
  427. function luaeval (expstr, arg)
  428. local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
  429. return chunk(arg) -- return typval
  430. end
  431. <
  432. Note that "_A" receives the argument to "luaeval". Lua numbers, strings, and
  433. list, dict, blob, and funcref userdata are converted to their Vim respective
  434. types, while Lua booleans are converted to numbers. An error is thrown if
  435. conversion of any of the remaining Lua types, including userdata other than
  436. lists, dicts, blobs, and funcrefs, is attempted.
  437. Examples: >
  438. :echo luaeval('math.pi')
  439. :lua a = vim.list():add('newlist')
  440. :let a = luaeval('a')
  441. :echo a[0] " 'newlist'
  442. :function Rand(x,y) " random uniform between x and y
  443. : return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
  444. : endfunction
  445. :echo Rand(1,10)
  446. ==============================================================================
  447. 10. Dynamic loading *lua-dynamic*
  448. On MS-Windows and Unix the Lua library can be loaded dynamically. The
  449. |:version| output then includes |+lua/dyn|.
  450. This means that Vim will search for the Lua DLL or shared library file only
  451. when needed. When you don't use the Lua interface you don't need it, thus
  452. you can use Vim without this file.
  453. MS-Windows ~
  454. To use the Lua interface the Lua DLL must be in your search path. In a
  455. console window type "path" to see what directories are used. The 'luadll'
  456. option can be also used to specify the Lua DLL. The version of the DLL must
  457. match the Lua version Vim was compiled with.
  458. Unix ~
  459. The 'luadll' option can be used to specify the Lua shared library file instead
  460. of DYNAMIC_LUA_DLL file what was specified at compile time. The version of
  461. the shared library must match the Lua version Vim was compiled with.
  462. ==============================================================================
  463. vim:tw=78:ts=8:noet:ft=help:norl: