2

I'm looking how I might use "Operator-Pending" mode to make a custom motion that allows change, delete or visual selection of a pattern match under the current cursor position.

In short, after searching for a pattern I would like to place the cursor on any match and type "dim" to delete the whole match (or "cim" to change).

I came up with this, which doesn't quite work:

function! MoveOverMatch()
    " Save last search pattern
    let reset = @/
    " Move to start of match
    call search(@/,"b")
    " Move to end of match
    call search(@/,"e")
    " Advance one more character
    normal! l
    " Restore search pattern
    let @/ = reset
endfunction

omap im :call MoveOverMatch()<CR>
xmap im :call MoveOverMatch()<CR>

The omap will work if the cursor is at the start of the match, but place the cursor anywhere in the middle of the match and it will delete from that position.

I thought the search backwards might take care of that, but apparently not.

The xmap in visual mode doesn't work at all. I was hoping that typing "vim" would visually select the match. In fact the cursor jumps to the previous match and cancels visual mode.

Any pointers very much welcome.

Update:

I found part of the puzzle. The following fixes for "cim" and "dim":

function! MoveOverMatch()
    " Save last search pattern
    let reset = @/
    " Move to start of match
    call search(@/,"b")
    normal! v
    " Move to end of match
    call search(@/,"e")
    " Advance one more character
    normal! l
    " Restore search pattern
    let @/ = reset
endfunction

Entering visual mode after the backwards search seems to do the trick for "change" and "delete".

Visual mode still doesn't work, so help is still appreciated.

5

If I understood your description, the built-in gn and gN already do what you are trying to do:

/foo<CR>
dgn
cgn
vgn
ygn

See :help gn.


Bonus mappings:

nnoremap <key>      *``cgn
nnoremap <otherkey> #``cgN

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.