neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

lua-guide.txt (29698B)


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