I'm using stylua
as the code formatter for lua files.
I do not usually get used to its formatting style but sometimes I do need a little help with it, so I decided to make it the formatprg
during the visual modes, to format the selected code piece, and clear it for the other modes. Here's what I have currently (yes, I write comma-first lists):
-- after/ftplugin/lua.lua
local enable_stylua_formatprg_on_vV_mode_only_group
= vim.api.nvim_create_augroup('enable_stylua_formatprg_on_vV_mode_only', {})
-- to v/V mode: enable
vim.api.nvim_create_autocmd('ModeChanged', { callback = function () vim.bo.formatprg = 'stylua --search-parent-directories -' end
, pattern = '*:[vV]'
, group = enable_stylua_formatprg_on_vV_mode_only_group
})
-- from v/V mode: disable
vim.api.nvim_create_autocmd('ModeChanged', { callback = function () vim.bo.formatprg = '' end
, pattern = '[vV]:*'
, group = enable_stylua_formatprg_on_vV_mode_only_group
})
It was after some time that I came to realise that these autocmds are not limited to functioning in lua files only. I immediately thought about adding a *.lua
pattern, as what you would do for BufRead
, BufLeave
, etc., but it seems that's not what you can do here since ModeChanged
event uses some old_mode:new_mode
pattern, leaving the only thing to do is to add a filetype checker within the callback function.
I wonder if my understanding is correct, or otherwise any better alternatives are available. Code suggestions are welcome.