Raul Durand
Raul Durand

Reputation: 93

vimscript: How to substitute in current selection?

Inside a function I can use:

s/foo/bar/ge

but it only substitutes the current line. I'd like to substitute in the current selection. I tried

'<,'>s/foo/bar/ge

with no success.

Any help is appreciated.

Upvotes: 0

Views: 455

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172510

This is perfectly fine:

fun! Foo()
    '<,'>s/foo/bar/ge
endfun

You may get E20: Mark not set when no visual selection has yet been established, though. For the '<,'> marks to be defined, visual mode must have been left already; but this is also accomplished by the : command that is used to invoke the function, so it shouldn't be a problem (except for special cases like :help :map-<expr>). If you establish the visual selection only within the function, you need to leave it. Instead of

:normal! Vjj

append a <Esc> to leave visual mode (and set the marks):

:execute normal! "Vjj\<Esc>"

Note that hard-coding the selection often is bad style; you usually want a mapping to work either on the selection, or [count] lines, or the current line / entire buffer. For that, it's advisable to define the function with the range attribute; see :help function-range-example for details.

Upvotes: 2

Related Questions