diff --git a/lua/r/edit.lua b/lua/r/edit.lua index 8bf4897f..486f53c1 100644 --- a/lua/r/edit.lua +++ b/lua/r/edit.lua @@ -33,6 +33,20 @@ M.assign = function() end end +local pipe_saved_maps = {} + +local restore_pipe_maps = function(bufnr) + local saved = pipe_saved_maps[bufnr] + if not saved then return end + pipe_saved_maps[bufnr] = nil + for key, old in pairs(saved) do + pcall(vim.keymap.del, "i", key, { buffer = bufnr }) + if old and vim.api.nvim_buf_is_valid(bufnr) then + vim.api.nvim_buf_call(bufnr, function() vim.fn.mapset("i", false, old) end) + end + end +end + M.pipe = function() local pipe_opts = { native = " |> ", @@ -67,6 +81,30 @@ M.pipe = function() -- mode. local temp_remaps = { "", "" } + local bufnr = vim.api.nvim_get_current_buf() + + if not pipe_saved_maps[bufnr] then + local saved = {} + for _, key in pairs(temp_remaps) do + local old = vim.fn.maparg(key, "i", false, true) + saved[key] = old.buffer == 1 and old or false + end + pipe_saved_maps[bufnr] = saved + + vim.schedule(function() + vim.api.nvim_create_autocmd( + { "TextChangedI", "CursorMovedI", "InsertLeave" }, + { + buffer = bufnr, + callback = function(args) + restore_pipe_maps(bufnr) + pcall(vim.api.nvim_del_autocmd, args.id) + end, + } + ) + end) + end + for _, key in pairs(temp_remaps) do vim.keymap.set("i", key, function() local cursor = vim.api.nvim_win_get_cursor(0) @@ -77,25 +115,11 @@ M.pipe = function() -- Move the cursor back one column. This only makes a difference if -- a pipe has been inserted mid-line vim.api.nvim_win_set_cursor(0, { row, col - 1 }) - -- Delete this keymapping so whitespace stripping doesn't happen again - vim.keymap.del("i", key, { buffer = 0 }) + restore_pipe_maps(bufnr) -- Insert the newline vim.api.nvim_input(key) - end, { buffer = 0 }) + end, { buffer = bufnr }) end - - -- Set a single-use autocommand so that if the user changes the text, i.e. - -- keeps typing after inserting the pipe, the above keymappings are removed - vim.schedule(function() - vim.api.nvim_create_autocmd({ "TextChangedI", "CursorMovedI", "InsertLeave" }, { - once = true, - callback = function() - for _, key in pairs(temp_remaps) do - pcall(vim.keymap.del, "i", key, { buffer = 0 }) - end - end, - }) - end) end M.buf_enter = function()