I am trying to write a couple of simple functions to find the next and previous links in Vimwiki and move to them. Links in Vimwiki are indicated with the syntax [[link to something]]
. Since I only want to move the cursor and I want to avoid highlighting all matches, I am using the functions searchpos()
and setpos()
instead of the usual /
and ?
. searchpos()
has the same options as search()
, so I imagine they work equivalently.
I have written the following:
function! MoveToNextLink()
" Get line number and column
let [lnum, col] = searchpos('\[\[.\{-}\]\]', 'nz')
" Move cursor
call setpos('.', [0, lnum, col, 0])
endfunction
function! MoveToPrevLink()
" Get line number and column
let [lnum, col] = searchpos('\[\[.\{-}\]\]', 'bnz')
" Move cursor
call setpos('.', [0, lnum, col, 0])
endfunction
nnoremap <silent> <C-l> :call MoveToNextLink()<CR>
nnoremap <silent> <C-h> :call MoveToPrevLink()<CR>
The options for search()
are: n
, that indicates to not move the cursor; b
, to search backwards; and z
, for starting the search at the cursor position rather than at the beginning or the end of the line.
For the most part these mappings seem to work. However, I run into problems when there are multiple matches [[link to something]]
in the current line:
- The forward function
MoveToNextLink
works in its current form. Originally, I did not have thez
option and it didn't work because all searches started at the beginning of the line, so only the first match was found, regardless of the position of the cursor in the line. Adding thez
option fixed this, as expected. - The backward function
MoveToPrevLink
does not work. Similarly to the behaviour ofMoveToNextLink
without thez
option, it only finds the last match in the current line, suggesting thatsearch()
starts looking at the end of the line and keeps searching backwards from there. Adding thez
option worked as intended in the forward direction, but did not change anything in the backward direction, which was surprising.
Why is this? Am I doing something wrong, or is there a bug/inconsistency in Vim such that the z
option does not work for backward search?