The existing answer which suggests using Visual mode and \%V
is good. But since you mentioned line ranges and directional searches I figured it worth mentioning a couple other options, one of which allows relative line ranges.
Absolute line ranges in search can be specified with the \%l
pattern atoms \%>###l
and \%<###l
.
Example:
/\%>100lfoo\%<200l
This will search for "foo" between lines 100 and 200.
Searching the next 200 lines starting with, let's say, a current line number of 50:
/foo\%<250l
If you wanted to do something like that programmatically, in a mapping for example, this would do the same thing but for any current line number:
:exe '/foo\%<' . (line(".") + 200) . 'l'
Note that these operations are exclusive. Referring to the first example, \%<200l
means "less than 200" just like the <
suggests so use /\%>99lfoo\%<201l
if you want to search lines 100 and 200 as well.*
What if you want to use relative line ranges without resorting to anything programmatic? By relative I mean a range like -10,+20
(start 10 lines before the current line and end 20 lines beyond it). For that you'll need to use a bit of a trick: the substitute command with the c
flag (normally used to manually confirm each potential substitution).
Example:
:-10,+20s/foo//gc
Upon a match you will be asked to enter a one-character command that determines what happens next. Under typical circumstances you'd be deciding whether to do the substitution or not but in this case only two commands are of interest to us: n
to continue searching (without substitution!) and q
to quit searching.
You can, of course, use this method for absolute line ranges, too, if you prefer it to the \%l
searches described above.
:help pattern
. There are also plugins (Narrow Region comes to mind) to let you edit a small portion of the file.