7

When using split windows in VIM, sometimes I create new split of a file already opened in another split (typically with plugins that open a unit test for given file in a new split).

Is there a way how to remap split command so that it checks whether the file is already opened before splitting, and if it is, give a focus on it?

iNecas
  • 1,743
  • 1
  • 13
  • 16

3 Answers3

10

You can't remap the existing split command, as far as I know, but you can achieve the same same effect by writing a new function Split and then using a command-mode abbreviation (cabbrev).

Here's a function/mapping that should do what you want.

function! MySplit( fname )
    let bufnum=bufnr(expand(a:fname))
    let winnum=bufwinnr(bufnum)
    if winnum != -1
        " Jump to existing split
        exe winnum . "wincmd w"
    else
        " Make new split as usual
        exe "split " . a:fname
    endif
endfunction


command! -nargs=1 Split :call MySplit("<args>")
cabbrev split Split

Note that this will only "check" for existing splits in the current tab, and hidden buffers are ignored. (However, it shouldn't be too difficult to add more cases to enhance this functionality.)

Prince Goulash
  • 15,295
  • 2
  • 46
  • 47
3

An alternative would be using :drop {file}.

Edit the first {file} in a window.
- If the file is already open in a window change to that
    window.
- If the file is not open in a window edit the file in the
    current window.  If the current buffer can't be abandoned,
    the window is split first.

Also using :sb to switch buffers might also be of use. See vim: move to buffer?

For more information:

:h :drop
:h :sb
:h 'swb'
Community
  • 1
  • 1
Peter Rincker
  • 43,539
  • 9
  • 74
  • 101
0

That's one of the features of searchInRuntime.

:GSplit and :GVSplit can be renamed, they support filename completion, and they will ask which file to open when several match the pattern in &path.

Luc Hermitte
  • 31,979
  • 7
  • 69
  • 83
  • Sounds like a wonderful plugin, do you know how it can be installed by vundle or pathogen? – Erik Sep 26 '12 at 18:20
  • I have no idea. I encourage to use vim-addon-manager instead. Unlike its competitors, VAM handles dependencies and all my plugins depend on at list one other (library) plugin (that I'm also maintaining). In the end, it's easier this way. Otherwise, you'll have to give the URL of the SVN repositories to vundle or pathogen. – Luc Hermitte Sep 27 '12 at 13:57