5

My current configuration makes vim automatically expand TAB to 4 spaces for me:

" Define tab as 4 spaces
" Taken from http://stackoverflow.com/questions/1878974/redefine-tab-as-4-spaces
set tabstop=4       " The width of a TAB is set to 4.
                    " Still it is a \t. It is just that
                    " Vim will interpret it to be having
                    " a width of 4.
set shiftwidth=4    " Indents will have a width of 4
set softtabstop=4   " Sets the number of columns for a TAB
set expandtab       " Expand TABs to spaces

While it is nice to make Tab 4 spaces in Python, a four-space indent in HTML files is just too much. I want to make vim detect the file type, and choose how many spaces to expand Tab into. For example, 2 for HTML and 4 for other file types.

2 Answers 2

7

Put this in your .vimrc file:

autocmd BufRead,BufNewFile *.htm,*.html setlocal tabstop=2 shiftwidth=2 softtabstop=2

Briefly, autocmds get processed when the specified events occur for the specified file name patterns. Here we just set the tab values for the current buffer to the desired value in the event of reading or creating a file with .htm or .html extension.

There are many other ways you can customize your settings for a file type: change the color scheme, modify settings globally or locally, run a script or some editor commands, and so on. :help autocmd for more details.

1
  • Thanks, but your configuration didn't work, while this works: autocmd BufRead,BufNewFile *.htm,*.html setlocal tabstop=2 shiftwidth=2 softtabstop=2
    – nalzok
    Jul 16, 2017 at 5:26
1

The accepted answer didn't work on vim 8.1 (Ubuntu 20.04). I had to add this to my .vimrc:

autocmd FileType html setlocal tabstop=2 shiftwidth=2 softtabstop=2
1
  • 2
    Instead of using a FileType autocommand you should create a ftplugin to put this kind of setup. It's much cleaner and that avoid reimplementing the ftplugin mechanism with autocmds. See :h ftplugin-overrule
    – statox
    Mar 29, 2022 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.