2

I have a function that looks like this:

function Foo()
    normal! vi)
    '<,'>s/abc/def/g
endfunction

However, when I try to call it, I get "Mark not set" error. What is wrong? Shouldn't the first line set the visual marks?

1
  • I can't figure out why you've got a closing parenthesis after vi...
    – joharr
    May 5 at 9:39
3

The marks '< and '> are only set when you leave Visual mode.

When you're using Vim interactively, this happens naturally, as you use the : to start typing a "substitute" command Vim will leave Visual mode and enter command-line mode. But that's not the case when you're using normal! from a function.

You can add an <Esc> to leave Visual mode explicitely. You'll need :execute to encode the <Esc> inside a string.

function! Foo()
    execute "normal! vi)\<Esc>"
    '<,'>s/abc/def/g
endfunction

If desired, you can further improve your function to only replace matches of "abc" inside the selection (inside the (...) block) by additionally using the /\%V marker in your pattern, which only matches at positions inside your last Visual block:

function! Foo()
    execute "normal! vi)\<Esc>"
    '<,'>s/\%Vab\%Vc/def/g
endfunction

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.