Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert leading spaces to tabs?

Tags:

vim

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.

like image 601
Martin Drlík Avatar asked Jul 22 '12 08:07

Martin Drlík


People also ask

How to convert leading spaces to tabs in AutoCAD?

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.

How to change each tab into 2 spaces in a line?

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.

How to convert text with spaces to tabs in Excel?

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.

How to change the default space size of each tab in Linux?

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.


2 Answers

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

like image 110
Jo So Avatar answered Nov 15 '22 09:11

Jo So


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.

like image 37
Martin Drlík Avatar answered Nov 15 '22 09:11

Martin Drlík