telescope.nvim icon indicating copy to clipboard operation
telescope.nvim copied to clipboard

Any buffer opened through the pickers open in Insert mode ...

Open daUnknownCoder opened this issue 1 year ago • 18 comments

Description

when i opened a file with Telescope live_grep or Telescope find_files it opens the files, but they get opened in a differed custom mode i would say, like lualine shows it's Normal mode and my cursor is also thick [for insert it is thin], but i can type in like normal letters, if there's a keymap with that letter, the which-key pops up and i can go back to normal mode with <Esc> but this is annoying

Neovim version

NVIM v0.9.5
Build type: Release
LuaJIT 2.1.1702233742

   system vimrc file: "$VIM/sysinit.vim"
  fall-back for $VIM: "/usr/share/nvim"

Run :checkhealth for more info

Operating system and version

6.7.9-arch1-1

Telescope version / branch / rev

v0.1.6 -> master

checkhealth telescope

==============================================================================
telescope: require("telescope.health").check()

Checking for required plugins ~
- OK plenary installed.
- OK nvim-treesitter installed.

Checking external dependencies ~
- OK rg: found ripgrep 14.1.0
- OK fd: found fd 9.0.0

===== Installed extensions ===== ~

Telescope Extension: `aerial` ~
- No healthcheck provided

Telescope Extension: `emoji` ~
- No healthcheck provided

Telescope Extension: `notify` ~
- No healthcheck provided

Steps to reproduce

just try using the pickers...

Expected behavior

No magic mode, it automatically goes into sort of insert mode

Actual behavior

Kooha-2024-03-20-23-14-17.webm

i use lazy.nvim

Minimal config

return {
  {
    "nvim-telescope/telescope.nvim",
    cmd = "Telescope",
    event = "VeryLazy",
    keys = {
      { "ff", "<cmd>Telescope find_files<CR>", desc = "Find Files Fuzzily [Telescope]" },
      { "fg", "<cmd>Telescope live_grep<CR>", desc = "Find Text [Telescope]" },
      { "fc", "<cmd>Telescope colorscheme<CR>", desc = "Choose Colorschemes [Telescope]" },
      { "fe", "<cmd>Telescope emoji<CR>", desc = "Emoji search - copy - paste [Telescope]" },
      { "fd", "<cmd>Telescope diagnostics<CR>", desc = "Workspace Diagnostics [Telescope]" },
      { "fr", "<cmd>Telescope oldfiles<CR>", desc = "Open Recent File [Telescope]" },
      { "fh", "<cmd>Telescope git_status<CR>", desc = "Git edited files [Telescope]" },
      { "fa", "<cmd>Telescope aerial<CR>", desc = "Symbol Navigation [Telescope]" },
    },
    dependencies = {
      { "xiyaowong/telescope-emoji.nvim", lazy = true, cmd = "Telescope emoji" },
      {
        "nvim-telescope/telescope-fzf-native.nvim",
        build = "cmake -S. -Bbuild -DCMAKE_BUILD_TYPE=Release && cmake --build build --config Release && cmake --install build --prefix build",
        lazy = false,
      },
    },
    config = function()
      local telescope_status_ok, telescope = pcall(require, "telescope")
      if not telescope_status_ok then
        print("Telescope not found!")
      end
      local icons_ok, icons = pcall(require, "NeutronVim.core.icons")
      if not icons_ok then
        print("Unable to import icons!")
      end
      telescope.setup({
        defaults = {
          entry_prefix = icons.ui.ArrowDownandRight,
          selection_caret = icons.ui.Plug,
          prompt_prefix = icons.ui.Telescope,
          initial_mode = "insert",
          selection_strategy = "reset",
          sorting_strategy = "ascending",
          layout_strategy = "horizontal",
          layout_config = {
            horizontal = {
              prompt_position = "top",
              preview_width = 0.55,
              results_width = 0.5,
            },
            vertical = {
              mirror = false,
            },
            width = 0.87,
            height = 0.8,
            preview_cutoff = 120,
          },
        },
        extensions = {
          fzf = {
            fuzzy = true,
            override_generic_sorter = true,
            override_file_sorter = true,
            case_mode = "smart_case",
          },
          aerial = {
            show_nesting = {
              ["_"] = false,
              json = true,
              yaml = true,
            },
          },
        },
      })
      telescope.load_extension("emoji")
      telescope.load_extension("aerial")
    end,
  },
}

