shawnl
shawnl

Reputation: 1939

Vim delete parent parenthesis and reindent child

I'm trying to go from here:

const f = function() {
    if (exists) { // delete this 
        const a = 'apple'
    }
}

to:

const f = function() {
    const a = 'apple'
}

What's the fastest way to delete and reindent everything in between?

Upvotes: 1

Views: 167

Answers (3)

anon
anon

Reputation:

Great answers all around, and, as pointed out, you can always map these keys to a shortcut. If you'd like to try a slightly more generic solution, you could check my "deleft" plugin: https://github.com/AndrewRadev/deleft.vim

Upvotes: 0

Matt
Matt

Reputation: 15081

Assuming that cursor is inside the braces; any number of lines and nested operators; "else"-branch is not supported:

[{"_dd<]}']"_dd

Explanation:

[{ go to previous unmatched brace

"_dd delete the "{"-line (now the cursor is in the first line of the block)

<]} decrease identation until the next unmatched "}"

'] go to the last changed line (i.e. "}"-line)

"_dd and delete it

If the cursor is initially set on the "{"-line and you don't care for 1-9 registers, the command can be simplified to dd<]}']dd

Upvotes: 2

Stun Brick
Stun Brick

Reputation: 1244

Assuming your cursor is somewhere on the line containing const a

?{^M%dd^Odd== (where ^M is you hitting the Enter key and ^O is you hitting Ctrl+O).

Broken down this is:
?{^M - search backwards/upwards for the opening brace
% - jump to the corresponding brace (closing brace)
dd - delete the current line
^O - jump to previous location (the opening brace)
dd - delete the line
== - indent current line

You don't need a special macro or function or anything to do this since vim gives you all the powerful text manipulation tools to do the task. If you find yourself doing this an awful lot then you could always map it to a key combination if you want.

The above only works for single lines inside curly braces, but the one below will work for multiple lines (again assuming you are on some line inside the curly braces)

<i{0f{%dd^Odd I'll leave you to figure out how this one works. Type the command slowly and see what happens.

Upvotes: 1

Related Questions