romgrk / barbar.nvim

The neovim tabline plugin.
2.23k stars 83 forks source link

[Question] Is it possible to replace the current tab? #390

Closed CimimUxMaio closed 1 year ago

CimimUxMaio commented 1 year ago

As the title suggests, I'd like to be able to choose whether to open a file in a new tab or in the same buffer. Is this possible to do with this plugin?

Many times I end up with a lot of different open tabs, so having this option to control how to open a new file would be nice.

Iron-E commented 1 year ago

There are a couple of things which will interest you:

  1. :h 'bufhidden': This controls the behavior of buffers that are not longer visible on your screen. If you want to, it is possible to make buffers you switch away from disappear automatically.
  2. You can use :e foo | execute "bdelete" . bufnr('#') to open a new buffer and close the last one. You can use :command or vim.api.nvim_create_user_command to turn that snippet into something easier to run.

Let me know if this helps.

CimimUxMaio commented 1 year ago

Thank you very much.

I made it into an user command and it works perfectly:

vim.api.nvim_create_user_command(
  "TabReplace",
  function(params)
    vim.cmd("e " .. params.args)
    vim.cmd [[execute "bdelete" . bufnr("#")]]
  end,
  { nargs = 1 }
)

I am trying to map this command to be used together with nvim-tree. The problem I am having now is that, if I understand correctly, since when the command is being called I am focused on nvim-tree's window, bufnr("#") does not return the active buffer. So I am getting the following: image

I understand this is not barbar related, but, do you know if there is a way to get the active buffer's number while focused on a different window such as nvim-tree's sidebar?

Iron-E commented 1 year ago

Something like this would work:

local current_buffer
local previous_buffer

vim.api.nvim_create_autocmd('BufEnter', {
  callback = function(event)
    if vim.api.nvim_buf_get_option(event.buf, 'buflisted') then
      previous_buffer = current_buffer
      current_buffer = event.file
    end
  end,
  group = vim.api.nvim_create_augroup('config', {clear = false}),
})

vim.api.nvim_create_user_command(
  "TabReplace",
  function(params)
    vim.cmd.edit(params.args) -- or `vim.cmd('edit ' .. params.args)`
    if previous_buffer then
      vim.cmd.BufferClose(previous_buffer) -- or `vim.cmd('BufferClose ' .. previous_buffer)`
      previous_buffer = nil
    end
  end,
  {complete = 'file', force = true, nargs = 1}
)
CimimUxMaio commented 1 year ago

It is perfect. Thanks a lot for the help and the time.