Reputation: 936
I have mapped gn
to :lnext<cr>
; how can I keep pressing it to cycle thru the location list, i.e. go to first if at last location?
Thanks
Upvotes: 7
Views: 1746
Reputation: 196546
Here is a solution taken straight from my configuration:
" wrap :cnext/:cprevious and :lnext/:lprevious
function! WrapCommand(direction, prefix)
if a:direction == "up"
try
execute a:prefix . "previous"
catch /^Vim\%((\a\+)\)\=:E553/
execute a:prefix . "last"
catch /^Vim\%((\a\+)\)\=:E\%(776\|42\):/
endtry
elseif a:direction == "down"
try
execute a:prefix . "next"
catch /^Vim\%((\a\+)\)\=:E553/
execute a:prefix . "first"
catch /^Vim\%((\a\+)\)\=:E\%(776\|42\):/
endtry
endif
endfunction
" <Home> and <End> go up and down the quickfix list and wrap around
nnoremap <silent> <Home> :call WrapCommand('up', 'c')<CR>
nnoremap <silent> <End> :call WrapCommand('down', 'c')<CR>
" <C-Home> and <C-End> go up and down the location list and wrap around
nnoremap <silent> <C-Home> :call WrapCommand('up', 'l')<CR>
nnoremap <silent> <C-End> :call WrapCommand('down', 'l')<CR>
Upvotes: 8
Reputation: 45107
The secret is to use :try
and :catch
the same as you would in other languages. You are looking to catch the following errors E553
or E42
.
nnoremap ]l :try<bar>lnext<bar>catch /^Vim\%((\a\+)\)\=:E\%(553\<bar>42\):/<bar>lfirst<bar>endtry<cr>
The command was inspired by Tim Pope's unimpaired.vim plugin.
I would also recommend against mapping of gn
. The gn
command is very handy motion that actions on the search pattern. See :h gn
.
For more information see:
:h :try
:h E553
:h E42
:h :lnext
:h :lfirst
Upvotes: 9