robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. KeyesMerge #40721 from justinmk/refactor4d736cd41f

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