user97662
user97662

Reputation: 960

Add different number of spaces to multiple lines so that each line has equal amount of characters

Is there an easy way to add spaces to multiple lines so that each line has equal amount of characters?

Motivation, say I want to add '*' at end of each line

/***************************
* This is line 1. *
* Line2. *
* May be line3. *
* For sure this is line 4. *
****************************/

Without using any custom format program, is there a way in VS code to add different number of spaces just before the last '*' like so:

/***************************
* This is line 1.          *
* Line2                    *
* May be line3             *
* For sure this is line 4. *
****************************/

Upvotes: 0

Views: 728

Answers (2)

Mark
Mark

Reputation: 181329

You can do this fairly simply with an extension I wrote, Find and Transform, because it allows you to use javascript or the vscode extension api in a replacement. So starting with this text:

/***************************
* This is line 1.
* Line2.
* May be line3.
* For sure this is line 4.
****************************/

you would make this keybinding (in your keybindings.json):

{
  "key": "alt+q",                    // whatever keybinding you want
  "command": "findInCurrentFile",
  "args": {
    
    "replace": [
      "$${",
        "const str = `${selectedText}`;",   // get the selected text
// since the selected text can contain newlines, surround the variable with backticks
        
        "let lineArray = str.split('\\n');",  // newlines must be double-escaped

        "let firstLineLength = lineArray[0].length;",

        "lineArray = lineArray.map((line, index) => {",
          "if (index === 0) return line;",
          "else if (line === lineArray.at(lineArray.length-1)) return line;",
          "else return `${line.padEnd(firstLineLength-1, ' ')}*`;",
        "});",

        "return lineArray.join('\\n');",

      "}$$"
    ]
  }
}

So the replacement is straightforward javascript which gets the selected text, splits it on the newlines and then uses the length of the first line to pad the other lines with spaces and then adds a * to the end of each line. It does nothing to the first or last line of the selection.

Demo:

pad selected lines with spaces and add asterisk

You can do multiple selections at a time too.

Upvotes: 1

rioV8
rioV8

Reputation: 28673

  • select all the * at the lines that are incorrect
  • add as much spaces as needed to get all *'s beyond the correct position
  • Esc to get out of multi cursor
  • Place Multi Cursor on all lines at the position where you want the *'s
  • press Ctrl+Delete
  • Esc to get out of multi cursor

Upvotes: 1

Related Questions