1

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?

  • 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 :/ – Christian Brabandt Apr 22 at 6:24
  • 2
    I did it like this for now, but meh – Martin Tournoij Apr 22 at 8:08
0

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

| improve this answer | |

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.