I have a window in vim opened (current file) and another one in split called [Scratch]. I want to check if the [Scratch] is open or not.

Any example is appreciated.


The problem with [Scratch] itself is that that's not really the name of a buffer, but just Vim telling you that this scratch buffer is actually unnamed...

It's much easier if you start with a named buffer and use bufadd() to create it. For example:

let bufnr = bufadd('MyFancyScratchBuffer')
execute 'sb' bufnr
setlocal buftype=nofile bufhidden=hide noswapfile
" Use `setlocal buflisted` if you want it
" to show up in `:ls` too.

Then at this point you can search for it by name, with:

let winid = bufwinid('MyFancyScratchBuffer')

And here you can look at winid. If it's -1, then that means the buffer is not loaded into a window (in the current tab!) So you can create a new split for it:

sb MyFancyScratchBuffer

Otherwise, you can just go to the window already open with that buffer:

call win_gotoid(winid)

An alternative to using bufadd() and naming your buffer is to save the buffer number for it as it's first created. For example:

if !get(g:, 'my_scratch_bufnr')
    " Create new scratch buffer and store
    " its buffer number in a global variable.
    setlocal buftype=nofile bufhidden=hide noswapfile
    let g:my_scratch_bufnr = bufnr()
    " Find if it's loaded in a window in current tab.
    let winid = bufwinid(g:my_scratch_bufnr)
    if winid < 0
        " It's not, so open it into a split.
        execute 'sb' g:my_scratch_bufnr
        " Already open, so go to that window.
        call win_gotoid(winid)

If you're writing your code in a plug-in file, then you can use s: variables for script-local variables rather than g: for global ones, that way you don't need to worry about name clashes with other plug-ins.


There are a few plugins that have started to use {name}://{whatever} to name scratch buffers (e.g. tags://patternsearched, tasks://..., ). This is kind of helpful when other plugins try to do things on buffers but wish to ignore scratch buffer. A typical example is a local-vimrc plugin that applies project configuration settings on every buffer under a certain directory.

Now we can also filter on &buftype==nofile to find scratch buffers as they usually tagged as such. It will help find scratch buffers, but not necessary point to the single scratch buffer you are looking for.

" will display the list of buffer numbers with a "nofile" buftype
:echo filter(range(1, bufnr('$')), 'getbufvar(v:val, "&buftype") == "nofile"')

By applying bufwinnr() on the results, you'll see if they are displayed (>=0) in a window or not (-1).

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.