Vim: match next/previous line in search pattern

Viewed 459

I'm trying to practice my search patterns for ex commands and trying to do stuff I would usually do with macros using them, and I got stuck with one I'm not sure is possible.

I have some code that looks like this:

public myFunc (): any {
    return {};
}

And I'm trying to yank it with this command (with the cursor after the function):

:?\vpublic\s*\w+\s*\(.*\)\s*:\s*\w+\s*\{?;/}$/y

This works as expected and matches the function that I mentioned up there.

What I would like to do but haven't found a way is to ignore the first line and the last one (I just want the contents of the function). I suspect it is possible to do it somehow (maybe +/- search offsets?), but I haven't had any luck yet.

Does anyone know how to do this? Thanks!

2 Answers

Yes, this is a simple matter of adding the appropriate offsets (:help search-offset). You basically define a range with two searches (one upwards from the current position, one downwards from there): ?...?;/.../. To exclude the targets, you just add / subtract 1; this is done by appending the offset to the search: ?...?+1;/.../-1. Applied to your example:

:?\vpublic\s*\w+\s*\(.*\)\s*:\s*\w+\s*\{?+1;/}$/-1y

To insert carriage return (Enter) like below use Ctrl-v Enter

:normal ?public^Mjwyiw

Explanation

:normal  ............ in normal mode
?public ............. search backward for public
^M .................. Enter
j ................... move to the line below
yiw ................. yank inner word
Related