I know that with commands like sbuffer you can create a new buffer and display it in a split window, and commands like enew can create a new buffer in the current window. But is it possible to not display the buffer in any way but just create a hidden buffer right away?

My use case is that I have a python class that should return a vim.buffer object to be processed. The display happens differently depending on conditions in the calling object. So I need a buffer that I can load, and write stuff into (it's a buffer not associated with any file, so it's a nofile buftype), but that is not displayed until I command to load into the current or some other window.


I'm not aware that you can create a hidden unnamed buffer.

But you can create a hidden (even unlisted) buffer with some fancy name and use that.

In VimScript:

let g:myscratch = bufnr("my-fancy-name", 1)
call setbufvar(g:myscratch, "&buftype", "nofile")

The first line returns the buffer number for the buffer named "my-fancy-name". If the buffer does not exist, it is created as hidden, unlisted buffer. So you don't see it with :ls.

The second line sets the buffer as nofile.

The buffer is created, but (for whatever reasons) you cannot write to it. You first have to activate it for a moment: [I didn't find another way to make it "writable".]

let curbuf = bufnr("")
execute g:myscratch . "buffer"
execute curbuf . "buffer"

If you do this short switch of buffers in a function, you won't see it (screen is not updated).

After that you can write to it with setbufline(g:myscratch, ...) and appendbufline(g:myscratch, ...).

To bring it to view:

execute g:myscratch . "buffer"

To finally delete it use bwipeout:

execute g:myscratch . "bwipeout"
  • Additionally i think bufadd can buffers without switching to them. – D. Ben Knoble Apr 11 at 13:15
  • @D.BenKnoble its the command :badd, but then you need a following bufnr()` to get the number for appendbufline() etc. – Ralf Apr 11 at 14:16
  • ah that makes sense i forgot about the writing part – D. Ben Knoble Apr 11 at 14:16
  • Can you link or explain why the short switch won't actually appear on the screen? When is the screen actually updated then? – SalmonKiller Apr 11 at 18:07
  • @SalmonKiller Redrawing the screen is a expensive operation, so Vim will try to do it only when needed. I'm not aware where this is documented. But perhaps someone else knows more. – Ralf Apr 11 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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