switch tab with vimscript?

2019-08-21 19:54发布

I want do something like this:

  1. check if a split named __Potion_Bytecode__ exists
  2. if exists, switch to the split with name
  3. if not, new a split named __Potion_Bytecode__

Here is code I am now doing:

function! PotionShowBytecode()
    " Here I need to check if split exists
    "  open a new split and set it up
    vsplit __Potion_Bytecode__
    normal! ggdG
endfunction

1条回答
叛逆
2楼-- · 2019-08-21 20:30

In lh-vim-lib, I have lh#buffer#jump() that does exactly that. It relies on another function to find a window where the buffer could be.

" Function: lh#buffer#find({filename}) {{{3
" If {filename} is opened in a window, jump to this window, otherwise return -1
function! lh#buffer#find(filename)
  let b = bufwinnr(a:filename) " find the window where the buffer is opened
  if b == -1 | return b | endif
  exe b.'wincmd w' " jump to the window found
  return b
endfunction

function! lh#buffer#jump(filename, cmd)
  let b = lh#buffer#find(a:filename)
  if b != -1 | return b | endif
  call lh#window#create_window_with(a:cmd . ' ' . a:filename)
  return winnr()
endfunction

Which uses another function to work around the extremely annoying E36:

" Function: lh#window#create_window_with(cmd) {{{3
" Since a few versions, vim throws a lot of E36 errors around:
" everytime we try to split from a windows where its height equals &winheight
" (the minimum height)
function! lh#window#create_window_with(cmd) abort
  try
    exe a:cmd
  catch /E36:/
    " Try again after an increase of the current window height
    resize +1
    exe a:cmd
  endtry
endfunction

If you want to work with tabs, you'll have to use tab* functions instead.

查看更多
登录 后发表回答