Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
daUnknownCoder opened this issue Mar 20, 2024 · 15 comments
Open

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

daUnknownCoder opened this issue Mar 20, 2024 · 15 comments
Labels
bug Something isn't working not reproducible

Comments

@daUnknownCoder
Copy link

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 daUnknownCoder added the bug Something isn't working label Mar 20, 2024
@jamestrew
Copy link
Contributor

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
Copy link
Author

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

@rasulomaroff
Copy link

rasulomaroff commented Apr 21, 2024

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!

@jamestrew
Copy link
Contributor

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.

telescope-insert.mp4
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. #2766
I'm pretty sure this is the cause of your issue @daUnknownCoder

@Nebell
Copy link

Nebell commented Apr 22, 2024

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

@daUnknownCoder
Copy link
Author

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
Copy link

Nebell commented Apr 23, 2024

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
Copy link
Contributor

Again, this seems like the same issue from #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
Copy link

@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
Copy link
Author

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

@daUnknownCoder
Copy link
Author

@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
Copy link

Nebell commented Apr 23, 2024

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
Copy link
Contributor

@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 (#2995 (comment))

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 neovim/neovim#27038

@rasulomaroff
Copy link

rasulomaroff commented Apr 25, 2024

@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?

@daUnknownCoder
Copy link
Author

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 daUnknownCoder changed the title Any buffer opened through the pickers open in magic mode [custom Normal + Insert], can't use telescope due to that... Any buffer opened through the pickers open in Insert mode ... Apr 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working not reproducible
Projects
None yet
Development

No branches or pull requests

4 participants