How can I convert spaces to tabs in Vim or Linux?
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
.
Using Vim to expand all leading spaces (wider than 'tabstop'
), you were right to use retab
but first ensure 'expandtab'
is reset (:verbose set ts? et?
is your friend). retab
takes a range, so I usually specify %
to mean "the whole file".
:set tabstop=2 " To match the sample file
:set noexpandtab " Use tabs, not spaces
:%retab! " Retabulate the whole file
Before doing anything like this (particularly with Python files!), I usually set 'list'
, so that I can see the whitespace and change.
I have the following mapping in my .vimrc
for this:
nnoremap <F2> :<C-U>setlocal lcs=tab:>-,trail:-,eol:$ list! list? <CR>