The following search-and-replace regex changes the number of spaces per indentation level from 4 to 2 in existing files. It's relatively easy to understand, reliable, and doesn't require installing anything.
Instructions
- Press CtrlH (or ⌥⌘F on macOS).
- Make sure regex matching is on by clicking on the .* button in the search popup or pressing AltR (or ⌥⌘R on macOS).
- In the Find field, enter
^(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?
- In the Replace field, enter
$1$2$3$4$5$6$7$8$9
- Finally press CtrlEnter (or ⌘Enter on macOS) to apply to the current file.
You could also use this in the Search pane on the left to do this across all files in your project. However, note that this should only be run once per file. It will mess up the indentation of files that already use 2 spaces.
Extra Credit: How It Works
The way the regular expression works is it matches groups (?: ... )
of four spaces at a time at the beginning ^ ...
of each line, only capturing ( ... )
the first two spaces. Each indentation level is optional ... ?
, so it works for as many indentation levels as the pattern is repeated and there are in each line. Then it replaces the whole pattern with only the captured spaces $1
, $2
, ..., effectively replacing every four-space indentation level with two spaces.
This pattern only works up to 9 indentation levels (I'm not sure if $10
would work, but if so this could be expanded indefinitely).
Extra Extra Credit: Extending
You could adapt the pattern to decrease the number of spaces per indentation level in a file from any original number to another lower target number.
Put the target number of spaces inside the inner parenthesis. Then, put the remaining original number of spaces in the outer parenthesis, so the total number of spaces in the pattern is the original.
For example, if you want to change the indentation level from 6 to 4, repeat this search pattern as many times as you like:
^(?:( ) )?
or ^(?:( {4}) {2})?
And use the same number of $1
, $2
in the replacement pattern.