Are you trying to remove the unnecessary spaces or are you just trying to format your code correctly. Because there are different solutions to the problem.
Do correct formatting:
You can get vim to correctly indent your code by using
The easiest way to use this is to use visual mode.
Go to the start of the section you want correctly indented. Hit Ctrl-V. Move the cursor to the end of the section you want correctly indented (can be the whole file). Hit
= key and your code will be correctly formatted.
Replace space (where you have tabs to indent).
Since you are using tabs.
The following assumes you don't have
The following should preserve the normal indentation of your lines. Any lines with extra space characters at the end of the initial indentation will change slightly as those extra spaces will be removed.
If you do this a lot (as it is several steps) it may be worth wrapping this in some type of function. But my vim foo is not that strong yet. The following assumes you have your tab stop set at 4 you may need to alter a couple of the searches if you use a different size.
I would do it in three steps.
:% s/^I/ /g
This converts all you tabs to spaces first (without messing with the indentation). (by first resizing your tabs replacing them with space then setting the tab size back to its original size).
Now you can convert all the leading space on a line into tabs.
:% g/^ /s/ /^I/g
The above searches for all lines that begin with four spaces (use the number of spaces you have in your tab stop size). And replaces from left to right each group of four spaces with a tab character.
So now all your lines have leading tabs and any extra space is on the end of the initial tab indented line. So now you can just remove any trailing white space as we expect this is unneeded.
:% s/^\(^I*\) */\1/
This searches for lines that begin with zero or more tabs followed by zero or more spaces. It then replaces the match with the initial number of tabs you found. Thus effectively removing space from the indentation.
^Iint a; ^I ; int b;(
^Is are tabs)? The spaces around the second tab should be removed?