I'm trying to implement a mapping for making the vim cursor jump to a pre-defined search pattern without overriding the current search, but it is falling short in multiple ways:
function! JumpToBlockEnd()
let search = @/
let @/ = '\%^\|^# ----------' "predefined search pattern
normal n
let @/ = search
endfunction
noremap m] :call JumpToBlockEnd()<CR>
- It isn't accepting a count. I would like to be able to do something like
3m]
to jump to the third occurrence of the pattern - It exits visual mode. If I want to highlight text from the current position to the intended jump pattern position, I want to be able to do
vm]
to continue with visual highlighting - This is a minor issue, but if there was a search pattern prior to executing the function that was called with reverse lookup
?
instead of forward lookup/
, it reassigns that pattern always to the forward lookup/
.
I'm making the above specific mapping to enable block-like editing and execution in vim, sort of like jupyter notebook. Here's the file I'm testing this function on:
x = 3
y = 4
# ---------- [block] ----------:
hi = 'hi'
hi = 'hi'
# ---------- [end] ----------:
hey = 'hey'
Edit: Based on the accepted answer below, I created a function that takes the pattern as an input and can also be passed flags, enabling reverse search:
function! JumpToPattern(count, visual, pattern, flags)
if a:visual
normal! gv
endif
for _ in range(a:count)
call search(a:pattern, a:flags)
endfor
endfunction
nnoremap m] :<c-u>call JumpToPattern(v:count1, 0, '\%$\\|^# ----------', '')<cr>
xnoremap m] :<c-u>call JumpToPattern(v:count1, 1, '\%$\\|^# ----------', '')<cr>
nnoremap m[ :<c-u>call JumpToPattern(v:count1, 0, '\%^\\|^# ----------', 'b')<cr>
xnoremap m[ :<c-u>call JumpToPattern(v:count1, 1, '\%^\\|^# ----------', 'b')<cr>