Reputation: 960
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
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:
You can do multiple selections at a time too.
Upvotes: 1
Reputation: 28673
*
at the lines that are incorrect*
's beyond the correct positionEsc
to get out of multi cursor*
'sCtrl+Delete
Esc
to get out of multi cursorUpvotes: 1