Vim Tips Wiki
Tip 247 Printable Monobook Previous Next

created May 17, 2002 · complexity basic · author Riccardo Casini · version 5.7

Using tabs as elementary unit in your code indentation has two advantages: first, you may modify 'tabstop' and immediately all the indentations depths are modified according to it; second, your file will be smaller.

But how can we change some already-written code in order to convert spaces to tabs. Very simple!

Suppose your old code has an indentation unit of 2 spaces

:ret! 2

will replace every 2-spaces to one tab, independently from your current tabstop value, and will save the modified file.

Then, if you open again the file with tabstop=2, the file will look as before but it will be smaller. If you open the file with tabstop=4, the code vill have a more indented look, and so on...


But what if you have two spaces somewhere in your code where it belongs (like, in a textstring or so)? I think you'd better unindent by removing all spaces at beginnings of lines (:%s/$\s+//g or so), be sure your tabsettings are good and gg=G your text to re-indent.

Maybe gg=G is already removing all the whitespace at the beginning of lines before reindenting. Dunno exactly (too lazy to find out :) )

Changing tabstop is always asking for trouble in my experience. There will always be people who open your file with a different tabstop (or just the default 8) and then write new code using spaces to indent. Et voilà, your formatting is busted.

Try softtabstop instead. Use modelines. Don't just change tabstop.

I always use 2 commands to avoid reformatting double spaces inside the valid code...

:s/^ /^I/


:s/I /^I^I/g

I do,

:%s/ /\t/g

and note, the number of spaces that comes after ":%s/" is the width of the tab stop you currently have.

How do you avoid replacing spaces with tabs somewhere in your code where spaces were put as part of a string or something. Your code does not take in consideration such possibility.

Alternative: if your file has indent 4 and you want an indent of 3 and gg=G is not working as expected, try

:set inde=indent(v:lnum)/4*3

then go ahead with the well known


use tabs or spaces, doesn't matter