@@ -442,6 +442,7 @@ local function swap_bufs(direction, opts)
442
442
443
443
local buf_1 = vim .api .nvim_get_current_buf ()
444
444
local win_1 = vim .api .nvim_get_current_win ()
445
+ local win_view_1 = vim .fn .winsaveview ()
445
446
446
447
local dir_key = DirectionKeys [direction ]
447
448
local will_wrap = (direction == Direction .right and at_right_edge ())
@@ -455,14 +456,36 @@ local function swap_bufs(direction, opts)
455
456
next_win_or_wrap (will_wrap , dir_key )
456
457
local buf_2 = vim .api .nvim_get_current_buf ()
457
458
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
458
481
459
- vim .api .nvim_win_set_buf (win_2 , buf_1 )
460
- vim .api .nvim_win_set_buf (win_1 , buf_2 )
461
482
local move_cursor_with_buf = opts .move_cursor
462
483
if move_cursor_with_buf == nil then
463
484
move_cursor_with_buf = config .cursor_follows_swapped_bufs
464
485
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
466
489
vim .api .nvim_set_current_win (win_1 )
467
490
end
468
491
end
0 commit comments