2

I have the following line:

return err

And would like to replace that to:

return fmt.Errorf(": %w", \1)

Which is done easily with something like:

:s/return \v(\k+)/return fmt.Errorf(": %w", \1)/

The problem with this is that after the :s my cursor position will be at the start of the line (the r in return), while it would be much more useful to place it on the :.

Is there any way to set the cursor position in the substitute replace pattern?

2
  • 1
    I don't think so. Only workaround I can imagine would be to define a custom command that performs the :s command, using a sub-replace expression, that calls a function \=MyReplace that drops a mark anywhere on the pattern and the command would then after successful substitution move to that mark. Sounds complicated :/ Apr 22, 2020 at 6:24
  • 2
    I did it like this for now, but meh Apr 22, 2020 at 8:08

1 Answer 1

1

Unfortuately, that's not possible, but hey, vimscript is here to help you:

function! Sub(search, replacement, flags)
    norm!^

    let pos = searchpos(a:search, a:flags.'n')

    exe ':s/'.a:search.'/'.a:replacement.'/'.a:flags

    call setpos('.', [0] + pos + [0])

endfunction

This function acts exactly like :s/.../.../... except it leaves your cursor on the replaced part

It's not perfect, especially if you're used to type :s/.... to replace, but It gets the job done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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