1 - If you have spaces and want tabs.
First, you need to decide how many spaces will have a single tab. That said, suppose you have lines with leading 4 spaces, or 8... Than you realize you probably want a tab to be 4 spaces. Now with that info, you do:
:set ts=4
:set noet
:%retab!
There is a problem here! This sequence of commands will look for all your text, not only spaces in the begin of the line. That mean a string like: "Hey,␣this␣␣␣␣is␣4␣spaces"
will become "Hey,␣this⇥is␣4␣spaces"
, but its not! its a tab!.
To settle this little problem I recomend a search
, instead of retab
.
:%s/^\(^I*\)␣␣␣␣/\1^I/g
This search will look in the whole file for any lines starting with whatever number of tabs, followed by 4 spaces, and substitute it for whatever number of tabs it found plus one.
This, unfortunately, will not run at once!
At first, the file will have lines starting with spaces. The search will then convert only the first 4 spaces to a tab, and let the following...
You need to repeat the command. How many times? Until you get a pattern not found
. I cannot think of a way to automatize the process yet. But if you do:
`10@:`
You are probably done. This command repeats the last search/replace for 10 times. Its not likely your program will have so many indents. If it has, just repeat again @@
.
Now, just to complete the answer. I know you asked for the opposite, but you never know when you need to undo things.
2 - You have tabs and want spaces.
First, decide how many spaces you want your tabs to be converted to. Lets say you want each tab to be 2 spaces. You then do:
:set ts=2
:set et
:%retab!
This would have the same problem with strings. But as its better programming style to not use hard tabs inside strings, you actually are doing a good thing here. If you really need a tab inside a string, use \t
.
sed "s/ +/`echo -e '\t'`/g" < input.py > output.py
)appears to convert all spaces, not just leading spaces. In the second example (sed "s/^ +/`echo -e '\t'`/g" < input.py > output.py
) it only replaces the first space on each line with a tab and leaves the rest of them. – cwdfind
,awk
and blackjack (too long to leave it in comments, though) – maxkoryukov