Skip to content

Commit

Permalink
fix(#48): preserve window views of formatted buffers
Browse files Browse the repository at this point in the history
  • Loading branch information
barrett-ruth committed Aug 11, 2023
1 parent 603dc47 commit 6c6efa2
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lua/guard/format.lua
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,27 @@ local function ignored(buf, patterns)
return false
end

local function save_views(bufnr)
local views = {}
for _, win in ipairs(vim.fn.win_findbuf(bufnr)) do
views[win] = api.nvim_win_call(win, vim.fn.winsaveview)
end
return views
end

local function restore_views(views)
for win, view in pairs(views) do
api.nvim_win_call(win, function()
vim.fn.winrestview(view)
end)
end
end

local function update_buffer(bufnr, new_lines, srow, erow)
if not new_lines or #new_lines == 0 then
return
end
local view = vim.fn.winsaveview()
local views = save_views(bufnr)

local prev_lines = vim.api.nvim_buf_get_lines(bufnr, srow, erow, true)
new_lines = vim.split(new_lines, '\n')
Expand Down Expand Up @@ -63,7 +79,7 @@ local function update_buffer(bufnr, new_lines, srow, erow)
if mode == 'v' or 'V' then
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes('<Esc>', true, false, true), 'n', true)
end
vim.fn.winrestview(view)
restore_views(views)
end

local function find(startpath, patterns, root_dir)
Expand Down

0 comments on commit 6c6efa2

Please sign in to comment.