packer.nvim icon indicating copy to clipboard operation
packer.nvim copied to clipboard

README: improve `autocmd` instructions

Open amarakon opened this issue 1 year ago • 5 comments

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.

amarakon avatar Oct 02 '22 01:10 amarakon

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

AzP avatar Nov 11 '22 23:11 AzP

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.",
})

dsully avatar Nov 13 '22 05:11 dsully

Nice, looks even better.

AzP avatar Nov 13 '22 09:11 AzP

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>

Susensio avatar Nov 25 '22 17:11 Susensio

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
})

dave-kennedy avatar Dec 23 '22 19:12 dave-kennedy