Determinant
Determinant

Reputation: 4036

Vim Configuration: How to expand tabs only when saving?

I love tabs, and prefer it to spaces in indentation.

But I'd like to transform tabs into 4-space groups when saving files. (Because the file may be opened and edited in other environments) And of course, those generated spaces should be converted back to tabs if I open the file again. (Assume that there are no 4 contiguous spaces in the original text)

Upvotes: 3

Views: 295

Answers (2)

Zsolt Botykai
Zsolt Botykai

Reputation: 51583

Well in your .vimrc:

set noexpandtab
set tabstop=4
set shiftwidth=4
fun MyRetab()
    set expandtab
    retab
    set noexpandtab
endfun
au FileWritePre *.YOURFILEEXTENSION call MyRetab()

But I don't know what you mean by "those spaces should be still recognized as tabs if I open the file again."

If you write a file spaces instead of tabs, well it can't be undone easily AFAIK. EDIT: see the super retab wiki page for undoing it!

NOTE if you have tab(s) in your source's string contents this will replace that as well!

Upvotes: 2

Prince Goulash
Prince Goulash

Reputation: 15715

In addition to Zsolt Botykai's answer, you could try using retab!, which attempts to replace spaces with tabs where appropriate. This seemed to work quite well when I just tried it, but I got a few erroneous tabs. I suppose it depends how good your assumption is that there no other sequences of 4 spaces other than expanded tabs.

HOWEVER... this all seems like a risky business. In my experience, when there are coding/encoding standards such as these, it is always easiest to adhere to them from the start. "Fixing-up" the file in this way is asking for trouble.

I think Vim does a good job of emulating tab-like behaviour while using only spaces. Have you tried using smarttab and expandtab?

Upvotes: 1

Related Questions