diff --git a/lua/orgmode/capture/init.lua b/lua/orgmode/capture/init.lua index 02b74dc90..57830baf7 100644 --- a/lua/orgmode/capture/init.lua +++ b/lua/orgmode/capture/init.lua @@ -346,7 +346,6 @@ function Capture:_refile_to(opts) apply_properties(opts) local is_same_file = opts.file == utils.current_file_path() - local cur_win = vim.api.nvim_get_current_win() local item = opts.item if is_same_file and item then @@ -354,18 +353,10 @@ function Capture:_refile_to(opts) return true end + local edit_file = utils.edit_file(opts.file) + if not is_same_file then - local bufnr = vim.fn.bufadd(opts.file) - vim.api.nvim_open_win(bufnr, true, { - relative = 'editor', - width = 1, - -- TODO: Revert to 1 once the https://github.com/neovim/neovim/issues/19464 is fixed - height = 2, - row = 99999, - col = 99999, - zindex = 1, - style = 'minimal', - }) + edit_file.open() end remove_buffer_empty_lines(opts) @@ -374,8 +365,7 @@ function Capture:_refile_to(opts) vim.api.nvim_buf_set_lines(0, range.start_line, range.end_line, false, opts.lines) if not is_same_file then - vim.cmd('silent! wq!') - vim.api.nvim_set_current_win(cur_win) + edit_file.close() end if item and item.file == utils.current_file_path() then diff --git a/lua/orgmode/parser/files.lua b/lua/orgmode/parser/files.lua index 018936952..acf68d321 100644 --- a/lua/orgmode/parser/files.lua +++ b/lua/orgmode/parser/files.lua @@ -186,21 +186,11 @@ function Files.update_file(filename, action) end) end - local bufnr = vim.fn.bufadd(filename) - vim.api.nvim_open_win(bufnr, true, { - relative = 'editor', - width = 1, - -- TODO: Revert to 1 once the https://github.com/neovim/neovim/issues/19464 is fixed - height = 2, - row = 99999, - col = 99999, - zindex = 1, - style = 'minimal', - }) + local edit_file = utils.edit_file(filename) + edit_file.open() return Promise.resolve(action(file)):next(function(result) - vim.cmd('silent! wq!') - vim.api.nvim_set_current_win(cur_win) + edit_file.close() return result end) end diff --git a/lua/orgmode/utils/init.lua b/lua/orgmode/utils/init.lua index 767eee525..fbea1e78f 100644 --- a/lua/orgmode/utils/init.lua +++ b/lua/orgmode/utils/init.lua @@ -596,4 +596,35 @@ function utils.pad_right(str, amount) return string.format('%s%s', str, string.rep(' ', spaces)) end +---@param filename string +function utils.edit_file(filename) + local buf_not_already_loaded = vim.fn.bufexists(filename) ~= 1 + local cur_win = vim.api.nvim_get_current_win() + + return { + open = function() + local bufnr = vim.fn.bufadd(filename) + vim.api.nvim_open_win(bufnr, true, { + relative = 'editor', + width = 1, + -- TODO: Revert to 1 once the https://github.com/neovim/neovim/issues/19464 is fixed + height = 2, + row = 99999, + col = 99999, + zindex = 1, + style = 'minimal', + }) + end, + close = function() + vim.cmd('silent! w') + if buf_not_already_loaded then + vim.cmd('silent! bw!') + else + vim.cmd('silent! q!') + end + vim.api.nvim_set_current_win(cur_win) + end, + } +end + return utils