wbthomason / packer.nvim

A use-package inspired plugin manager for Neovim. Uses native packages, supports Luarocks dependencies, written in Lua, allows for expressive config
MIT License
7.87k stars 267 forks source link

README: improve `autocmd` instructions #1082

Open amarakon opened 2 years ago

amarakon commented 2 years ago

First, you can use source without arguments to source the current buffer. As for Lua, it is better to use actual Lua code than calling Vim from Lua.

AzP commented 1 year ago

I was just about to supply a PR with this change, good I found that you'd already done it :)

dsully commented 1 year ago

Even more lua:

vim.api.nvim_create_autocmd("BufWritePost", {
  pattern = "lua/plugins.lua",
  callback = function(args)
    vim.cmd.source(args.file)
    vim.cmd.PackerCompile()
  end,
  desc = "Compile Packer plugins source.",
})
AzP commented 1 year ago

Nice, looks even better.

Susensio commented 1 year ago

Even more lua:

vim.api.nvim_create_autocmd("BufWritePost", {
  pattern = "lua/plugins.lua",
  callback = function(args)
    vim.cmd.source(args.file)
    vim.cmd.PackerCompile()
  end,
  desc = "Compile Packer plugins source.",
})

It's not working for me:

Error detected while processing BufWritePost Autocommands for "plugins.lua":
Error executing lua callback: /home/susensio/.config/nvim/lua/user/plugins.lua:22: attempt to
 index field 'cmd' (a function value)
stack traceback:
        /home/susensio/.config/nvim/lua/user/plugins.lua:22: in function </home/susensio/.con
fig/nvim/lua/user/plugins.lua:21>
dave-kennedy commented 1 year ago
vim.api.nvim_create_autocmd("BufWritePost", {
  pattern = "lua/plugins.lua",
  callback = function(args)
    vim.cmd.source(args.file)
    vim.cmd.PackerCompile()
  end,
  desc = "Compile Packer plugins source.",
})
  1. I think we want to use an autocommand group here, in case the file is sourced more than once.
  2. I don't think that pattern will ever match because it isn't absolute and doesn't contain a wildcard (see :help autocmd-pattern).
  3. Per the OP's original suggestion, we can omit the argument to vim.cmd.source().

So something like this:

vim.api.nvim_create_autocmd('BufWritePost', {
  group = vim.api.nvim_create_augroup('packer_compile', {}),
  pattern = '*/lua/plugins.lua',
  callback = 'source | PackerCompile'
})

I actually prefer to see a message when the command is executed. Also, */lua/plugins.lua might match a lot of files unintentionally, so I use the full path in the pattern:

vim.api.nvim_create_autocmd('BufWritePost', {
  group = vim.api.nvim_create_augroup('packer_compile', {}),
  pattern = vim.fn.expand('$HOME') .. '/dotfiles/vim/lua/plugins.lua',
  callback = function (ctx)
    vim.cmd.source()
    vim.cmd.PackerCompile()
    print('Packer compiled!')
  end
})