Marius
Marius

Reputation: 1998

How to remove empty lines in VS Code?

Is there a better way to remove the empty rows? Currently I'm deleting them manually but it's a pain.

VSC

Upvotes: 0

Views: 3253

Answers (3)

Mark
Mark

Reputation: 180641

You can do this with a macro as you wished for in your answer. You will need a macro extension: multiCommand.

In your settings:

  "multiCommand.commands": [

    {
      "command": "multiCommand.removeEmptyLines",
      // "interval": 50,
      "sequence": [
        {
          "command": "type",
          "args": {
            "text": "^\\n"
          }
        },
        "cursorHomeSelect",
        "editor.action.clipboardCutAction",
        "editor.action.startFindReplaceAction",
        "editor.action.clipboardPasteAction",

        //  focus to the replace input
        "editor.action.startFindReplaceAction",

        // clear the replace input, if any
        "editor.action.clipboardCutAction",

        "editor.action.replaceAll"
      ]
    }
  ]

It is tricky because you cannot directly write into the find widget (even with a longer delay interval). But you can print out what you want to find, "^\\n", select it, cut it and open the find widget and it will auto-populate the find field with the clipboard contents. [Note the extra escape "^\n" is necessary here.]

Then there are some more commands to clear any pre-existing replace text you may have in the replace input field.

Also, as you know, you must have the "Use Regular Expression" option toggled on. Unfortunately, that is a toggle, there is no command for simply turning it on. So the macro above can't invoke the toggle command - if you already had it on it would toggle off and the find would not work. So this macro must assume you already have "Use Regular Expression" option toggled on. I always leave it on and almost never find I need to toggle it off temporarily.

In your keybindings.json, set up whatever keybinding you would like:

{
    "key": "ctrl+alt+u",
    "command": "multiCommand.removeEmptyLines",
},

and then invoke that keybinding on any open line and it will trigger the macro - removing all open lines in the file (except any empty line at the very end of the file because there is no \n at the end of it).

Upvotes: 1

Alex
Alex

Reputation: 67473

Here's an extension Remove empty lines

enter image description here

Upvotes: 0

Marius
Marius

Reputation: 1998

Found a way is to use this in Find/Replace

^$\n

Also make sure to enable: Regular Expression

But i wish there was a script to run this.

Upvotes: 1

Related Questions