nvim-telescope / telescope.nvim

Find, Filter, Preview, Pick. All lua, all the time.
MIT License
14.75k stars 807 forks source link

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

Open daUnknownCoder opened 3 months ago

daUnknownCoder commented 3 months ago

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,
  },
}
jamestrew commented 3 months ago

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.

daUnknownCoder commented 3 months ago

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

rasulomaroff commented 2 months ago

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:

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!

jamestrew commented 2 months ago

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 ```lua 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", "", ":Telescope find_files") 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

Nebell commented 2 months ago

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

daUnknownCoder commented 2 months ago

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?

Nebell commented 2 months ago

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
jamestrew commented 2 months ago

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.

rasulomaroff commented 2 months ago

@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).

daUnknownCoder commented 2 months ago

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

daUnknownCoder commented 2 months ago

@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,
          },
Nebell commented 2 months ago

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.

jamestrew commented 2 months ago

@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

rasulomaroff commented 2 months ago

@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

3. 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?
daUnknownCoder commented 2 months ago

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: