aboutsummaryrefslogtreecommitdiffstats
path: root/lua/conform
diff options
context:
space:
mode:
authorSteven Arcangeli <stevearc@stevearc.com>2023-09-15 14:27:29 -0700
committerSteven Arcangeli <stevearc@stevearc.com>2023-09-15 14:30:24 -0700
commitaa38b05575dab57b813ddcd14780f65ff20a6d49 (patch)
treefbd0cf1bf9719335592ebe7b09336471dd7a9f87 /lua/conform
parent9e7d1d6e47a8dcc93fac8d83eea74fef7a6b3322 (diff)
feat: provide a formatexpr (#55)
Diffstat (limited to 'lua/conform')
-rw-r--r--lua/conform/init.lua37
1 files changed, 37 insertions, 0 deletions
diff --git a/lua/conform/init.lua b/lua/conform/init.lua
index a19813e..07c46a3 100644
--- a/lua/conform/init.lua
+++ b/lua/conform/init.lua
@@ -343,6 +343,7 @@ M.format = function(opts, callback)
elseif opts.lsp_fallback and not vim.tbl_isempty(lsp_format.get_format_clients(opts)) then
log.debug("Running LSP formatter on %s", vim.api.nvim_buf_get_name(opts.bufnr))
lsp_format.format(opts, callback)
+ any_formatters = true
elseif any_formatters_configured and not opts.quiet then
vim.notify("No formatters found for buffer. See :ConformInfo", vim.log.levels.WARN)
callback("No formatters found for buffer")
@@ -480,4 +481,40 @@ M.get_formatter_info = function(formatter, bufnr)
}
end
+M.formatexpr = function(opts)
+ -- Change the defaults slightly from conform.format
+ opts = vim.tbl_deep_extend("keep", opts or {}, {
+ timeout_ms = 500,
+ lsp_fallback = true,
+ })
+ -- Force async = false
+ opts.async = false
+ if vim.tbl_contains({ "i", "R", "ic", "ix" }, vim.fn.mode()) then
+ -- `formatexpr` is also called when exceeding `textwidth` in insert mode
+ -- fall back to internal formatting
+ return 1
+ end
+
+ local start_lnum = vim.v.lnum
+ local end_lnum = start_lnum + vim.v.count - 1
+
+ if start_lnum <= 0 or end_lnum <= 0 then
+ return 0
+ end
+ local end_line = vim.fn.getline(end_lnum)
+ local end_col = end_line:len()
+ opts.range = {
+ start = { start_lnum, 0 },
+ ["end"] = { end_lnum, end_col },
+ }
+ if M.format(opts) then
+ return 0
+ elseif opts.lsp_fallback then
+ -- No formatters were available; fall back to lsp formatter
+ return vim.lsp.formatexpr({ timeout_ms = opts.timeout_ms })
+ else
+ return 1
+ end
+end
+
return M