2

I know that I can replace characters in a linespan via something to the effect of :300,305s/foo/bar/g But when I'm deep in the code, and I know that I just want to replace in the next five lines, I'm wasting both keystrokes and time looking up the line numbers by setting absolute line numbers.

Is there a way to perform a substitute based on a relative linespan, something to the effect of (trigger warning: pseudo-vim) :+5s/foo/bar/g?

2 Answers 2

3

I actually figured it out a few minutes later: define a range based on current location . and relative line number +{} or -{}, e.g. :.,+5s/foo/bar/g.

I'll leave the question up anyway for the sake of anyone else who might want to know how to do that.

2
  • 2
    See :help [range] for more fun things :) You can leave off the . in :,+5 if that makes typing easier.
    – D. Ben Knoble
    Commented Aug 2, 2022 at 14:04
  • 3
    another way is v5j: to automatically populate the range, which is roughly the same amount of typing
    – D. Ben Knoble
    Commented Aug 2, 2022 at 14:04
1

I prefer using Visual Line mode for this.

  1. Enter Visual Line mode with V. This will highlight the current line.
  2. 5j to also select the next five lines.
  3. Enter command line mode with : and the command line will appear like: :'<,'> which is the range notation for the visual selection.
  4. Add your substitution command after the range.
2
  • 1
    strictly speaking, any : command you run from any visual mode is linewise and is populated with the range :'<,'>, so you can save yourself a shift with v5j:
    – D. Ben Knoble
    Commented Aug 3, 2022 at 12:57
  • I doubted this initially, but you're exactly right because ranges work line-by-line. Commented Aug 3, 2022 at 18:48

Your Answer

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

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