Skip to content

Commit 00fba7a

Browse files
authored
Merge pull request #259 from mrjones2014/mrj/245/swap-buf-win-same-buffer
feat(api): Swap buffer view state when swapping wins with the same buf
2 parents 5910b38 + e1b4441 commit 00fba7a

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

lua/smart-splits/api.lua

+26-3
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,7 @@ local function swap_bufs(direction, opts)
442442

443443
local buf_1 = vim.api.nvim_get_current_buf()
444444
local win_1 = vim.api.nvim_get_current_win()
445+
local win_view_1 = vim.fn.winsaveview()
445446

446447
local dir_key = DirectionKeys[direction]
447448
local will_wrap = (direction == Direction.right and at_right_edge())
@@ -455,14 +456,36 @@ local function swap_bufs(direction, opts)
455456
next_win_or_wrap(will_wrap, dir_key)
456457
local buf_2 = vim.api.nvim_get_current_buf()
457458
local win_2 = vim.api.nvim_get_current_win()
459+
local win_view_2 = vim.fn.winsaveview()
460+
461+
-- special case, same buffer in both windows, just swap cursor/scroll position
462+
if buf_1 == buf_2 then
463+
-- temporarily turn off folds to prevent jumping around the buffer
464+
local win_1_folds_enabled = vim.api.nvim_get_option_value('foldenable', { win = win_1 })
465+
local win_2_folds_enabled = vim.api.nvim_get_option_value('foldenable', { win = win_2 })
466+
vim.api.nvim_set_option_value('foldenable', false, { win = win_1 })
467+
vim.api.nvim_set_option_value('foldenable', false, { win = win_2 })
468+
469+
vim.api.nvim_set_current_win(win_1)
470+
vim.fn.winrestview(win_view_2)
471+
vim.api.nvim_set_current_win(win_2)
472+
vim.fn.winrestview(win_view_1)
473+
474+
-- revert `foldenable` option
475+
vim.api.nvim_set_option_value('foldenable', win_1_folds_enabled, { win = win_1 })
476+
vim.api.nvim_set_option_value('foldenable', win_2_folds_enabled, { win = win_2 })
477+
else
478+
vim.api.nvim_win_set_buf(win_2, buf_1)
479+
vim.api.nvim_win_set_buf(win_1, buf_2)
480+
end
458481

459-
vim.api.nvim_win_set_buf(win_2, buf_1)
460-
vim.api.nvim_win_set_buf(win_1, buf_2)
461482
local move_cursor_with_buf = opts.move_cursor
462483
if move_cursor_with_buf == nil then
463484
move_cursor_with_buf = config.cursor_follows_swapped_bufs
464485
end
465-
if not move_cursor_with_buf then
486+
if move_cursor_with_buf then
487+
vim.api.nvim_set_current_win(win_2)
488+
else
466489
vim.api.nvim_set_current_win(win_1)
467490
end
468491
end

0 commit comments

Comments
 (0)