I am trying to write a Vim function which should make the window go to the previous open buffer.
How can I do it from the command line? My first idea was to find out some CTRL-O command line alternative.
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.Sign up to join this community
The jumplist is not the best way to do buffer navigation. Vim has a great number of buffer navigation tools which are probably better used for this task.
<c-6>- jump to the alternative file or if providing a count to a certain buffer number. See
:b- jump to a specific buffer. Takes buffer number or partial filename. See
:sb- split variant of
:buffers- list opened buffers. See
#used to represent the alternative file which is often the previous buffer. e.g.
nnoremap <leader>b :ls<cr>:b<space>
You can also use
ctrl + o to go to the previous buffer, going backwards. You can keep pressing the same command to go to the previous, previous buffer.
You can also use
ctrl + i to go to the next buffer, going forward. I.e, if you had pressed
ctrl + o to go to the previous buffer, you can use
ctrl + i to go to the first/original buffer.
Recently someone asked a similar question on Reddit and I wrote a piece of code to answer it. Today I've found this question in a review queue so that is the opportunity to share my code in a late answer.
The idea is to create two new mappings
<leader><c-i> which will execute respectively
<c-i> until the buffer has changed or until there is no more jumps available in the jumplist. It seems to be working fine but there might be some edge cases that are not handled well.
" In ~/.vim/autoload/jumps.vim " Repeat <C-o> or <C-i> jump commands until the current buffer changes " or no other jumps are available function jumps#fileCO(up) let current_buffer = bufnr() " Get the jump list and parse the position of the first jump in the list " if the number is zero then we reached the top redir => jumps_output silent jumps redir END let lastjump = split(jumps_output, '\n') let lastjumppos = str2nr(matchstr(lastjump, '\d\+')) " Execute the jump command until the buffer changes or there are no more jumps while bufnr() == current_buffer && lastjumppos > 0 if a:up == v:true execute "normal! \<c-o>" else " \<CR> is an ugly hack to do nothing but let the normal command " see that it has an argument execute "normal! \<CR>\<c-i>" endif let lastjumppos = lastjumppos - 1 endwhile endfunction " In ~/.vimrc nnoremap <silent> <leader><C-o> :call jumps#fileCO(v:true)<CR> nnoremap <silent> <leader><C-i> :call jumps#fileCO(v:false)<CR>
Plug https://github.com/inkarkat/vim-EnhancedJumps defines
<leader><c-o> as a jump to the previous position in previous buffer. Similarly
<leader><c-i>. It works.