Delete everything between two brackets in Vim, including newlines
Asked Answered
M

5

10

Say I have the following python array literal:

def f():
    arr = [
        1,          
        2,
        3   
    ]  

I want to delete everything in the brackets so that it becomes this:

def f():
    arr = [] 

How can I do that with minimal commands in vim?


These are some of my attempts:

  • Using di] will delete the text, but not the empty newlines, leaving a lot of whitespace I'd have to delete:

    def f():
        arr = [         
        ]
    
  • Using da] will delete the newlines, but also the brackets:

    def f():
        arr =
    
Mathilda answered 24/10, 2016 at 0:7 Comment(0)
W
9

You can simply do:

ca[[]<Esc>

or:

ca][]<Esc>

See :help text-objects.

Wheresoever answered 24/10, 2016 at 6:8 Comment(1)
Just doing ci[ worked better for me. Left the brackets.Rarity
A
7

With your cursor on the first opening bracket ([), press V, followed by %. This will select the block which you then can join J, followed by di[.

Alight answered 24/10, 2016 at 0:19 Comment(1)
Is it easy to do this a million times?Menadione
C
2

Select the lines in visual mode (v) and use J to remove newlines. Then use di[.

Or if there are many lines, di[ first, after which you move the cursor to top line and then J. This will potentially leave a space between the brackets which has to be removed with x.

Cristobal answered 24/10, 2016 at 0:12 Comment(2)
That's pretty good. I can va] to select every line between the brackets, J to join then, then di] to delete the array contents. So va]Jdi] overall.Mathilda
That's a neat way too do it too.Cristobal
Y
0

I find using a code formatter shortcut saves a lot of time

If you install vim prettier, you could do di[ <leader>p

Using the formatter in JS for example means I don't have to remove extra spacing, jump to end of line to insert ;, or fix indenting etc

Yaw answered 16/1, 2021 at 22:58 Comment(0)
N
0

You can use a regex like this:

:%s/\[\_.\{-}\]/[]/g

\_. to match any character including newline, and \{-} is the non-greedy command

Norrie answered 27/1 at 1:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.