vimtricks.wiki Concise Vim tricks, one at a time.

How do I open a file in a new tab or switch to it if it is already open?

Answer

:tab drop filename

Explanation

When working with many tabs, you often want to open a file — but only if it is not already open somewhere. If it is, you want to jump to that tab instead of creating a duplicate. The :tab drop command does exactly this: it switches to the tab containing the file if one exists, or opens it in a new tab if it does not.

How it works

  • :drop filename opens the file, reusing an existing window if it is already loaded in the current tab page
  • Adding :tab as a modifier makes it operate across all tab pages
  • If the file is found in any tab, Vim switches to that tab and window
  • If the file is not open anywhere, Vim opens it in a new tab

Example

You have three tabs open and want to edit utils.go:

:tab drop utils.go

If utils.go is already open in tab 2, Vim switches to tab 2. If it is not open, Vim creates a new tab with utils.go.

Tips

  • :drop without :tab searches only windows in the current tab page
  • You can combine with wildcards: :tab drop **/*.test.js (with wildmenu enabled)
  • Useful in mappings for quick project file switching: nnoremap <leader>u :tab drop utils.go<CR>
  • Requires the switchbuf option to include usetab for cross-tab switching without :tab modifier

Next

How do I ignore whitespace changes when using Vim's diff mode?