Reindenting code in a hurry with CodePen

Matt Stauffer posed a practical question on Twitter: when you copy a code sample written with two-space indentation and want four-space indentation instead, what is the fastest and easiest way to make the switch? The author of the original piece had previously written about doing this in Sublime Text, and notes the process in VS Code isn't terribly different. But there is another route: run the code through CodePen.

Paste, configure, format

  1. Copy the sample from wherever you found it and paste it straight into CodePen.
  2. Set the desired indentation in the Pen Settings area. If you already have an account, your preferences are likely already configured the way you like them.
  3. Format the code—either by doing it manually (the source shows the button for this) or by simply saving the Pen with "Format on Save" enabled, which triggers the formatting automatically.

Once that's done, the code switches over to the four-space preference right away.

What's doing the work

The formatting is handled by Prettier, which means the same trick works anywhere a working copy of Prettier is available. CodePen just makes it convenient: there is no configuration editing involved to get the indentation you want. Prettier's own playground is an option that is likely just as easy, with one small caveat—on CodePen your preferences may already be set up, which saves a step.