Vim logo vim online Vim Book Ad

basic Tip #247: Preexisting code indentation

 tip karma   Rating 17/9, Viewed by 1049 

created:   May 17, 2002 0:46      complexity:   basic
author:   Riccardo Casini      as of Vim:   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
:x
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...

Cheers!

 rate this tip  Life Changing Helpful Unfulfilling 

<<Working with Unicode (the same, rewritten for legibility) | Auto-save the current buffer periodically. >>

Additional Notes

[email protected], May 17, 2002 6:08
Ehm, maybe... 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....
[email protected], May 17, 2002 6:10
Ehm... maybe gg=G is already removing all the whitespace at the beginning of lines before reindenting. Dunno exactly (too lazy to find out :) )
informatik.hu-berlin.de: piefel, May 23, 2002 7:04
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.
Anonymous, October 17, 2002 10:15
I always use 2 commands to avoid reformatting double spaces inside the valid code...
:s/^  /^I/
Then
:s/I  /^I^I/g
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
SourceForge Logo