Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

And then to automatically re-indent after that? (I tried copying code from one terminal screen to the other, but the tabulation got all messed up)

I didn't know what to call this functionality, so it was hard for me to find it on google (which generally returned things related to how to set tab size, which wasn't what I was looking for unfortunately.)

Thanks

share|improve this question

3 Answers 3

up vote 5 down vote accepted

Vim has a retab command that allows you to tabify or untabify your document. It uses settings such as tabstop and expandtab. So, if you want to replace tabs with spaces you could do the following:

:%retab

See the retab documentation for full details.

Caveat Emptor: this also replaces tabs that are NOT at the beginning of a line. So if you use hard tabs in the middle of strings they will be replaced as well.

share|improve this answer
2  
In general, it's considered a bad idea to include a true tab in a string anyway. It can still happen, but \t is preferred, just to avoid these kinds of issues. –  Spencer Rathbun Sep 23 '11 at 1:18

To expand on @Kaleb's answer (I don't have the rep yet to comment), before executing the retab command, you will need to :set expandtab (set et). Otherwise the retab will not replace tabs with spaces.

In additon, you may wish to specify the tabstops. Often in source code created by others, the code is written with tabstops set to 4 or even 2. Before doing the :%retab command, experiment with different tabstops. Try

:set ts=8 (the default)
:set ts=4 
:set ts=2  

to see which setting makes the most sense.

To go backwards (replacing spaces with appropriate TAB characters, use

:set noet
:%retab!
share|improve this answer

By un-tab, do you mean to change tabs to spaces? If so, substitute spaces for tabs in the entire buffer like this:

:%s/^I/    /g

That's four spaces on the right side of the substitution, but you can make it whatever number you want. To get the literal ^I tab character, you can hit ^V followed by the Tab key.

You can re-indent with the = command. To re-indent the entire contents of the buffer, use these commands:

gg
=G

This takes you to the top, then re-indents everything to the bottom.

share|improve this answer
    
-1: Replacing a tab with a fixed number of spaces is almost never useful. It will change the appearance of any line containing a tab preceded by a non-tab. –  kevin cline Sep 24 '11 at 3:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.