Search code examples
cvimconfigurationviauto-indent

Number of Tabs I do get after striking Tab key in Vim Insert mode


I am learning C programming.

I met a problem about vim configuration.

The following is my vim setting written in .vimrc:

set nu
set shiftwidth=4
set tabstop=4
set softtabstop=8
set autoindent
set cindent
set smartindent
syntax on

In order to see where the tabs are, I have used :set list:

#include <stdio.h>$
int main(void)$
{$
^Iprintf("ab\n");$
^Ireturn 0;$ 
}$

Now in line 4 under Insert mode, I want to see how many tabs I can get after I strike Tab key in different locations.

Here's the result:

When I strike Tab after n, I get ^Iprin^I^Itf("ab\n");$.

When I strike Tab after \n, I get ^Iprintf("ab\n^I^I");$.

The above two situations are quite understandable to me.

But when I strike Tab after a, I get ^Iprintf("a^Ib\n");$.

This is beyond my understanding.

Can anybody explain why there is only one tab replaced?

I thought there should be two because softtabstop takes up 8 spaces which is two times tabstop (4).


Solution

  • This is the result of the interaction between your softtabstop and (regular) tabstop.

    Your softtabstop says when hitting the Tab key, the results should be aligned with multiples of 8 columns. When you strike Tab after a, you're already at column 13, so just one 4-width tab character is enough to get there. In the other cases you were at 16 and 8, respectively, so it took two 4-width tab characters to align to your 8-width soft tab.

    PS: if you want weird behaviours (not recommended of course), set tabstop=3 softtabstop=8. Then you get combinations of spaces and tab characters when you hit the Tab key.

    PPS: All this is part of why I don't like literal Tab characters. They're unstable, their display depending on each developer's tab-stop settings. In my organization, I push hard for everyone to use :set expandtab (or the equivalent in each developer's editor) and use space characters for stable and reproducible display. The only place I tolerate tab characters in my work is in makefiles, where I don't have a choice.