Search code examples
pythonpython-2.7pycharm

Delete opening and closing quotes (or brackets,braces,etc) at once


The opening and closing quotes (or brackets, braces etc) are highlighted in PyCharm(and other editors). So this means it can identify the pair.

Now, is there a way to delete both the quotes at once (or brackets, braces etc) when either of the opening or closing quotes are deleted, Since it identifies the pair?

For eg. I want this in one keyboard action (by both cases either deleting the opening or closing square bracket):
From this: [[a for a in l1 if a!=0]]
To this: [a for a in l1 if a!=0]

I googled and searched on SO but couldn't find it.


Solution

  • I would do that with macros.

    1. Place the cursor after the closing bracket:
      [[a for a in l1 if a!=0]]
    #                          ^ - place cursor here
    
    1. Go to Edit | Macros | Start Macro Recording

    Press the following:

    1. CtrlShiftM - "Move Caret to Matching brace" action.
      [[a for a in l1 if a!=0]]
    #^ - it will jump here
    
    1. Del or select action "Delete to Word End".
      [a for a in l1 if a!=0]]
    #^ - the first bracket was deleted
    
    1. CtrlShiftBackspace - "Last Edit Location" (assuming you edited there).
      [a for a in l1 if a!=0]]
    #                         ^ - will jump here
    
    1. Backspace or "Delete to Word Start"
      [a for a in l1 if a!=0]
    #                        ^ - deleted the paired closing bracket
    

    Now need to stop macro recording.

    1. Go to Edit | Macros | Start Macro Recording
    2. Give a name to your macros
    3. Optionally, assign shortcut to it.

    Links:
    Macros documentation.
    Source code navigation documentation.
    Other suggestion to use Code|Unwrap/Remove. It will not work in some cases. For example, if you have incorrect code, the IDE cannot wrap it.