lua-guide.txt 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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. print(vim.fn.printf('Hello from %s', 'Lua'))
  195. <
  196. This works for both |builtin-functions| and |user-function|s.
  197. Note that hashes (`#`) are not valid characters for identifiers in Lua, so,
  198. e.g., |autoload| functions have to be called with this syntax:
  199. >lua
  200. vim.fn['my#autoload#function']()
  201. <
  202. ------------------------------------------------------------------------------
  203. See also:
  204. • |builtin-functions|: alphabetic list of all Vimscript functions
  205. • |function-list|: list of all Vimscript functions grouped by topic
  206. • |:runtime|: run all Lua scripts matching a pattern in |'runtimepath'|
  207. • |package.path|: list of all paths searched by `require()`
  208. ==============================================================================
  209. Variables *lua-guide-variables*
  210. Variables can be set and read using the following wrappers, which directly
  211. correspond to their |variable-scope|:
  212. • |vim.g|: global variables (|g:|)
  213. • |vim.b|: variables for the current buffer (|b:|)
  214. • |vim.w|: variables for the current window (|w:|)
  215. • |vim.t|: variables for the current tabpage (|t:|)
  216. • |vim.v|: predefined Vim variables (|v:|)
  217. • |vim.env|: environment variables defined in the editor session
  218. Data types are converted automatically. For example:
  219. >lua
  220. vim.g.some_global_variable = {
  221. key1 = "value",
  222. key2 = 300
  223. }
  224. vim.print(vim.g.some_global_variable)
  225. --> { key1 = "value", key2 = 300 }
  226. <
  227. You can target specific buffers (via number), windows (via |window-ID|), or
  228. tabpages by indexing the wrappers:
  229. >lua
  230. vim.b[2].myvar = 1 -- set myvar for buffer number 2
  231. vim.w[1005].myothervar = true -- set myothervar for window ID 1005
  232. <
  233. Some variable names may contain characters that cannot be used for identifiers
  234. in Lua. You can still manipulate these variables by using the syntax
  235. >lua
  236. vim.g['my#variable'] = 1
  237. <
  238. Note that you cannot directly change fields of array variables. This won't
  239. work:
  240. >lua
  241. vim.g.some_global_variable.key2 = 400
  242. vim.print(vim.g.some_global_variable)
  243. --> { key1 = "value", key2 = 300 }
  244. <
  245. Instead, you need to create an intermediate Lua table and change this:
  246. >lua
  247. local temp_table = vim.g.some_global_variable
  248. temp_table.key2 = 400
  249. vim.g.some_global_variable = temp_table
  250. vim.print(vim.g.some_global_variable)
  251. --> { key1 = "value", key2 = 400 }
  252. <
  253. To delete a variable, simply set it to `nil`:
  254. >lua
  255. vim.g.myvar = nil
  256. <
  257. ------------------------------------------------------------------------------
  258. See also:
  259. • |lua-vim-variables|
  260. ==============================================================================
  261. Options *lua-guide-options*
  262. There are two complementary ways of setting |options| via Lua.
  263. ------------------------------------------------------------------------------
  264. vim.opt
  265. The most convenient way for setting global and local options, e.g., in `init.lua`,
  266. is through `vim.opt` and friends:
  267. • |vim.opt|: behaves like |:set|
  268. • |vim.opt_global|: behaves like |:setglobal|
  269. • |vim.opt_local|: behaves like |:setlocal|
  270. For example, the Vimscript commands
  271. >vim
  272. set smarttab
  273. set nosmarttab
  274. <
  275. are equivalent to
  276. >lua
  277. vim.opt.smarttab = true
  278. vim.opt.smarttab = false
  279. <
  280. In particular, they allow an easy way to working with list-like, map-like, and
  281. set-like options through Lua tables: Instead of
  282. >vim
  283. set wildignore=*.o,*.a,__pycache__
  284. set listchars=space:_,tab:>~
  285. set formatoptions=njt
  286. <
  287. you can use
  288. >lua
  289. vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
  290. vim.opt.listchars = { space = '_', tab = '>~' }
  291. vim.opt.formatoptions = { n = true, j = true, t = true }
  292. <
  293. These wrappers also come with methods that work similarly to their |:set+=|,
  294. |:set^=| and |:set-=| counterparts in Vimscript:
  295. >lua
  296. vim.opt.shortmess:append({ I = true })
  297. vim.opt.wildignore:prepend('*.o')
  298. vim.opt.whichwrap:remove({ 'b', 's' })
  299. <
  300. The price to pay is that you cannot access the option values directly but must
  301. use |vim.opt:get()|:
  302. >lua
  303. print(vim.opt.smarttab)
  304. --> {...} (big table)
  305. print(vim.opt.smarttab:get())
  306. --> false
  307. vim.print(vim.opt.listchars:get())
  308. --> { space = '_', tab = '>~' }
  309. <
  310. ------------------------------------------------------------------------------
  311. vim.o
  312. For this reason, there exists a more direct variable-like access using `vim.o`
  313. and friends, similarly to how you can get and set options via `:echo &number`
  314. and `:let &listchars='space:_,tab:>~'`:
  315. • |vim.o|: behaves like |:set|
  316. • |vim.go|: behaves like |:setglobal|
  317. • |vim.bo|: for buffer-scoped options
  318. • |vim.wo|: for window-scoped options (can be double indexed)
  319. For example:
  320. >lua
  321. vim.o.smarttab = false -- :set nosmarttab
  322. print(vim.o.smarttab)
  323. --> false
  324. vim.o.listchars = 'space:_,tab:>~' -- :set listchars='space:_,tab:>~'
  325. print(vim.o.listchars)
  326. --> 'space:_,tab:>~'
  327. vim.o.isfname = vim.o.isfname .. ',@-@' -- :set isfname+=@-@
  328. print(vim.o.isfname)
  329. --> '@,48-57,/,.,-,_,+,,,#,$,%,~,=,@-@'
  330. vim.bo.shiftwidth = 4 -- :setlocal shiftwidth=4
  331. print(vim.bo.shiftwidth)
  332. --> 4
  333. <
  334. Just like variables, you can specify a buffer number or |window-ID| for buffer
  335. and window options, respectively. If no number is given, the current buffer or
  336. window is used:
  337. >lua
  338. vim.bo[4].expandtab = true -- sets expandtab to true in buffer 4
  339. vim.wo.number = true -- sets number to true in current window
  340. vim.wo[0].number = true -- same as above
  341. vim.wo[0][0].number = true -- sets number to true in current buffer
  342. -- in current window only
  343. print(vim.wo[0].number) --> true
  344. <
  345. ------------------------------------------------------------------------------
  346. See also:
  347. • |lua-options|
  348. ==============================================================================
  349. Mappings *lua-guide-mappings*
  350. You can map either Vim commands or Lua functions to key sequences.
  351. ------------------------------------------------------------------------------
  352. Creating mappings *lua-guide-mappings-set*
  353. Mappings can be created using |vim.keymap.set()|. This function takes three
  354. mandatory arguments:
  355. • {mode} is a string or a table of strings containing the mode
  356. prefix for which the mapping will take effect. The prefixes are the ones
  357. listed in |:map-modes|, or "!" for |:map!|, or empty string for |:map|.
  358. • {lhs} is a string with the key sequences that should trigger the mapping.
  359. • {rhs} is either a string with a Vim command or a Lua function that should
  360. be executed when the {lhs} is entered.
  361. An empty string is equivalent to |<Nop>|, which disables a key.
  362. Examples:
  363. >lua
  364. -- Normal mode mapping for Vim command
  365. vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>')
  366. -- Normal and Command-line mode mapping for Vim command
  367. vim.keymap.set({'n', 'c'}, '<Leader>ex2', '<cmd>echo "Example 2"<cr>')
  368. -- Normal mode mapping for Lua function
  369. vim.keymap.set('n', '<Leader>ex3', vim.treesitter.start)
  370. -- Normal mode mapping for Lua function with arguments
  371. vim.keymap.set('n', '<Leader>ex4', function() print('Example 4') end)
  372. <
  373. You can map functions from Lua modules via
  374. >lua
  375. vim.keymap.set('n', '<Leader>pl1', require('plugin').action)
  376. <
  377. Note that this loads the plugin at the time the mapping is defined. If you
  378. want to defer the loading to the time when the mapping is executed (as for
  379. |autoload| functions), wrap it in `function() end`:
  380. >lua
  381. vim.keymap.set('n', '<Leader>pl2', function() require('plugin').action() end)
  382. <
  383. The fourth, optional, argument is a table with keys that modify the behavior
  384. of the mapping such as those from |:map-arguments|. The following are the most
  385. useful options:
  386. • `buffer`: If given, only set the mapping for the buffer with the specified
  387. number; `0` or `true` means the current buffer. >lua
  388. -- set mapping for the current buffer
  389. vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = true })
  390. -- set mapping for the buffer number 4
  391. vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { buffer = 4 })
  392. <
  393. • `silent`: If set to `true`, suppress output such as error messages. >lua
  394. vim.keymap.set('n', '<Leader>pl1', require('plugin').action, { silent = true })
  395. <
  396. • `expr`: If set to `true`, do not execute the {rhs} but use the return value
  397. as input. Special |keycodes| are converted automatically. For example, the following
  398. mapping replaces <down> with <c-n> in the popupmenu only: >lua
  399. vim.keymap.set('c', '<down>', function()
  400. if vim.fn.pumvisible() == 1 then return '<c-n>' end
  401. return '<down>'
  402. end, { expr = true })
  403. <
  404. • `desc`: A string that is shown when listing mappings with, e.g., |:map|.
  405. This is useful since Lua functions as {rhs} are otherwise only listed as
  406. `Lua: <number> <source file>:<line>`. Plugins should therefore always use this
  407. for mappings they create. >lua
  408. vim.keymap.set('n', '<Leader>pl1', require('plugin').action,
  409. { desc = 'Execute action from plugin' })
  410. <
  411. • `remap`: By default, all mappings are nonrecursive (i.e., |vim.keymap.set()|
  412. behaves like |:noremap|). If the {rhs} is itself a mapping that should be
  413. executed, set `remap = true`: >lua
  414. vim.keymap.set('n', '<Leader>ex1', '<cmd>echo "Example 1"<cr>')
  415. -- add a shorter mapping
  416. vim.keymap.set('n', 'e', '<Leader>ex1', { remap = true })
  417. <
  418. Note: |<Plug>| mappings are always expanded even with the default `remap = false`: >lua
  419. vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)')
  420. <
  421. ------------------------------------------------------------------------------
  422. Removing mappings *lua-guide-mappings-del*
  423. A specific mapping can be removed with |vim.keymap.del()|:
  424. >lua
  425. vim.keymap.del('n', '<Leader>ex1')
  426. vim.keymap.del({'n', 'c'}, '<Leader>ex2', {buffer = true})
  427. <
  428. ------------------------------------------------------------------------------
  429. See also:
  430. • `vim.api.`|nvim_get_keymap()|: return all global mapping
  431. • `vim.api.`|nvim_buf_get_keymap()|: return all mappings for buffer
  432. ==============================================================================
  433. Autocommands *lua-guide-autocommands*
  434. An |autocommand| is a Vim command or a Lua function that is automatically
  435. executed whenever one or more |events| are triggered, e.g., when a file is
  436. read or written, or when a window is created. These are accessible from Lua
  437. through the Nvim API.
  438. ------------------------------------------------------------------------------
  439. Creating autocommands *lua-guide-autocommand-create*
  440. Autocommands are created using `vim.api.`|nvim_create_autocmd()|, which takes
  441. two mandatory arguments:
  442. • {event}: a string or table of strings containing the event(s) which should
  443. trigger the command or function.
  444. • {opts}: a table with keys that control what should happen when the event(s)
  445. are triggered.
  446. The most important options are:
  447. • `pattern`: A string or table of strings containing the |autocmd-pattern|.
  448. Note: Environment variable like `$HOME` and `~` are not automatically
  449. expanded; you need to explicitly use `vim.fn.`|expand()| for this.
  450. • `command`: A string containing a Vim command.
  451. • `callback`: A Lua function.
  452. You must specify one and only one of `command` and `callback`. If `pattern` is
  453. omitted, it defaults to `pattern = '*'`.
  454. Examples:
  455. >lua
  456. vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
  457. pattern = {"*.c", "*.h"},
  458. command = "echo 'Entering a C or C++ file'",
  459. })
  460. -- Same autocommand written with a Lua function instead
  461. vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
  462. pattern = {"*.c", "*.h"},
  463. callback = function() print("Entering a C or C++ file") end,
  464. })
  465. -- User event triggered by MyPlugin
  466. vim.api.nvim_create_autocmd("User", {
  467. pattern = "MyPlugin",
  468. callback = function() print("My Plugin Works!") end,
  469. })
  470. <
  471. Nvim will always call a Lua function with a single table containing information
  472. about the triggered autocommand. The most useful keys are
  473. • `match`: a string that matched the `pattern` (see |<amatch>|)
  474. • `buf`: the number of the buffer the event was triggered in (see |<abuf>|)
  475. • `file`: the file name of the buffer the event was triggered in (see |<afile>|)
  476. • `data`: a table with other relevant data that is passed for some events
  477. For example, this allows you to set buffer-local mappings for some filetypes:
  478. >lua
  479. vim.api.nvim_create_autocmd("FileType", {
  480. pattern = "lua",
  481. callback = function(args)
  482. vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = args.buf })
  483. end
  484. })
  485. <
  486. This means that if your callback itself takes an (even optional) argument, you
  487. must wrap it in `function() end` to avoid an error:
  488. >lua
  489. vim.api.nvim_create_autocmd('TextYankPost', {
  490. callback = function() vim.highlight.on_yank() end
  491. })
  492. <
  493. (Since unused arguments can be omitted in Lua function definitions, this is
  494. equivalent to `function(args) ... end`.)
  495. Instead of using a pattern, you can create a buffer-local autocommand (see
  496. |autocmd-buflocal|) with `buffer`; in this case, `pattern` cannot be used:
  497. >lua
  498. -- set autocommand for current buffer
  499. vim.api.nvim_create_autocmd("CursorHold", {
  500. buffer = 0,
  501. callback = function() print("hold") end,
  502. })
  503. -- set autocommand for buffer number 33
  504. vim.api.nvim_create_autocmd("CursorHold", {
  505. buffer = 33,
  506. callback = function() print("hold") end,
  507. })
  508. <
  509. Similarly to mappings, you can (and should) add a description using `desc`:
  510. >lua
  511. vim.api.nvim_create_autocmd('TextYankPost', {
  512. callback = function() vim.highlight.on_yank() end,
  513. desc = "Briefly highlight yanked text"
  514. })
  515. <
  516. Finally, you can group autocommands using the `group` key; this will be
  517. covered in detail in the next section.
  518. ------------------------------------------------------------------------------
  519. Grouping autocommands *lua-guide-autocommands-group*
  520. Autocommand groups can be used to group related autocommands together; see
  521. |autocmd-groups|. This is useful for organizing autocommands and especially
  522. for preventing autocommands to be set multiple times.
  523. Groups can be created with `vim.api.`|nvim_create_augroup()|. This function
  524. takes two mandatory arguments: a string with the name of a group and a table
  525. determining whether the group should be cleared (i.e., all grouped
  526. autocommands removed) if it already exists. The function returns a number that
  527. is the internal identifier of the group. Groups can be specified either by
  528. this identifier or by the name (but only if the group has been created first).
  529. For example, a common Vimscript pattern for autocommands defined in files that
  530. may be reloaded is
  531. >vim
  532. augroup vimrc
  533. " Remove all vimrc autocommands
  534. autocmd!
  535. au BufNewFile,BufRead *.html set shiftwidth=4
  536. au BufNewFile,BufRead *.html set expandtab
  537. augroup END
  538. <
  539. This is equivalent to the following Lua code:
  540. >lua
  541. local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = true })
  542. vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, {
  543. pattern = '*.html',
  544. group = mygroup,
  545. command = 'set shiftwidth=4',
  546. })
  547. vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, {
  548. pattern = '*.html',
  549. group = 'vimrc', -- equivalent to group=mygroup
  550. command = 'set expandtab',
  551. })
  552. <
  553. Autocommand groups are unique for a given name, so you can reuse them, e.g.,
  554. in a different file:
  555. >lua
  556. local mygroup = vim.api.nvim_create_augroup('vimrc', { clear = false })
  557. vim.api.nvim_create_autocmd({ 'BufNewFile', 'BufRead' }, {
  558. pattern = '*.c',
  559. group = mygroup,
  560. command = 'set noexpandtab',
  561. })
  562. <
  563. ------------------------------------------------------------------------------
  564. Deleting autocommands *lua-guide-autocommands-delete*
  565. You can use `vim.api.`|nvim_clear_autocmds()| to remove autocommands. This
  566. function takes a single mandatory argument that is a table of keys describing
  567. the autocommands that are to be removed:
  568. >lua
  569. -- Delete all BufEnter and InsertLeave autocommands
  570. vim.api.nvim_clear_autocmds({event = {"BufEnter", "InsertLeave"}})
  571. -- Delete all autocommands that uses "*.py" pattern
  572. vim.api.nvim_clear_autocmds({pattern = "*.py"})
  573. -- Delete all autocommands in group "scala"
  574. vim.api.nvim_clear_autocmds({group = "scala"})
  575. -- Delete all ColorScheme autocommands in current buffer
  576. vim.api.nvim_clear_autocmds({event = "ColorScheme", buffer = 0 })
  577. <
  578. Note: Autocommands in groups will only be removed if the `group` key is
  579. specified, even if another option matches it.
  580. ------------------------------------------------------------------------------
  581. See also
  582. • |nvim_get_autocmds()|: return all matching autocommands
  583. • |nvim_exec_autocmds()|: execute all matching autocommands
  584. ==============================================================================
  585. User commands *lua-guide-commands*
  586. |user-commands| are custom Vim commands that call a Vimscript or Lua function.
  587. Just like built-in commands, they can have arguments, act on ranges, or have
  588. custom completion of arguments. As these are most useful for plugins, we will
  589. cover only the basics of this advanced topic.
  590. ------------------------------------------------------------------------------
  591. Creating user commands *lua-guide-commands-create*
  592. User commands can be created via |nvim_create_user_command()|. This function
  593. takes three mandatory arguments:
  594. • a string that is the name of the command (which must start with an uppercase
  595. letter to distinguish it from builtin commands);
  596. • a string containing Vim commands or a Lua function that is executed when the
  597. command is invoked;
  598. • a table with |command-attributes|; in addition, it can contain the keys
  599. `desc` (a string describing the command); `force` (set to `false` to avoid
  600. replacing an already existing command with the same name), and `preview` (a
  601. Lua function that is used for |:command-preview|).
  602. Example:
  603. >lua
  604. vim.api.nvim_create_user_command('Test', 'echo "It works!"', {})
  605. vim.cmd.Test()
  606. --> It works!
  607. <
  608. (Note that the third argument is mandatory even if no attributes are given.)
  609. Lua functions are called with a single table argument containing arguments and
  610. modifiers. The most important are:
  611. • `name`: a string with the command name
  612. • `fargs`: a table containing the command arguments split by whitespace (see |<f-args>|)
  613. • `bang`: `true` if the command was executed with a `!` modifier (see |<bang>|)
  614. • `line1`: the starting line number of the command range (see |<line1>|)
  615. • `line2`: the final line number of the command range (see |<line2>|)
  616. • `range`: the number of items in the command range: 0, 1, or 2 (see |<range>|)
  617. • `count`: any count supplied (see |<count>|)
  618. • `smods`: a table containing the command modifiers (see |<mods>|)
  619. For example:
  620. >lua
  621. vim.api.nvim_create_user_command('Upper',
  622. function(opts)
  623. print(string.upper(opts.fargs[1]))
  624. end,
  625. { nargs = 1 })
  626. vim.cmd.Upper('foo')
  627. --> FOO
  628. <
  629. The `complete` attribute can take a Lua function in addition to the
  630. attributes listed in |:command-complete|. >lua
  631. vim.api.nvim_create_user_command('Upper',
  632. function(opts)
  633. print(string.upper(opts.fargs[1]))
  634. end,
  635. { nargs = 1,
  636. complete = function(ArgLead, CmdLine, CursorPos)
  637. -- return completion candidates as a list-like table
  638. return { "foo", "bar", "baz" }
  639. end,
  640. })
  641. <
  642. Buffer-local user commands are created with `vim.api.`|nvim_buf_create_user_command()|.
  643. Here the first argument is the buffer number (`0` being the current buffer);
  644. the remaining arguments are the same as for |nvim_create_user_command()|:
  645. >lua
  646. vim.api.nvim_buf_create_user_command(0, 'Upper',
  647. function(opts)
  648. print(string.upper(opts.fargs[1]))
  649. end,
  650. { nargs = 1 })
  651. <
  652. ------------------------------------------------------------------------------
  653. Deleting user commands *lua-guide-commands-delete*
  654. User commands can be deleted with `vim.api.`|nvim_del_user_command()|. The only
  655. argument is the name of the command:
  656. >lua
  657. vim.api.nvim_del_user_command('Upper')
  658. <
  659. To delete buffer-local user commands use `vim.api.`|nvim_buf_del_user_command()|.
  660. Here the first argument is the buffer number (`0` being the current buffer),
  661. and second is command name:
  662. >lua
  663. vim.api.nvim_buf_del_user_command(4, 'Upper')
  664. <
  665. ==============================================================================
  666. Credits *lua-guide-credits*
  667. This guide is in large part taken from nanotee's Lua guide:
  668. https://github.com/nanotee/nvim-lua-guide
  669. Thank you @nanotee!
  670. vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: