Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,13 @@ ft('lang'):fmt('format-tool-1')

-- Call setup() LAST!
require('guard').setup({
-- the only options for the setup function
-- Choose to format on every write to a buffer
fmt_on_save = true,
-- Use lsp if no formatter was defined for this filetype
lsp_as_default_formatter = false,
-- By default, Guard writes the buffer on every format
-- You can disable this by setting:
-- save_on_fmt = false,
})
```

Expand Down
8 changes: 6 additions & 2 deletions lua/guard/format.lua
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ local function update_buffer(bufnr, prev_lines, new_lines)

if #new_lines ~= #prev_lines then
api.nvim_buf_set_lines(bufnr, 0, -1, false, new_lines)
api.nvim_command('silent! noautocmd write!')
if require("guard").config.opts.save_on_fmt then
api.nvim_command('silent! noautocmd write!')
end
restore_views(views)
return
end
Expand All @@ -66,7 +68,9 @@ local function update_buffer(bufnr, prev_lines, new_lines)
end

api.nvim_buf_set_lines(bufnr, 0, -1, false, new_lines)
api.nvim_command('silent! noautocmd write!')
if require("guard").config.opts.save_on_fmt then
api.nvim_command('silent! noautocmd write!')
end
restore_views(views)
end

Expand Down
16 changes: 11 additions & 5 deletions lua/guard/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ local util = require('guard.util')
local ft_handler = require('guard.filetype')
local events = require('guard.events')

local config = {
Comment thread
xiaoshihou514 marked this conversation as resolved.
opts = nil
}

local function register_cfg_by_table(fts_with_cfg)
for ft, cfg in pairs(fts_with_cfg or {}) do
if not vim.tbl_isempty(cfg) then
Expand All @@ -28,23 +32,24 @@ local function resolve_multi_ft()
end

local function setup(opt)
opt = vim.tbl_extend('force', {
config.opts = vim.tbl_extend('force', {
fmt_on_save = true,
lsp_as_default_formatter = false,
save_on_fmt = true,
}, opt or {})

register_cfg_by_table(opt.ft)
register_cfg_by_table(config.opts.ft)
resolve_multi_ft()

if opt.lsp_as_default_formatter then
events.create_lspattach_autocmd(opt.fmt_on_save)
if config.opts.lsp_as_default_formatter then
events.create_lspattach_autocmd(config.opts.fmt_on_save)
end

local lint = require('guard.lint')
for ft, conf in pairs(ft_handler) do
local lint_events = { 'BufWritePost', 'BufEnter' }

if conf.formatter and opt.fmt_on_save then
if conf.formatter and config.opts.fmt_on_save then
events.watch_ft(ft)
lint_events[1] = 'User GuardFmt'
end
Expand All @@ -63,4 +68,5 @@ end

return {
setup = setup,
config = config,
}