A question:
If you copy a code sample that uses two-space indentation and you want to convert it to four-space indentation, what’s the *fastest* and easiest option?
Matt Stauffer, Twitter
I wrote about doing this in Sublime Text a few years back. It’s not terribly different in VS Code, I don’t think.
But here’s another way: Use CodePen.
Step 1: Copy and paste to CodePen
Say you found some code elsewhere, just copy and paste it in:

Step 2: Adjust code indentation settings
If you already have a CodePen account, you’ve probably already got it set up, so the default is how you like it. But if it’s not yet, adjust it in the Pen Settings area:

Step 3: Format the code
You can manually do it here:

You may not have to use that option at all if you save the Pen and have the “Format on Save” option on, as it will automatically happen.

It’ll kick over to that new 4-space preference right quick:
CodePen uses Prettier under the hood to do this. So you could do this anywhere you have access to a working version of Prettier, but it might be easier on CodePen since there’s nothing like editing config or anything to adjust how you want it. Prettier has its own playground as well, which is likely just as easy as CodePen, except that on CodePen you might already have your preferences set up, saving a step.
The ultimate better way is to have eslint and make a rule so that no matter what format or indent you might write/copy-paste it will adjust as you desired on save.
Depends on your configuration. You can have a very strict eslint ruleset that does that for you, but I prefer using prettier for formatting, and leave eslint for code quality checks.
It’s weird if your IDE doesn’t do this automatically, no?
I think so too. Though sometimes when copying/moving my own code, the entire block is either too indented by a constant amount of tabs/spaces or not enough. Then Ctrl+Alt+F (or whatever your shortcut for Format All is) and it’s fixed. Then there’s the Format On Save option in settings.
I’m really grateful for VS Code.
PS: Don’t expect to have code formatted inside strings (possiblly HereDoc). Formatter can’t know if there are tabs there instead of spaces intentionally or not.
And… queue the infamous tabs vs. spaces debate, where this issue is only a problem when people indent with spaces.