Skip to content

Commit 3a69472

Browse files
committed
fix: use :startinsert instead of feedkeys to switch to terminal mode
If user has their own `startinsert`, e.g. in the following case, `startinsert` is trigger by `:term`, but later fzf term is focused. ``` nvim \ +"au TermOpen * startinsert" \ +"term" \ +"lua vim.defer_fn(function() vim.cmd [[FzfLua files]] end, 100)" ``` Technically user should not `startinsert` on an incorrect window, but currently there's no way to avoid it since builtin `startinsert` seems defered but `nvim_get_mode` is fast (return actual mode immediately). This PR periodly retry `startinsert` until `nt` mode on fzf term buffer. TODO: test
1 parent 9a1f4b6 commit 3a69472

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

lua/fzf-lua/fzf.lua

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -333,14 +333,8 @@ function M.raw_fzf(contents, fzf_cli_args, opts)
333333
-- fzf-tmux spawns outside neovim, don't set filetype/insert mode
334334
if not opts.is_fzf_tmux then
335335
vim.bo.filetype = "fzf"
336-
337336
-- See note in "ModeChanged" above
338-
if vim.api.nvim_get_mode().mode == "t" then
339-
-- Called from another fzf-win most likely
340-
utils.feed_keys_termcodes("i")
341-
else
342-
vim.cmd [[startinsert]]
343-
end
337+
utils.ensure_startinsert(5, 10)
344338
end
345339

346340
return coroutine.yield()

lua/fzf-lua/utils.lua

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1298,6 +1298,26 @@ function M.setmetatable__gc(t, mt)
12981298
return setmetatable(t, mt)
12991299
end
13001300

1301+
---@param retry integer?
1302+
---@param timeout integer?
1303+
function M.ensure_startinsert(retry, timeout)
1304+
local bufnr = vim.api.nvim_get_current_buf()
1305+
local function ensure_startinsert(_retry, _timeout)
1306+
-- abort for some reason we switch to another buffer
1307+
if vim.api.nvim_get_current_buf() ~= bufnr then return end
1308+
if vim.api.nvim_get_mode().mode ~= "t" then
1309+
vim.cmd [[startinsert]]
1310+
return
1311+
end
1312+
-- Called from another fzf-win most likely
1313+
-- don't startinsert until we enter new terminal mode
1314+
return vim.defer_fn(function()
1315+
return ensure_startinsert(_retry - 1, math.min(100, _timeout * 2))
1316+
end, _timeout)
1317+
end
1318+
return ensure_startinsert(retry or 5, timeout or 10)
1319+
end
1320+
13011321
--- Checks if treesitter parser for language is installed
13021322
---@param lang string
13031323
function M.has_ts_parser(lang)

0 commit comments

Comments
 (0)