diff --git a/lua/fff/picker_ui.lua b/lua/fff/picker_ui.lua index 5a2e0041..e997eee3 100644 --- a/lua/fff/picker_ui.lua +++ b/lua/fff/picker_ui.lua @@ -1219,6 +1219,42 @@ function M.scroll_preview_down() preview.scroll(scroll_lines) end +--- Find the first visible window with a normal file buffer +--- @return number|nil Window ID of the first suitable window, or nil if none found +local function find_suitable_window() + local current_tabpage = vim.api.nvim_get_current_tabpage() + local windows = vim.api.nvim_tabpage_list_wins(current_tabpage) + + for _, win in ipairs(windows) do + if vim.api.nvim_win_is_valid(win) then + local buf = vim.api.nvim_win_get_buf(win) + if vim.api.nvim_buf_is_valid(buf) then + local buftype = vim.api.nvim_buf_get_option(buf, 'buftype') + local modifiable = vim.api.nvim_buf_get_option(buf, 'modifiable') + local filetype = vim.api.nvim_buf_get_option(buf, 'filetype') + + local is_picker_window = ( + win == M.state.input_win + or win == M.state.list_win + or win == M.state.preview_win + or win == M.state.file_info_win + ) + + if + (buftype == '' or buftype == 'acwrite') + and modifiable + and not is_picker_window + and filetype ~= 'undotree' + then + return win + end + end + end + end + + return nil +end + function M.select(action) if not M.state.active then return end @@ -1235,6 +1271,21 @@ function M.select(action) M.close() if action == 'edit' then + local current_buf = vim.api.nvim_get_current_buf() + local current_buftype = vim.api.nvim_buf_get_option(current_buf, 'buftype') + local current_buf_modifiable = vim.api.nvim_buf_get_option(current_buf, 'modifiable') + + -- If current active buffer is not a normal buffer we find a suitable window with a tab otherwise opening a new split + if current_buftype ~= '' or not current_buf_modifiable then + local suitable_win = find_suitable_window() + if suitable_win then + vim.api.nvim_set_current_win(suitable_win) + else + vim.cmd('split ' .. vim.fn.fnameescape(relative_path)) + return + end + end + vim.cmd('edit ' .. vim.fn.fnameescape(relative_path)) elseif action == 'split' then vim.cmd('split ' .. vim.fn.fnameescape(relative_path))