Search code examples
vim

How to convert leading spaces to tabs?


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.


Solution

  • 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.