rmagatti / goto-preview

A small Neovim plugin for previewing definitions using floating windows.
Apache License 2.0
779 stars 27 forks source link

[FEATURE] Close floating window when cursor leaves buffer #112

Open Leandros opened 8 months ago

Leandros commented 8 months ago

Is your feature request related to a problem? Please describe. Often I'd like to take a peek at an implementation, and close the opened floating window from goto-preview when I don't have it focused anymore. It would be great if unfocusing it could close it automatically.

Describe the solution you'd like An option in the config to close floating buffers when leaving focus.

Describe alternatives you've considered I've tried implementing it myself using the post_open_hook, but I didn't manage to get a working solution.

post_open_hook = function(bufid, win)
  print('post_open_hook | bufid: ' .. vim.inspect(bufid) .. ' | win: ' .. vim.inspect(win))
  vim.api.nvim_create_autocmd({'WinLeave'}, {
    buffer = bufid,
    callback = function(ev)
      vim.api.nvim_win_close(win, false)
    end,
  })
end,

Thank you!

Leandros commented 8 months ago

The above version works the first time, but the second time the following errors occur:

image
vladimir-popov commented 6 months ago

@Leandros try to return true from your callback. It should delete autocmd.

And also, I think it's useful to mark the buffer as nomodifiable in the preview window. Together with closing the preview window on WinLeave event, it works well for me:

post_open_hook = function(buf, win)
            local orig_state = vim.api.nvim_buf_get_option(buf, 'modifiable')
            vim.api.nvim_buf_set_option(buf, 'modifiable', false)
            vim.api.nvim_create_autocmd({ 'WinLeave' }, {
                buffer = buf,
                callback = function()
                    vim.api.nvim_win_close(win, false)
                    vim.api.nvim_buf_set_option(buf, 'modifiable', orig_state)
                    return true
                end,
            })
        end
rmagatti commented 6 months ago

@vladimir-popov's solution is the way to go. The current ergonomics of goto-preview are exactly how I want them to be for my use-case. Hooks are provided so everyone else can implement their own flavour of behaviours. An idea would be to add community hooks to the repo that are maintained by the community that can be more easily set than copying over hook implementations all over. I'll give this some more thought