From 3f34f2de48e393b2ee289f2c8fa613c7eabae6d8 Mon Sep 17 00:00:00 2001 From: Steven Arcangeli <506791+stevearc@users.noreply.github.com> Date: Thu, 31 Aug 2023 08:54:11 -0700 Subject: feat: format() takes an optional callback (#21) * refactor: replicate lsp.buf.format call * feat: format() takes an optional callback * fix: improper logging * fix: callback returns error if buffer is no longer valid * fix: provide more detailed error message to callback * fix: properly detect task interruption * cleanup: remove unnecessary error code translation * fix: lsp formatting for Neovim 0.9 * doc: add example of async formatting on save * fix: async LSP formatter discards changes if buffer was modified * fix: error code comparison * fix: use the same LSP client filtering logic everywhere * fix: add buffer validity guard checks * fix: add buffer validity guard to LSP formatter * refactor: change the default log level to WARN --- doc/conform.txt | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'doc') diff --git a/doc/conform.txt b/doc/conform.txt index 16faaf4..1482ea2 100644 --- a/doc/conform.txt +++ b/doc/conform.txt @@ -88,11 +88,11 @@ OPTIONS *conform-option -------------------------------------------------------------------------------- API *conform-api* -format({opts}): boolean *conform.format* +format({opts}, {callback}): boolean *conform.format* Format a buffer Parameters: - {opts} `nil|table` + {opts} `nil|table` {timeout_ms} `nil|integer` Time in milliseconds to block for formatting. Defaults to 1000. No effect if async = true. @@ -108,6 +108,7 @@ format({opts}): boolean *conform.forma {range} `nil|table` Range to format. Table must contain `start` and `end` keys with {row, col} tuples using (1,0) indexing. Defaults to current selection in visual mode + {callback} `nil|fun(err: nil|string)` Called once formatting has completed Returns: `boolean` True if any formatters were attempted @@ -196,6 +197,7 @@ AUTOFORMAT *conform-autoforma If you want more complex logic than the `format_on_save` option allows, you can write it yourself using your own autocmd. For example: >lua + -- Format synchronously on save vim.api.nvim_create_autocmd("BufWritePre", { pattern = "*", callback = function(args) @@ -216,6 +218,20 @@ write it yourself using your own autocmd. For example: require("conform").format({ timeout_ms = 500, lsp_fallback = true, buf = args.buf }) end, }) + + -- Format asynchronously on save + vim.api.nvim_create_autocmd("BufWritePost", { + pattern = "*", + callback = function(args) + require("conform").format({ async = true, lsp_fallback = true, buf = args.buf }, function(err) + if not err then + vim.api.nvim_buf_call(args.buf, function() + vim.cmd.update() + end) + end + end) + end, + }) < ================================================================================ -- cgit v1.2.3-70-g09d2