Vim Tips Wiki
Register
Advertisement

When using most tabbed editors, if you open a file for editing, and the file is already open in another tab, the editor will simply jump to that tab. There are very good reasons that Vim does not act this way, which are too numerous to go into detail about here – suffice it to say that there are many excellent features in Vim that would not be possible if it acted like "most tabbed editors". Nevertheless, it would be nice if Vim had this functionality when the user wishes to use it.

As discussed in VimTip135 and VimTip1242, using the 'switchbuf' option along with :sbuffer will almost get us there, because it will allow us to switch to the already-open tab of a file, if it is already loaded into a buffer. However, you cannot load new files into a buffer in this fashion, nor will tab completion work for file names (it will complete buffer names only).

The following commands in your vimrc will provide the Tfile and Wfile commands, to open a file in a new tab or window, or jump to whatever tab or window the file is currently open in if it has already been loaded. Filename completion is enabled on the commands, meaning that you can use <Tab> and the wildmenu (if enabled) to complete file names if desired.

command! -nargs=1 -bar -complete=file Tfile call OpenFileOrJump("tab", <q-args>)
command! -nargs=1 -bar -complete=file Wfile call OpenFileOrJump("", <q-args>)

function! OpenFileOrJump(tab, fileName)
  if bufexists(a:fileName)
    let sb_save = &switchbuf
    set switchbuf=usetab
    exec a:tab." sbuffer ".a:fileName
    let &switchbuf = sb_save
  else
    exec a:tab."new ".a:fileName
  endif
endfunction

Comments

I couldn't decide whether it would be better to just merge this tip into VimTip1242 and rename that page. If we keep this as a new tip, VimTip1242 can probably be merged into VimTip135. I would not have discovered the basis behind this tip (switchbuf and :sbuffer) unless I had read VimTip1242. --Fritzophrenic 18:03, 8 August 2008 (UTC)

Advertisement