daUnknownCoder avatar Mar 20 '24 20:03 daUnknownCoder

I can't reproduce this. Please try with the original minimal config that was in the issue template. I could be due to other factors in your config and not necessarily due to telescope.

jamestrew avatar Mar 21 '24 02:03 jamestrew

@jamestrew, so after a few updates, there's no magic mode, but sometimes it still opens any telescope related stuff in insert mode...

daUnknownCoder avatar Apr 03 '24 17:04 daUnknownCoder

Hi @jamestrew! I was facing this issue for a long time and didn't really know if it's a telescope bug or not.

I'm not sure if I'm talking about the issue that originally was described by @daUnknownCoder here, but you can look at it:

  1. Take a default telescope config
  2. Paste this autocmd to your config
vim.api.nvim_create_autocmd('ModeChanged', {
    pattern = '*:*',
    callback = function() vim.print(vim.v.event.new_mode) end,
})
  1. And after you enter any buffer using find_files or live_grep picker (can happen with other pickers as well, haven't checked that), you'll see i letter in your console - meaning that you're in the insert mode, when in reality you're in normal.

I'm the author of reactive.nvim plugin that uses ModeChanged autocmd to highlight anything and people opened issues on that error several times. For example here (the second part of the very first message).

I don't really know why ModeChanged autocmd isn't triggered when your mode is actually changing from insert to normal when you select an entry in the pickers. Can it be a neovim issue instead?

I was playing with telescope sources and noticed this:

  • When wrapping this line in vim.schedule, it does fix the issue for the find_files picker, but not for live_grep (what??)
  • As I assume, any normal command will fix the issue since it forcely changes the mode to normal. For example, if you put this line out of if-statement so that it's always executed, problem will be solved.

My thoughts are that there can be something happening in the neovim event loop, that forgets to fire ModeChanged autocmd when a lot of things are happening (buffer closing, opening another one, mode change, window focus change, cursor change etc), although I can be wrong on this one. The funny part is that if you put a delay in ModeChanged, let's say for 1 sec, to check which mode you're in using vim.fn.mode(true), you'll see the normal mode there, although autocmd for its change wasn't triggered.

Please, let me know if I need to open a separate issue for this. I'm also ready to provide more information if that's needed!

rasulomaroff avatar Apr 21 '24 02:04 rasulomaroff

And after you enter any buffer using find_files or live_grep picker (can happen with other pickers as well, haven't checked that), you'll see i letter in your console - meaning that you're in the insert mode, when in reality you're in normal.

I'm not experiencing this on either neovim 0.9.5 or master, telescope 0.1.6 or master.

https://github.com/nvim-telescope/telescope.nvim/assets/66286082/3018343c-8b72-4f86-b856-31da5c20ea0d

Here's the minimal config I used for this demo
local root = vim.fn.fnamemodify("./.repro", ":p")

-- set stdpaths to use .repro
for _, name in ipairs({ "config", "data", "state", "cache" }) do
	vim.env[("XDG_%s_HOME"):format(name:upper())] = root .. "/" .. name
end

-- bootstrap lazy
local lazypath = root .. "/plugins/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
	vim.fn.system({
		"git",
		"clone",
		"--filter=blob:none",
		"https://github.com/folke/lazy.nvim.git",
		lazypath,
	})
end
vim.opt.runtimepath:prepend(lazypath)

-- install plugins
local plugins = {
	{
		"nvim-telescope/telescope.nvim",
		tag = "0.1.6",
		dependencies = {
			"nvim-lua/plenary.nvim",
			"nvim-tree/nvim-web-devicons",
		},
		config = function()
			require("telescope").setup({})
			vim.keymap.set("n", "<C-p>", ":Telescope find_files<CR>")
		end,
	},
}

require("lazy").setup(plugins, {
	root = root .. "/plugins",
})

vim.opt.cmdheight = 3
vim.api.nvim_create_autocmd("ModeChanged", {
	pattern = "*:*",
	callback = function()
		print(vim.v.event.new_mode, vim.bo.filetype, vim.api.nvim_buf_get_name(0))
	end,
})

Although semi-recently, there was a neovim issue that caused entering files from telescope to stay in insert mode. https://github.com/nvim-telescope/telescope.nvim/issues/2766 I'm pretty sure this is the cause of your issue @daUnknownCoder

jamestrew avatar Apr 21 '24 02:04 jamestrew

This happened to me too, but disabling codeium.vim stopped it from happening.

Nebell avatar Apr 22 '24 12:04 Nebell

This happened to me too, but disabling codeium.vim stopped it from happening.

you sure its due to codeium.vim? i do use it so can you tell a workaround for that?

daUnknownCoder avatar Apr 22 '24 17:04 daUnknownCoder

This happened to me too, but disabling codeium.vim stopped it from happening.

you sure its due to codeium.vim? i do use it so can you tell a workaround for that?

I don't know how to fix it, but I commented this line and it never happen again. https://github.com/Exafunction/codeium.vim/blob/31dd2962c81759be007895db6ce089feec397c86/autoload/codeium.vim#L504

function! codeium#RedrawStatusLine() abort
  if s:using_codeium_status
    " redrawstatus   " comment this line
  endif
endfunction

I've found that this happens only when the autocmd BufLeave is triggered: https://github.com/Exafunction/codeium.vim/blob/31dd2962c81759be007895db6ce089feec397c86/plugin/codeium.vim#L33

augroup codeium
  autocmd!
  autocmd InsertEnter,CursorMovedI,CompleteChanged * call codeium#DebouncedComplete()
  autocmd BufEnter     * if mode() =~# '^[iR]'|call codeium#DebouncedComplete()|endif
  autocmd InsertLeave  * call codeium#Clear()
  " autocmd BufLeave     * if mode() =~# '^[iR]'|call codeium#Clear()|endif " this autocmd is triggered

Nebell avatar Apr 23 '24 01:04 Nebell

Again, this seems like the same issue from https://github.com/nvim-telescope/telescope.nvim/issues/2766 where the cause was doing certain operations inside a BufWinLeave (similar to BufLeave maybe). This was a neovim/vim issue that got fixed in nightly. If you can try neovim 0.10 nightly if you're not already, this might be an easy way to see if the issue is fixed.

jamestrew avatar Apr 23 '24 02:04 jamestrew

@jamestrew yes indeed, I tried tweaking everything and found out that it's not the bug you were describing. It's actually vim.cmd.normal command. Sometimes, when it's called in insert mode, neovim doesn't trigger ModeChanged command to reflect changes from insert mode to normal mode. I don't really know if that's intentional, but from my understanding ModeChanged should always be triggered no matter what (maybe except when eventignore option is set).

rasulomaroff avatar Apr 23 '24 03:04 rasulomaroff

so i guess i have to cross-post this on codeium.vim's github @Nebell

daUnknownCoder avatar Apr 23 '24 08:04 daUnknownCoder

@Nebell, i am using getStatusString for my lualine

          {
            'vim.fn["codeium#GetStatusString"]()',
            fmt = function(str)
              if str == " ON" then
                return " "
              elseif str == " OFF" then
                return " "
              elseif str == " * " then
                return " "
              else
                return "󰧑 " .. str
              end
            end,
          },

daUnknownCoder avatar Apr 23 '24 08:04 daUnknownCoder

so i guess i have to cross-post this on codeium.vim's github @Nebell

I don't know how to fix it on v0.9.5, and I had tried, it's fixed on v0.10 nightly.

Nebell avatar Apr 23 '24 12:04 Nebell

@rasulomaroff your issue appears to be a separate thing.

Can you create a new issue for it? I'm also curious if you are able to replicate your issue with my minimal config from above (https://github.com/nvim-telescope/telescope.nvim/issues/2995#issuecomment-2067869350)

It would be great if you can also try to replicate this without telescope and just using vim/neovim api as this may very well be not specific to telescope. You can see an example of how I did this for the issue affecting codeium.vim here https://github.com/neovim/neovim/issues/27038

jamestrew avatar Apr 25 '24 03:04 jamestrew

@jamestrew It's really hard to reproduce this issue without using Telescope, because I believe it happens when several conditions are met.

Anyway, I don't think this is a telescope bug even though it happens only when I'm using it. As I stated above, when I put some vim.schedule around vim.cmd.normal calls in telescope sources it starts working.

So, to reproduce my issue you have to:

  1. Have any telescope config, you'll need the find_files picker
  2. Paste this into your config
-- restores the latest cursor position when opening a buffer
local group = vim.api.nvim_create_augroup('restore-cursor-position', {})

vim.api.nvim_create_autocmd('BufReadPre', {
    desc = 'Jump to the latest position in this buffer',
    group = group,
    callback = function(opts)
        vim.api.nvim_create_autocmd('FileType', {
            once = true,
            buffer = opts.buf,
            group = group,
            callback = function()
                local ft = vim.bo.filetype

                -- ignore these filetypes
                if ft == 'commit' or ft == 'rebase' then return end

                local mark = vim.api.nvim_buf_get_mark(opts.buf, '"')
                if mark[1] > 0 and mark[1] <= vim.api.nvim_buf_line_count(opts.buf) then
                    -- vim.api.nvim_win_set_cursor(0, mark)
                    vim.cmd.normal { 'g`"zz', bang = true }
                end
            end,
        })
    end,
})

vim.api.nvim_create_autocmd('ModeChanged', {
    pattern = '*:*',
    callback = function() vim.print(vim.v.event.new_mode) end,
})

This autocmd basically restores the last position in a buffer

  1. Just open the find_files picker and go to any file. In your console, you'll see i indicating that you're in the insert mode while in reality you're in normal. Basically, ModeChanged event wasn't triggered for the i => n transition.

What to note here:

  1. Right above vim.cmd.normal call there's a vim.api.nvim_win_set_cursor api. If you use it instead, it'll work fine
  2. If you put vim.cmd.normal into vim.schedule, it will also work fine (at least for find_files picker)

As I said, even though it happens using telescope, this is clearly not a telescope bug. Something when calling vim.cmd.normal while leaving a buffer or what? Really hard to say

Should I create a new issue for this? If so, clearly in neovim repo?

rasulomaroff avatar Apr 25 '24 04:04 rasulomaroff

so the magic problem is solved i guess, but it really was a nuisance, i had to press Esc a few times to go back to the real normal mode coz i was typing in normal mode, the keyword keys (d, y, h,j,k,l, o) worked like normal mode (dw, o, 5k) all of it was possible... It is solved ig in nightly but in 0.9.5 it still exists, opening any file with any picker still goes into insert mode, somethings i've noticed so far:

  • I use codeium.vim
  • I use the restore last cursor position autocmd
  • It does happen with the minimal config

daUnknownCoder avatar Apr 26 '24 12:04 daUnknownCoder

I'm having this issue when I use the fused layout example, is there any workaround? I removed the restore cursor position autocmd and codeium.nvim and neocodeium.nvim, it doesn't work.

https://github.com/nvim-telescope/telescope.nvim/wiki/Configuration-Recipes#fused-layout

This is the only workaround that seems to work for me

https://github.com/nvim-telescope/telescope.nvim/issues/2027#issuecomment-1510001730

Ajaymamtora avatar Jul 22 '24 19:07 Ajaymamtora

This is the workaround enhanced so when telescope pickers re-trigger telescope pickers, it doesnt set it back to normal mode like Telescope with no args. Also closes cmp if your buffer opens at the previous edit which might have a completion

  -- Create the Hacks group if it doesn't exist
  local group = vim.api.nvim_create_augroup("Hacks", { clear = true })

  -- Create the autocommand
  vim.api.nvim_create_autocmd("WinLeave", {
    callback = function()
      if vim.bo.filetype == "TelescopePrompt" and vim.fn.mode() == "i" then
        vim.schedule(function()
          local current_win = vim.api.nvim_get_current_win()
          local current_buf = vim.api.nvim_win_get_buf(current_win)
          local filetype = vim.api.nvim_buf_get_option(current_buf, "filetype")

          if filetype ~= "TelescopePrompt" and vim.fn.mode() == "i" then
            vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "i", false)
            -- Use pcall to safely require nvim-cmp
            local status, cmp = pcall(require, "cmp")
            if status and cmp and cmp.close then
              cmp.close()
            end
          end
        end)
      end
    end,
    group = group,
  })

Ajaymamtora avatar Jul 22 '24 21:07 Ajaymamtora

I can't say for sure because this behavior has heisenbug properties, it does seem to be some sort of race condition. But I removed a huge function i had configured for create_layout for telescope, and it seems to be helping.

Now telescope is super ugly for me again, but, I'm going to get rid of Telescope for many reasons (but the main one is that the telescope-fzf-native implementation DoSes me when I open it in my home directory, due to I/O lockup from not properly running asynchronously in a terminal, while fzf runs like a champ over millions of files) but this will hold me over until i can sink time into that.

unphased avatar Oct 08 '24 18:10 unphased