Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim - change up to and including searched string

Assuming I have the following code:

bool myCopiedFunc() {
    Some code that I've written;
    The cursor is on this line; <<<<<<<<<<<<<<
    if (something) {
        bool aValue;
        some of this is inside braces;
        return aValue;
    }
    if (somethingElse) {
        this is also inside braces;
        bool anotherValue;
        {
            more braces;
        }
        return anotherValue;
    }
    return false;
}

I decide I want to rewrite the remainder of the function, from the line with the cursor on it.

To replace up to a char on the same line, I can use ct<char> e.g. ct;
To replace up to and including a char on the same line I can use cf<char> e.g. cf;
To replace up to a string across multiple lines, I can use c/<string> e.g. c/return false
To replace up to and including a string across multiple lines, I can use... ?? e.g. ??

I can't just search for a semicolon, as there are an unknown number of them between the cursor and the end of the function, and counting them would be slow. I can't just search for a closing brace, as there are several blocks between the cursor and the end of the function, and counting all closing braces would be slow. With the help of code highlighting, I can easily see that the unique string I can search for is return false.

Is there an elegant solution to delete or change up to and including a string pattern?

I've already looked at a couple of related questions.

Make Vim treat forward search as "up to and including" has an accepted answer which doesn't answer my question.

In my case, I settled for deleting up to the search string, then separately deleting up to the semicolon, but it felt inefficient, and like it would have been quicker to just reach for the mouse. #firstworldproblems

like image 461
M_M Avatar asked Oct 16 '25 20:10

M_M


1 Answers

To replace up to and including a string across multiple lines, I can use... ?? e.g. ??

The / supports offsets.

In your case, you are gonna need the e offset, that is, c/foo/e.

You may want to know more details about "search offset":

:h offset
like image 60
Kent Avatar answered Oct 18 '25 17:10

Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!