I've looked over several questions on Stack Overflow for how to convert spaces to tabs without finding what I need. There seem to be more questions about how to convert tabs to spaces, but I'm trying to do the opposite.
In Vim
I've tried :retab
and :retab!
without luck, but I believe those are actually for going from tabs to spaces anyways.
I tried both expand
and unexpand
at the command prompt without any luck.
Here is the file in question:
How can I convert leading spaces to tabs using either Vim
or the shell?
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>