diff --git a/README.md b/README.md index 5771d7f..1c6faa5 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,10 @@ ft('typescript,javascript,typescriptreact'):fmt('prettier') -- call setup LAST require('guard').setup({ - -- the only option for the setup function + -- the only options for the setup function fmt_on_save = true, + -- Use lsp if no formatter was defined for this filetype + lsp_as_default_formatter = false, }) ``` @@ -90,7 +92,7 @@ Table format for custom tool: - `Pylint` - `rubocop` -## Trobuleshooting +## Troubleshooting if guard does not auto format on save, run `checkhealth` first. diff --git a/doc/guard.nvim.txt b/doc/guard.nvim.txt index ffd709f..18f19b1 100644 --- a/doc/guard.nvim.txt +++ b/doc/guard.nvim.txt @@ -40,26 +40,29 @@ examples, more info below. >lua local ft = require('guard.filetype') - + -- use clang-format and clang-tidy for c files ft('c'):fmt('clang-format') :lint('clang-tidy') - + -- use stylua to format lua files and no linter ft('lua'):fmt('stylua') - + -- use lsp to format first then use golines to format ft('go'):fmt('lsp') :append('golines') :lint('golangci') - + -- multiple files register ft('typescript,javascript,typescriptreact'):fmt('prettier') - + + -- call setup LAST require('guard').setup({ - -- the only option for the setup function - fmt_on_save = true, + -- the only options for the setup function + fmt_on_save = true, + -- Use lsp if no formatter was defined for this filetype + lsp_as_default_formatter = false, }) < @@ -96,7 +99,7 @@ Table format for custom tool: timeout --integer ignore_pattern --table ignore run format when pattern match ignore_error --when has lsp error ignore format - + --special fn --function if fn is set other field will not take effect } diff --git a/lua/guard/init.lua b/lua/guard/init.lua index b5cb7a4..90e2177 100644 --- a/lua/guard/init.lua +++ b/lua/guard/init.lua @@ -56,6 +56,7 @@ end local function setup(opt) opt = opt or { fmt_on_save = true, + lsp_as_default_formatter = false, } parse_setup_cfg(opt.ft) @@ -65,6 +66,24 @@ local function setup(opt) register_event(fts) end + if opt.lsp_as_default_formatter then + vim.api.nvim_create_autocmd('LspAttach', { + callback = function(args) + local client = vim.lsp.get_client_by_id(args.data.client_id) + if not client:supports_method('textDocument/formatting') then + return + end + local fthandler = require('guard.filetype') + local lsp = require('guard.tools.formatter').lsp + if fthandler[vim.bo[args.buf].filetype] and fthandler[vim.bo[args.buf].filetype].fmt then + table.insert(fthandler[vim.bo[args.buf]], 1, lsp) + else + fthandler(vim.bo[args.buf].filetype):fmt(lsp) + end + end + }) + end + local lint = require('guard.lint') for ft, conf in pairs(fts_config) do if conf.linter then