Skip to content

Commit

Permalink
fix: keep window position stable when LSP formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
stevearc committed Aug 28, 2023
1 parent b883fec commit 90e8a8d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
15 changes: 14 additions & 1 deletion lua/conform/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,17 @@ M.setup = function(opts)
end,
})
end

---@diagnostic disable-next-line: duplicate-set-field
vim.lsp.handlers["textDocument/formatting"] = function(_, result, ctx, _)
if not result then
return
end
local client = vim.lsp.get_client_by_id(ctx.client_id)
local restore = require("conform.util").save_win_positions(ctx.bufnr)
vim.lsp.util.apply_text_edits(result, ctx.bufnr, client.offset_encoding)
restore()
end
end

---Format a buffer
Expand Down Expand Up @@ -130,7 +141,9 @@ M.format = function(opts)
if supports_lsp_formatting then
local restore = require("conform.util").save_win_positions(opts.bufnr)
vim.lsp.buf.format(opts)
restore()
if not opts.async then
restore()
end
end
else
vim.notify("No formatters found for buffer. See :checkhealth conform", vim.log.levels.WARN)
Expand Down
11 changes: 8 additions & 3 deletions lua/conform/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,14 @@ M.save_win_positions = function(bufnr)

return function()
for winid, view in pairs(win_positions) do
vim.api.nvim_win_call(winid, function()
pcall(vim.fn.winrestview, view)
end)
if
vim.api.nvim_win_is_valid(winid)
and vim.deep_equal(vim.api.nvim_win_get_cursor(winid), { 1, 0 })
then
vim.api.nvim_win_call(winid, function()
pcall(vim.fn.winrestview, view)
end)
end
end
end
end
Expand Down

0 comments on commit 90e8a8d

Please sign in to comment.