From 39da4f01c4e6aa63888c88fda402c1e68e78b1c3 Mon Sep 17 00:00:00 2001 From: Micah Halter Date: Fri, 20 Sep 2024 03:01:55 -0400 Subject: [PATCH] centralize leaving visual mode and use more correct way to leave visual mode --- lua/grug-far.lua | 21 ++++----------------- lua/grug-far/utils.lua | 11 +++++++++++ 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/lua/grug-far.lua b/lua/grug-far.lua index 9ba442ff..35deaf38 100644 --- a/lua/grug-far.lua +++ b/lua/grug-far.lua @@ -252,12 +252,8 @@ function M.open(options) ensure_configured() local resolvedOpts = opts.with_defaults(options or {}, globalOptions) local is_visual = false - if not resolvedOpts.ignoreVisualSelection and vim.fn.mode():lower():find('v') ~= nil then - is_visual = true - end - if is_visual then - -- needed to make visual selection work - vim.cmd([[normal! vv]]) + if not resolvedOpts.ignoreVisualSelection then + is_visual = utils.leaveVisualMode() end return M._open_internal(resolvedOpts, { is_visual = is_visual }) @@ -422,11 +418,7 @@ end function M.with_visual_selection(options) ensure_configured() - local isVisualMode = vim.fn.mode():lower():find('v') ~= nil - if isVisualMode then - -- needed to make visual selection work - vim.cmd([[normal! vv]]) - end + utils.leaveVisualMode() local resolvedOpts = opts.with_defaults(options or {}, globalOptions) return M._open_internal(resolvedOpts, { is_visual = true }) @@ -436,12 +428,7 @@ end --- This is provided as a utility for users so they don't have to rewrite ---@return string function M.get_current_visual_selection() - local isVisualMode = vim.fn.mode():lower():find('v') ~= nil - if isVisualMode then - -- needed to make visual selection work - vim.cmd([[normal! vv]]) - end - + utils.leaveVisualMode() local selection_lines = utils.getVisualSelectionLines() return vim.fn.join(selection_lines, '\n') end diff --git a/lua/grug-far/utils.lua b/lua/grug-far/utils.lua index 3877a86c..996c5d90 100644 --- a/lua/grug-far/utils.lua +++ b/lua/grug-far/utils.lua @@ -268,6 +268,17 @@ function M.ensureBufTopEmptyLines(buf, count) end end +--- leave visual mode if in visual mode +---@return boolean if left visual mode +function M.leaveVisualMode() + local isVisualMode = vim.fn.mode():lower():find('v') ~= nil + if isVisualMode then + -- needed to make visual selection work + vim.fn.feedkeys(':', 'nx') + end + return isVisualMode +end + --- get text lines in visual selection ---@return string[] function M.getVisualSelectionLines()