From f2fc7cafc54de58718ea8d769e457d864f013fb0 Mon Sep 17 00:00:00 2001 From: Tomas Slusny Date: Thu, 28 Nov 2024 22:24:08 +0100 Subject: [PATCH] refactor: simplify buffer handling using builtin functions Replace manual buffer search and creation logic with built-in Neovim functions bufadd() and bufload(). This change makes the code more concise and reliable by leveraging Neovim's native buffer management APIs. The new implementation: - Removes redundant buffer search loop - Uses bufadd() to add new buffer - Uses bufload() to ensure buffer is loaded Signed-off-by: Tomas Slusny --- lua/CopilotChat/init.lua | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/lua/CopilotChat/init.lua b/lua/CopilotChat/init.lua index 9c00d0b0..0ceee510 100644 --- a/lua/CopilotChat/init.lua +++ b/lua/CopilotChat/init.lua @@ -171,7 +171,7 @@ end ---@param end_line number ---@param config CopilotChat.config.shared local function jump_to_diff(winnr, bufnr, start_line, end_line, config) - vim.api.nvim_win_set_cursor(winnr, { start_line, 0 }) + pcall(vim.api.nvim_win_set_cursor, winnr, { start_line, 0 }) pcall(vim.api.nvim_buf_set_mark, bufnr, '<', start_line, 0, {}) pcall(vim.api.nvim_buf_set_mark, bufnr, '>', end_line, 0, {}) pcall(vim.api.nvim_buf_set_mark, bufnr, '[', start_line, 0, {}) @@ -1062,24 +1062,15 @@ function M.setup(config) local diff_bufnr = diff.bufnr - -- Try to find existing buffer first + -- If buffer is not found, try to load it if not diff_bufnr then - for _, buf in ipairs(vim.api.nvim_list_bufs()) do - if utils.filename_same(vim.api.nvim_buf_get_name(buf), diff.filename) then - diff_bufnr = buf - break - end - end - end - - -- Create new empty buffer if doesn't exist - if not diff_bufnr then - diff_bufnr = vim.api.nvim_create_buf(true, false) - vim.api.nvim_buf_set_name(diff_bufnr, diff.filename) - vim.bo[diff_bufnr].filetype = diff.filetype + diff_bufnr = vim.fn.bufadd(diff.filename) + vim.fn.bufload(diff_bufnr) end + state.source.bufnr = diff_bufnr vim.api.nvim_win_set_buf(state.source.winnr, diff_bufnr) + jump_to_diff( state.source.winnr, diff_bufnr,