0

As title. Is it possible to change the current buffer by vimscript to the (only) [No Name] buffer?

I need these tools:

  • an API to return all (loaded) buffers
  • loop through each of them
    • if the buffer is a No Name-buffer, then record its buffer number
  • an API to edit that buffer from the current window.

I put emphasis on "the only" is that what I want to do is to keep only one No Name-buffer, so there won't be many No Name-buffers that spam out there. To do so my idea is that whenever I want to open a new No Name-buffer use a script to check if there is one: if so switch to it, if not then really create one.

2
  • Use vim however you want, but to me this would be odd. When I run :new or :enew, I want a new buffer (not to automatically re-use an existing one). A :Scratch command that re-uses the same buffer might be interesting, though.
    – D. Ben Knoble
    Jan 10, 2022 at 15:49
  • @D.BenKnoble: Just to provide context: I just created a plugin (while in Lua). In the implementation I need to use :enew to substitute the current buffer to a No Name, while I don't want to be spammed by many No Name buffers. Jan 10, 2022 at 18:03

2 Answers 2

2

an API to return all (loaded) buffers

:h getbufinfo()

loop through each of them

:h filter()

if the buffer is a No Name-buffer

:echo empty(bufname(N))
:echo empty(getbufinfo(N)[0].name)

an API to edit that buffer on the current window (split) by that buffer number

:h :buffer

0

This is the Lua version:

  • an API to return all (loaded) buffers
  • loop through each of them
    • if the buffer is a No Name-buffer, then record its buffer number
local function is_no_name_buf(buf)
  return
    vim.api.nvim_buf_is_loaded(buf)
    and vim.api.nvim_buf_get_option(buf, 'buflisted')
    and vim.api.nvim_buf_get_name(buf) == ''
    and vim.api.nvim_buf_get_option(buf, 'buftype') == ''
    and vim.api.nvim_buf_get_option(buf, 'filetype') == ''
end

local all_no_name = vim.tbl_filter(is_no_name_buf, vim.api.nvim_list_bufs())

an API to edit that buffer from the current window.

vim.api.nvim_win_set_buf(win, buf_to_put)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.