Custom VIM functions to navigate buffers by class names
08.08.21So. I know the title is not the greatest. Sorry. :-) Here's what I'm trying to do in GVIM:
- Navigate from the current buffer to another buffer (by selecting a word that can be interpreted as the name of the file I want to go to).
- Keep a list of where I've been.
- Navigate back to previous files - in reverse order of when I saw them.
- Use simple controls that make sense in navigating forward and backward.
In the end I used C-LeftMouse (Control + Left click) to navigate forward, and C-RightMouse to navigate backward. I know it's a bit backward, but it follows navigating forward with the left mouse when you're in a web page. The code I put in my _vimrc (the underscore comes from using GVIM on msWin) is shown below:
let s:bufNameList =  function PushFileJump() if len(s:bufNameList) == 0 let prev = bufname("#") call add(s:bufNameList, strpart( prev, 0, stridx(prev,".") ) ) endif call add(s:bufNameList, getreg('z') ) endfunction function PopFileJump() if len(s:bufNameList) > 0 call remove(s:bufNameList,-1) call setreg( 'z', get(s:bufNameList,-1) ) endif endfunction map! <C-LeftMouse> <LeftMouse><Esc>b"zye:b<Space><C-r>z.<C-q> <CR>:call PushFileJump()<CR> map <C-LeftMouse> <LeftMouse>b"zye:b<Space><C-r>z.<C-q> <CR>:call PushFileJump()<CR> map! <C-RightMouse> <Esc>:call PopFileJump()<CR>:b<Space><C-r>z.<C-q> <CR> map <C-RightMouse> :call PopFileJump()<CR>:b<Space><C-r>z.<C-q> <CR>
To explain a bit, I used a List, and carried the file I want to go to in the z register. C-LeftMouse copies the word I clicked on into the z register, navigates to that word as a file, and then calls PushFileJump to add the new file into the List.
The only reason why PushFileJump is a bit more complex than that is because I need to add the previous buffers name to the List if it was the file I started navigating at.
C-RightMouse is simpler. It calls PopFileJump, which removes the current buffer name and sets the z register to the last buffer name in the List. The rest of the mapped command for C-RightMouse finishes using the z register to navigate to the previously seen file.
This should allow me to quickly navigate forward and backward - but it throws away anything I back over... so there is still some room for improvement.