Many people use spaces rather than tabs. I use both of them. Tabs at the beginning of line and spaces from the first non-whitespace character. No problem for starting new document and in case I have to modify one better adapt to using format. Still sometimes I need to fix the spaces issue anyway.
According to Search and replace I can just do :%s/spaces_for_tab/tab/g
. It is simple and it will work for many cases. Anyway I want to refactor only spaces at the beginning of line.
Select a block of lines of text with the problem of mixed spaces and tabs. Press [Tab] and [Shift]+ [Tab] to add and remove a tab from each line. In the process, the leading spaces had been converted to tabs.
For example, if you have to change each tab into 2 spaces, you can use the expand command like this: Often in the programs, you would only want to convert the leading tabs i.e. the tabs at the beginning of the line. You don’t want to touch the tabs in between the lines that are actually part of the code.
Enter text with spaces in Input text area. Choose type of space you want to convert i.e. Spaces/Repeated Spaces/Whitespaces/Repeated Whitespaces. Click on Show Output button to get text converted to tabs.
The good thing is that you can change the default space size with the -t option. For example, if you have to change each tab into 2 spaces, you can use the expand command like this: Often in the programs, you would only want to convert the leading tabs i.e. the tabs at the beginning of the line.
This is more of a regex issue. To anchor at the beginning of the line, use the caret, e.g.
s/^ /\t/
Or do it using vim's builtin functionality:
:set tabstop=4 "four spaces will make up for one tab
:set noexpandtab "tell vim to keep tabs instead of inserting spaces
:retab "let vim handle your case
By the way, I too prefer tabs for indentation and spaces for alignment. Unfortunately, vim doesn't handle this well (and I don't know what other editors do), so I mostly use :set expandtab
(maybe see :set softtabstop
).
I've written a simple func for it. Anyway it will work only for 4-space tab.
fu! Fixspaces()
while search('^\t* \{4}') != 0
execute ':%s/^\t*\zs \{4}/\t/g'
endwhile
endfu
You can suggest better solution, if exists, and I will use it with pleasure. The issue is that this func replaces spaces in strings as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With