|
| 1 | +--- Prevents a buffer from appearing in multiple windows (opposite of 'winfixbuf') |
| 2 | +--- |
| 3 | +--- This module solves the problem where buffers can appear in multiple windows |
| 4 | +--- despite having 'winfixbuf' set. The 'winfixbuf' option prevents a window from |
| 5 | +--- changing buffers, but doesn't prevent a buffer from appearing in multiple windows. |
| 6 | +--- |
| 7 | +local M = {} |
| 8 | +local buff_to_win_map = {} |
| 9 | +local global_autocmd_setup = false |
| 10 | + |
| 11 | +local function close_duplicates(buf, get_win) |
| 12 | + local intended = get_win() |
| 13 | + if not intended or not vim.api.nvim_win_is_valid(intended) then |
| 14 | + return |
| 15 | + end |
| 16 | + |
| 17 | + local wins = vim.fn.win_findbuf(buf) |
| 18 | + if #wins <= 1 then |
| 19 | + return |
| 20 | + end |
| 21 | + |
| 22 | + for _, win in ipairs(wins) do |
| 23 | + if win ~= intended and vim.api.nvim_win_is_valid(win) then |
| 24 | + vim.schedule(function() |
| 25 | + pcall(vim.api.nvim_win_close, win, true) |
| 26 | + end) |
| 27 | + end |
| 28 | + end |
| 29 | +end |
| 30 | + |
| 31 | +local check_all_buffers = vim.schedule_wrap(function() |
| 32 | + for buf, get_win in pairs(buff_to_win_map) do |
| 33 | + if vim.api.nvim_buf_is_valid(buf) then |
| 34 | + close_duplicates(buf, get_win) |
| 35 | + else |
| 36 | + buff_to_win_map[buf] = nil |
| 37 | + end |
| 38 | + end |
| 39 | +end) |
| 40 | + |
| 41 | +local function setup() |
| 42 | + if global_autocmd_setup then |
| 43 | + return |
| 44 | + end |
| 45 | + global_autocmd_setup = true |
| 46 | + |
| 47 | + vim.api.nvim_create_autocmd({ 'WinNew', 'VimResized' }, { |
| 48 | + callback = check_all_buffers, |
| 49 | + }) |
| 50 | +end |
| 51 | + |
| 52 | +--- Protect a buffer from appearing in multiple windows |
| 53 | +---@param buf integer Buffer number |
| 54 | +---@param get_intended_window fun(): integer? Function returning intended window ID |
| 55 | +function M.fix_to_win(buf, get_intended_window) |
| 56 | + setup() |
| 57 | + |
| 58 | + buff_to_win_map[buf] = get_intended_window |
| 59 | + vim.api.nvim_create_autocmd('BufWinEnter', { |
| 60 | + buffer = buf, |
| 61 | + callback = function() |
| 62 | + close_duplicates(buf, get_intended_window) |
| 63 | + end, |
| 64 | + }) |
| 65 | +end |
| 66 | + |
| 67 | +return M |
0 commit comments