Search code examples
vimauto-indenttabstop

vim - set auto indent to fill the leading space with space or tabstop


It seems if we enable 'ai', vim will fill the the leading space with tabstop. I can make it fill with just space with 'et'. I don't like a C file mixed with space and tabstop.

My vimrc:

set ts=4 et
set ai
set hlsearch
syntax on
filetype plugin indent on
autocmd FileType make setlocal noexpandtab

However, in some condition I do need to input tabstop when I hit the 'TAB' on keyboard, for example, in makefile and some others. The 'autocmd FileType' command is not good: I can't add every file type in vimrc.

What I want is simple:

  1. autoindent to fill leading area with space;
  2. when hit 'TAB' on keyboard, tabstop input, not space (so no 'et')

How to do it?


Solution

  • inoremap <expr> <tab> ((getline('.')[:col('.')-2]=~'\S')?("\<C-v>\t"):(repeat(' ', &ts-((virtcol('.')-1)%&ts))))
    

    It does the same as @Lynch answer if I read it correctly.

    You can also use <C-v><Tab>: this will insert <Tab> without invoking any mappings and ignores expandtab unless you remapped <C-v> or <C-v><Tab> for some reason.

    If you want to just insert tab do

    inoremap <Tab> <C-v><Tab>
    

    It will ignore expandtab setting.