lua-guide.txt 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. *lua-guide.txt* Nvim
  2. NVIM REFERENCE MANUAL
  3. Guide to using Lua in Nvim
  4. Type |gO| to see the table of contents.
  5. ==============================================================================
  6. Introduction *lua-guide*
  7. This guide will go through the basics of using Lua in Nvim. It is not meant
  8. to be a comprehensive encyclopedia of all available features, nor will it
  9. detail all intricacies. Think of it as a survival kit -- the bare minimum
  10. needed to know to comfortably get started on using Lua in Nvim.
  11. An important thing to note is that this isn't a guide to the Lua language
  12. itself. Rather, this is a guide on how to configure and modify Nvim through
  13. the Lua language and the functions we provide to help with this. Take a look
  14. at |luaref| and |lua-concepts| if you'd like to learn more about Lua itself.
  15. Similarly, this guide assumes some familiarity with the basics of Nvim
  16. (commands, options, mappings, autocommands), which are covered in the
  17. |user-manual|.
  18. ------------------------------------------------------------------------------
  19. Some words on the API *lua-guide-api*
  20. The purpose of this guide is to introduce the different ways of interacting
  21. with Nvim through Lua (the "API"). This API consists of three different
  22. layers:
  23. 1. The "Vim API" inherited from Vim: |Ex-commands| and |builtin-functions| as
  24. well as |user-function|s in Vimscript. These are accessed through |vim.cmd()|
  25. and |vim.fn| respectively, which are discussed under |lua-guide-vimscript|
  26. below.
  27. 2. The "Nvim API" written in C for use in remote plugins and GUIs; see |api|.
  28. These functions are accessed through |vim.api|.
  29. 3. The "Lua API" written in and specifically for Lua. These are any other
  30. functions accessible through `vim.*` not mentioned already; see |lua-stdlib|.
  31. This distinction is important, as API functions inherit behavior from their
  32. original layer: For example, Nvim API functions always need all arguments to
  33. be specified even if Lua itself allows omitting arguments (which are then
  34. passed as `nil`); and Vim API functions can use 0-based indexing even if Lua
  35. arrays are 1-indexed by default.
  36. Through this, any possible interaction can be done through Lua without writing
  37. a complete new API from scratch. For this reason, functions are usually not
  38. duplicated between layers unless there is a significant benefit in
  39. functionality or performance (e.g., you can map Lua functions directly through
  40. |nvim_create_autocmd()| but not through |:autocmd|). In case there are multiple
  41. ways of achieving the same thing, this guide will only cover what is most
  42. convenient to use from Lua.
  43. ==============================================================================
  44. Using Lua *lua-guide-using-Lua*
  45. To run Lua code from the Nvim command line, use the |:lua| command:
  46. >vim
  47. :lua print("Hello!")
  48. <
  49. Note: each |:lua| command has its own scope and variables declared with the
  50. local keyword are not accessible outside of the command. This won't work:
  51. >vim
  52. :lua local foo = 1
  53. :lua print(foo)
  54. " prints "nil" instead of "1"
  55. <
  56. You can also use `:lua=`, which is equivalent to `:lua vim.print(...)`, to
  57. conveniently check the value of a variable or a table:
  58. >vim
  59. :lua =package
  60. <
  61. To run a Lua script in an external file, you can use the |:source| command
  62. exactly like for a Vimscript file:
  63. >vim
  64. :source ~/programs/baz/myluafile.lua
  65. <
  66. Finally, you can include Lua code in a Vimscript file by putting it inside a
  67. |:lua-heredoc| block:
  68. >vim
  69. lua << EOF
  70. local tbl = {1, 2, 3}
  71. for k, v in ipairs(tbl) do
  72. print(v)
  73. end
  74. EOF
  75. <
  76. ------------------------------------------------------------------------------
  77. Using Lua files on startup *lua-guide-config*
  78. Nvim supports using `init.vim` or `init.lua` as the configuration file, but
  79. not both at the same time. This should be placed in your |config| directory,
  80. which is typically `~/.config/nvim` for Linux, BSD, or macOS, and
  81. `~/AppData/Local/nvim/` for Windows. Note that you can use Lua in `init.vim`
  82. and Vimscript in `init.lua`, which will be covered below.
  83. If you'd like to run any other Lua script on |startup| automatically, then you
  84. can simply put it in `plugin/` in your |'runtimepath'|.
  85. ------------------------------------------------------------------------------
  86. Lua modules *lua-guide-modules*
  87. If you want to load Lua files on demand, you can place them in the `lua/`
  88. directory in your |'runtimepath'| and load them with `require`. (This is the
  89. Lua equivalent of Vimscript's |autoload| mechanism.)
  90. Let's assume you have the following directory structure:
  91. >
  92. ~/.config/nvim
  93. |-- after/
  94. |-- ftplugin/
  95. |-- lua/
  96. | |-- myluamodule.lua
  97. | |-- other_modules/
  98. | |-- anothermodule.lua
  99. | |-- init.lua
  100. |-- plugin/
  101. |-- syntax/
  102. |-- init.vim
  103. <
  104. Then the following Lua code will load `myluamodule.lua`:
  105. >lua
  106. require("myluamodule")
  107. <
  108. Note the absence of a `.lua` extension.
  109. Similarly, loading `other_modules/anothermodule.lua` is done via
  110. >lua
  111. require('other_modules/anothermodule')
  112. -- or
  113. require('other_modules.anothermodule')
  114. <
  115. Note how "submodules" are just subdirectories; the `.` is equivalent to the
  116. path separator `/` (even on Windows).
  117. A folder containing an |init.lua| file can be required directly, without
  118. having to specify the name of the file:
  119. >lua
  120. require('other_modules') -- loads other_modules/init.lua
  121. <
  122. Requiring a nonexistent module or a module which contains syntax errors aborts
  123. the currently executing script. `pcall()` may be used to catch such errors. The
  124. following example tries to load the `module_with_error` and only calls one of
  125. its functions if this succeeds and prints an error message otherwise:
  126. >lua
  127. local ok, mymod = pcall(require, 'module_with_error')
  128. if not ok then
  129. print("Module had an error")
  130. else
  131. mymod.function()
  132. end
  133. <
  134. In contrast to |:source|, |require()| not only searches through all `lua/` directories
  135. under |'runtimepath'|, it also caches the module on first use. Calling
  136. `require()` a second time will therefore _not_ execute the script again and
  137. instead return the cached file. To rerun the file, you need to remove it from
  138. the cache manually first:
  139. >lua
  140. package.loaded['myluamodule'] = nil
  141. require('myluamodule') -- read and execute the module again from disk
  142. <
  143. ------------------------------------------------------------------------------
  144. See also:
  145. • |lua-module-load|
  146. • |pcall()|
  147. ==============================================================================
  148. Using Vim commands and functions from Lua *lua-guide-vimscript*
  149. All Vim commands and functions are accessible from Lua.
  150. ------------------------------------------------------------------------------
  151. Vim commands *lua-guide-vim-commands*
  152. To run an arbitrary Vim command from Lua, pass it as a string to |vim.cmd()|:
  153. >lua
  154. vim.cmd("colorscheme habamax")
  155. <
  156. Note that special characters will need to be escaped with backslashes:
  157. >lua
  158. vim.cmd("%s/\\Vfoo/bar/g")
  159. <
  160. An alternative is to use a literal string (see |lua-literal|) delimited by
  161. double brackets `[[ ]]` as in
  162. >lua
  163. vim.cmd([[%s/\Vfoo/bar/g]])
  164. <
  165. Another benefit of using literal strings is that they can be multiple lines;
  166. this allows you to pass multiple commands to a single call of |vim.cmd()|:
  167. >lua
  168. vim.cmd([[
  169. highlight Error guibg=red
  170. highlight link Warning Error
  171. ]])
  172. <
  173. This is the converse of |:lua-heredoc| and allows you to include Vimscript
  174. code in your `init.lua`.
  175. If you want to build your Vim command programmatically, the following form can
  176. be useful (all these are equivalent to the corresponding line above):
  177. >lua
  178. vim.cmd.colorscheme("habamax")
  179. vim.cmd.highlight({ "Error", "guibg=red" })
  180. vim.cmd.highlight({ "link", "Warning", "Error" })
  181. <
  182. ------------------------------------------------------------------------------
  183. Vimscript functions *lua-guide-vim-functions*
  184. Use |vim.fn| to call Vimscript functions from Lua. Data types between Lua and
  185. Vimscript are automatically converted:
  186. >lua
  187. print(vim.fn.printf('Hello from %s', 'Lua'))
  188. local reversed_list = vim.fn.reverse({ 'a', 'b', 'c' })
  189. vim.print(reversed_list) -- { "c", "b", "a" }
  190. local function print_stdout(chan_id, data, name)
  191. print(data[1])
  192. end
  193. vim.fn.jobstart('ls', { on_stdout = print_stdout })
  194. <
  195. This works for both |builtin-functions| and |user-function|s.
  196. Note that hashes (`#`) are not valid characters for identifiers in Lua, so,
  197. e.g., |autoload| functions have to be called with this syntax:
  198. >lua
  199. vim.fn['my#autoload#function']()
  200. <
  201. ------------------------------------------------------------------------------
  202. See also:
  203. • |builtin-functions|: alphabetic list of all Vimscript functions
  204. • |function-list|: list of all Vimscript functions grouped by topic
  205. • |:runtime|: run all Lua scripts matching a pattern in |'runtimepath'|
  206. • |package.path|: list of all paths searched by `require()`
  207. ==============================================================================
  208. Variables *lua-guide-variables*
  209. Variables can be set and read using the following wrappers, which directly
  210. correspond to their |variable-scope|:
  211. • |vim.g|: global variables (|g:|)
  212. • |vim.b|: variables for the current buffer (|b:|)
  213. • |vim.w|: variables for the current window (|w:|)
  214. • |vim.t|: variables for the current tabpage (|t:|)
  215. • |vim.v|: predefined Vim variables (|v:|)
  216. • |vim.env|: environment variables defined in the editor session
  217. Data types are converted automatically. For example:
  218. >lua
  219. vim.g.some_global_variable = {
  220. key1 = "value",
  221. key2 = 300
  222. }
  223. vim.print(vim.g.some_global_variable)
  224. --> { key1 = "value", key2 = 300 }
  225. <
  226. You can target specific buffers (via number), windows (via |window-ID|), or
  227. tabpages by indexing the wrappers:
  228. >lua
  229. vim.b[2].myvar = 1 -- set myvar for buffer number 2
  230. vim.w[1005].myothervar = true -- set myothervar for window ID 1005
  231. <
  232. Some variable names may contain characters that cannot be used for identifiers
  233. in Lua. You can still manipulate these variables by using the syntax
  234. >lua
  235. vim.g['my#variable'] = 1
  236. <
  237. Note that you cannot directly change fields of array variables. This won't
  238. work:
  239. >lua
  240. vim.g.some_global_variable.key2 = 400
  241. vim.print(vim.g.some_global_variable)
  242. --> { key1 = "value", key2 = 300 }
  243. <
  244. Instead, you need to create an intermediate Lua table and change this:
  245. >lua
  246. local temp_table = vim.g.some_global_variable
  247. temp_table.key2 = 400
  248. vim.g.some_global_variable = temp_table
  249. vim.print(vim.g.some_global_variable)
  250. --> { key1 = "value", key2 = 400 }
  251. <
  252. To delete a variable, simply set it to `nil`:
  253. >lua
  254. vim.g.myvar = nil
  255. <
  256. ------------------------------------------------------------------------------
  257. See also:
  258. • |lua-vim-variables|
  259. ==============================================================================
  260. Options *lua-guide-options*
  261. There are two complementary ways of setting |options| via Lua.
  262. ------------------------------------------------------------------------------
  263. vim.opt
  264. The most convenient way for setting global and local options, e.g., in `init.lua`,
  265. is through `vim.opt` and friends:
  266. • |vim.opt|: behaves like |:set|
  267. • |vim.opt_global|: behaves like |:setglobal|
  268. • |vim.opt_local|: behaves like |:setlocal|
  269. For example, the Vimscript commands
  270. >vim
  271. set smarttab
  272. set nosmarttab
  273. <
  274. are equivalent to
  275. >lua
  276. vim.opt.smarttab = true
  277. vim.opt.smarttab = false
  278. <
  279. In particular, they allow an easy way to working with list-like, map-like, and
  280. set-like options through Lua tables: Instead of
  281. >vim
  282. set wildignore=*.o,*.a,__pycache__
  283. set listchars=space:_,tab:>~
  284. set formatoptions=njt
  285. <
  286. you can use
  287. >lua
  288. vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
  289. vim.opt.listchars = { space = '_', tab = '>~' }
  290. vim.opt.formatoptions = { n = true, j = true, t = true }
  291. <
  292. These wrappers also come with methods that work similarly to their |:set+=|,
  293. |:set^=| and |:set-=| counterparts in Vimscript:
  294. >lua
  295. vim.opt.shortmess:append({ I = true })
  296. vim.opt.wildignore:prepend('*.o')
  297. vim.opt.whichwrap:remove({ 'b', 's' })
  298. <
  299. The price to pay is that you cannot access the option values directly but must
  300. use |vim.opt:get()|:
  301. >lua
  302. print(vim.opt.smarttab)
  303. --> {...} (big table)
  304. print(vim.opt.smarttab:get())
  305. --> false
  306. vim.print(vim.opt.listchars:get())
  307. --> { space = '_', tab = '>~' }
  308. <
  309. ------------------------------------------------------------------------------
  310. vim.o
  311. For this reason, there exists a more direct variable-like access using `vim.o`
  312. and friends, similarly to how you can get and set options via `:echo &number`
  313. and `:let &listchars='space:_,tab:>~'`:
  314. • |vim.o|: behaves like |:set|
  315. • |vim.go|: behaves like |:setglobal|
  316. • |vim.bo|: for buffer-scoped options
  317. • |vim.wo|: for window-scoped options (can be double indexed)
  318. For example:
  319. >lua
  320. vim.o.smarttab = false -- :set nosmarttab
  321. print(vim.o.smarttab)
  322. --> false
  323. vim.o.listchars = 'space:_,tab:>~' -- :set listchars='space:_,tab:>~'
  324. print(vim.o.listchars)
  325. --> 'space:_,tab:>~'
  326. vim.o.isfname = vim.o.isfname .. ',@-@' -- :set isfname+=@-@
  327. print(vim.o.isfname)
  328. --> '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@'
  329. vim.bo.shiftwidth = 4 -- :setlocal shiftwidth=4
  330. print(vim.bo.shiftwidth)
  331. --> 4
  332. <
  333. Just like variables, you can specify a buffer number or |window-ID| for buffer
  334. and window options, respectively. If no number is given, the current buffer or
  335. window is used:
  336. >lua
  337. vim.bo[4].expandtab = true -- sets expandtab to true in buffer 4
  338. vim.wo.number = true -- sets number to true in current window
  339. vim.wo[0].number = true -- same as above
  340. vim.wo[0][0].number = true -- sets number to true in current buffer
  341. -- in current window only
  342. print(vim.wo[0].number) --> true
  343. <
  344. ------------------------------------------------------------------------------
  345. See also:
  346. • |lua-options|
  347. ==============================================================================
  348. Mappings *lua-guide-mappings*
  349. You can map either Vim commands or Lua functions to key sequences.
  350. ------------------------------------------------------------------------------
  351. Creating mappings *lua-guide-mappings-set*
  352. Mappings can be created using |vim.keymap.set()|. This function takes three
  353. mandatory arguments:
  354. • {mode} is a string or a table of strings containing the mode
  355. prefix for which the mapping will take effect. The prefixes are the ones
  356. listed in |:map-modes|, or "!" for |:map!|, or empty string for |:map|.
  357. • {lhs} is a string with the key sequences that should trigger the mapping.
  358. • {rhs} is either a string with a Vim command or a Lua function that should
  359. be executed when the {lhs} is entered.
  360. An empty string is equivalent to |<Nop>|, which disables a key.
  361. Examples:
  362. >lua
  363. -- Normal mode mapping for Vim command
  364. vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>')
  365. -- Normal and Command-line mode mapping for Vim command
  366. vim.keymap.set({'n', 'c'}, '<Leader>ex2', '<cmd>echo "Example 2"<cr>')
  367. -- Normal mode mapping for Lua function
  368. vim.keymap.set('n', '<Leader>ex3', vim.treesitter.start)
  369. -- Normal mode mapping for Lua function with arguments
  370. vim.keymap.set('n', '<Leader>ex4', function() print('Example 4') end)
  371. <
  372. You can map functions from Lua modules via
  373. >lua
  374. vim.keymap.set('n', '<Leader>pl1', require('plugin').action)
  375. <
  376. Note that this loads the plugin at the time the mapping is defined. If you
  377. want to defer the loading to the time when the mapping is executed (as for
  378. |autoload| functions), wrap it in `function() end`:
  379. >lua
  380. vim.keymap.set('n', '<Leader>pl2', function() require('plugin').action() end)
  381. <
  382. The fourth, optional, argument is a table with keys that modify the behavior
  383. of the mapping such as those from |:map-arguments|. The following are the most
  384. useful options:
  385. • `buffer`: If given, only set the mapping for the buffer with the specified
  386. number; `0` or `true` means the current buffer. >lua
  387. -- set mapping for the current buffer
  388. vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = true })
  389. -- set mapping for the buffer number 4
  390. vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = 4 })
  391. <
  392. • `silent`: If set to `true`, suppress output such as error messages. >lua
  393. vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { silent = true })
  394. <
  395. • `expr`: If set to `true`, do not execute the {rhs} but use the return value
  396. as input. Special |keycodes| are converted automatically. For example, the following
  397. mapping replaces <down> with <c-n> in the popupmenu only: >lua
  398. vim.keymap.set('c', '<down>', function()
  399. if vim.fn.pumvisible() == 1 then return '<c-n>' end
  400. return '<down>'
  401. end, { expr = true })
  402. <
  403. • `desc`: A string that is shown when listing mappings with, e.g., |:map|.
  404. This is useful since Lua functions as {rhs} are otherwise only listed as
  405. `Lua: <number> <source file>:<line>`. Plugins should therefore always use this
  406. for mappings they create. >lua
  407. vim.keymap.set('n', '<Leader>pl1', require('plugin').action,
  408. { desc = 'Execute action from plugin' })
  409. <
  410. • `remap`: By default, all mappings are nonrecursive (i.e., |vim.keymap.set()|
  411. behaves like |:noremap|). If the {rhs} is itself a mapping that should be
  412. executed, set `remap = true`: >lua
  413. vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>')
  414. -- add a shorter mapping
  415. vim.keymap.set('n', 'e', '<Leader>ex1', { remap = true })
  416. <
  417. Note: |<Plug>| mappings are always expanded even with the default `remap = false`: >lua
  418. vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)')
  419. <
  420. ------------------------------------------------------------------------------
  421. Removing mappings *lua-guide-mappings-del*
  422. A specific mapping can be removed with |vim.keymap.del()|:
  423. >lua
  424. vim.keymap.del('n', '<Leader>ex1')
  425. vim.keymap.del({'n', 'c'}, '<Leader>ex2', {buffer = true})
  426. <
  427. ------------------------------------------------------------------------------
  428. See also:
  429. • `vim.api.`|nvim_get_keymap()|: return all global mapping
  430. • `vim.api.`|nvim_buf_get_keymap()|: return all mappings for buffer
  431. ==============================================================================
  432. Autocommands *lua-guide-autocommands*
  433. An |autocommand| is a Vim command or a Lua function that is automatically
  434. executed whenever one or more |events| are triggered, e.g., when a file is
  435. read or written, or when a window is created. These are accessible from Lua
  436. through the Nvim API.
  437. ------------------------------------------------------------------------------
  438. Creating autocommands *lua-guide-autocommand-create*
  439. Autocommands are created using `vim.api.`|nvim_create_autocmd()|, which takes
  440. two mandatory arguments:
  441. • {event}: a string or table of strings containing the event(s) which should
  442. trigger the command or function.
  443. • {opts}: a table with keys that control what should happen when the event(s)
  444. are triggered.
  445. The most important options are:
  446. • `pattern`: A string or table of strings containing the |autocmd-pattern|.
  447. Note: Environment variable like `$HOME` and `~` are not automatically
  448. expanded; you need to explicitly use `vim.fn.`|expand()| for this.
  449. • `command`: A string containing a Vim command.
  450. • `callback`: A Lua function.
  451. You must specify one and only one of `command` and `callback`. If `pattern` is
  452. omitted, it defaults to `pattern = '*'`.
  453. Examples:
  454. >lua
  455. vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
  456. pattern = {"*.c", "*.h"},
  457. command = "echo 'Entering a C or C++ file'",
  458. })
  459. -- Same autocommand written with a Lua function instead
  460. vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
  461. pattern = {"*.c", "*.h"},
  462. callback = function() print("Entering a C or C++ file") end,
  463. })
  464. -- User event triggered by MyPlugin
  465. vim.api.nvim_create_autocmd("User", {
  466. pattern = "MyPlugin",
  467. callback = function() print("My Plugin Works!") end,
  468. })
  469. <
  470. Nvim will always call a Lua function with a single table containing information
  471. about the triggered autocommand. The most useful keys are
  472. • `match`: a string that matched the `pattern` (see |<amatch>|)
  473. • `buf`: the number of the buffer the event was triggered in (see |<abuf>|)
  474. • `file`: the file name of the buffer the event was triggered in (see |<afile>|)
  475. • `data`: a table with other relevant data that is passed for some events
  476. For example, this allows you to set buffer-local mappings for some filetypes:
  477. >lua
  478. vim.api.nvim_create_autocmd("FileType", {
  479. pattern = "lua",
  480. callback = function(args)
  481. vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = args.buf })
  482. end
  483. })
  484. <
  485. This means that if your callback itself takes an (even optional) argument, you
  486. must wrap it in `function() end` to avoid an error:
  487. >lua
  488. vim.api.nvim_create_autocmd('TextYankPost', {
  489. callback = function() vim.hl.on_yank() end
  490. })
  491. <
  492. (Since unused arguments can be omitted in Lua function definitions, this is
  493. equivalent to `function(args) ... end`.)
  494. Instead of using a pattern, you can create a buffer-local autocommand (see
  495. |autocmd-buflocal|) with `buffer`; in this case, `pattern` cannot be used:
  496. >lua
  497. -- set autocommand for current buffer
  498. vim.api.nvim_create_autocmd("CursorHold", {
  499. buffer = 0,
  500. callback = function() print("hold") end,
  501. })
  502. -- set autocommand for buffer number 33
  503. vim.api.nvim_create_autocmd("CursorHold", {
  504. buffer = 33,
  505. callback = function() print("hold") end,
  506. })
  507. <
  508. Similarly to mappings, you can (and should) add a description using `desc`:
  509. >lua
  510. vim.api.nvim_create_autocmd('TextYankPost', {
  511. callback = function() vim.hl.on_yank() end,
  512. desc = "Briefly highlight yanked text"
  513. })
  514. <
  515. Finally, you can group autocommands using the `group` key; this will be
  516. covered in detail in the next section.
  517. ------------------------------------------------------------------------------
  518. Grouping autocommands *lua-guide-autocommands-group*
  519. Autocommand groups can be used to group related autocommands together; see
  520. |autocmd-groups|. This is useful for organizing autocommands and especially
  521. for preventing autocommands to be set multiple times.
  522. Groups can be created with `vim.api.`|nvim_create_augroup()|. This function
  523. takes two mandatory arguments: a string with the name of a group and a table
  524. determining whether the group should be cleared (i.e., all grouped
  525. autocommands removed) if it already exists. The function returns a number that
  526. is the internal identifier of the group. Groups can be specified either by
  527. this identifier or by the name (but only if the group has been created first).
  528. For example, a common Vimscript pattern for autocommands defined in files that
  529. may be reloaded is
  530. >vim
  531. augroup vimrc
  532. " Remove all vimrc autocommands
  533. autocmd!
  534. au BufNewFile,BufRead *.html set shiftwidth=4
  535. au BufNewFile,BufRead *.html set expandtab
  536. augroup END
  537. <
  538. This is equivalent to the following Lua code:
  539. >lua
  540. local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = true })
  541. vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, {
  542. pattern = '*.html',
  543. group = mygroup,
  544. command = 'set shiftwidth=4',
  545. })
  546. vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, {
  547. pattern = '*.html',
  548. group = 'vimrc', -- equivalent to group=mygroup
  549. command = 'set expandtab',
  550. })
  551. <
  552. Autocommand groups are unique for a given name, so you can reuse them, e.g.,
  553. in a different file:
  554. >lua
  555. local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = false })
  556. vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, {
  557. pattern = '*.c',
  558. group = mygroup,
  559. command = 'set noexpandtab',
  560. })
  561. <
  562. ------------------------------------------------------------------------------
  563. Deleting autocommands *lua-guide-autocommands-delete*
  564. You can use `vim.api.`|nvim_clear_autocmds()| to remove autocommands. This
  565. function takes a single mandatory argument that is a table of keys describing
  566. the autocommands that are to be removed:
  567. >lua
  568. -- Delete all BufEnter and InsertLeave autocommands
  569. vim.api.nvim_clear_autocmds({event = {"BufEnter", "InsertLeave"}})
  570. -- Delete all autocommands that uses "*.py" pattern
  571. vim.api.nvim_clear_autocmds({pattern = "*.py"})
  572. -- Delete all autocommands in group "scala"
  573. vim.api.nvim_clear_autocmds({group = "scala"})
  574. -- Delete all ColorScheme autocommands in current buffer
  575. vim.api.nvim_clear_autocmds({event = "ColorScheme", buffer = 0 })
  576. <
  577. Note: Autocommands in groups will only be removed if the `group` key is
  578. specified, even if another option matches it.
  579. ------------------------------------------------------------------------------
  580. See also
  581. • |nvim_get_autocmds()|: return all matching autocommands
  582. • |nvim_exec_autocmds()|: execute all matching autocommands
  583. ==============================================================================
  584. User commands *lua-guide-commands*
  585. |user-commands| are custom Vim commands that call a Vimscript or Lua function.
  586. Just like built-in commands, they can have arguments, act on ranges, or have
  587. custom completion of arguments. As these are most useful for plugins, we will
  588. cover only the basics of this advanced topic.
  589. ------------------------------------------------------------------------------
  590. Creating user commands *lua-guide-commands-create*
  591. User commands can be created via |nvim_create_user_command()|. This function
  592. takes three mandatory arguments:
  593. • a string that is the name of the command (which must start with an uppercase
  594. letter to distinguish it from builtin commands);
  595. • a string containing Vim commands or a Lua function that is executed when the
  596. command is invoked;
  597. • a table with |command-attributes|; in addition, it can contain the keys
  598. `desc` (a string describing the command); `force` (set to `false` to avoid
  599. replacing an already existing command with the same name), and `preview` (a
  600. Lua function that is used for |:command-preview|).
  601. Example:
  602. >lua
  603. vim.api.nvim_create_user_command('Test', 'echo "It works!"', {})
  604. vim.cmd.Test()
  605. --> It works!
  606. <
  607. (Note that the third argument is mandatory even if no attributes are given.)
  608. Lua functions are called with a single table argument containing arguments and
  609. modifiers. The most important are:
  610. • `name`: a string with the command name
  611. • `fargs`: a table containing the command arguments split by whitespace (see |<f-args>|)
  612. • `bang`: `true` if the command was executed with a `!` modifier (see |<bang>|)
  613. • `line1`: the starting line number of the command range (see |<line1>|)
  614. • `line2`: the final line number of the command range (see |<line2>|)
  615. • `range`: the number of items in the command range: 0, 1, or 2 (see |<range>|)
  616. • `count`: any count supplied (see |<count>|)
  617. • `smods`: a table containing the command modifiers (see |<mods>|)
  618. For example:
  619. >lua
  620. vim.api.nvim_create_user_command('Upper',
  621. function(opts)
  622. print(string.upper(opts.fargs[1]))
  623. end,
  624. { nargs = 1 })
  625. vim.cmd.Upper('foo')
  626. --> FOO
  627. <
  628. The `complete` attribute can take a Lua function in addition to the
  629. attributes listed in |:command-complete|. >lua
  630. vim.api.nvim_create_user_command('Upper',
  631. function(opts)
  632. print(string.upper(opts.fargs[1]))
  633. end,
  634. { nargs = 1,
  635. complete = function(ArgLead, CmdLine, CursorPos)
  636. -- return completion candidates as a list-like table
  637. return { "foo", "bar", "baz" }
  638. end,
  639. })
  640. <
  641. Buffer-local user commands are created with `vim.api.`|nvim_buf_create_user_command()|.
  642. Here the first argument is the buffer number (`0` being the current buffer);
  643. the remaining arguments are the same as for |nvim_create_user_command()|:
  644. >lua
  645. vim.api.nvim_buf_create_user_command(0, 'Upper',
  646. function(opts)
  647. print(string.upper(opts.fargs[1]))
  648. end,
  649. { nargs = 1 })
  650. <
  651. ------------------------------------------------------------------------------
  652. Deleting user commands *lua-guide-commands-delete*
  653. User commands can be deleted with `vim.api.`|nvim_del_user_command()|. The only
  654. argument is the name of the command:
  655. >lua
  656. vim.api.nvim_del_user_command('Upper')
  657. <
  658. To delete buffer-local user commands use `vim.api.`|nvim_buf_del_user_command()|.
  659. Here the first argument is the buffer number (`0` being the current buffer),
  660. and second is command name:
  661. >lua
  662. vim.api.nvim_buf_del_user_command(4, 'Upper')
  663. <
  664. ==============================================================================
  665. Credits *lua-guide-credits*
  666. This guide is in large part taken from nanotee's Lua guide:
  667. https://github.com/nanotee/nvim-lua-guide
  668. Thank you @nanotee!
  669. vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: