Search code examples
vimautocmd

How to prevent global defaults from overriding 'filetype=vim' specific settings in .vimrc when automatically sourcing .vimrc?


Context

I have my .vimrc automatically being sourced with:

autocmd! BufWritePost ~/.vimrc source ~/.vimrc

I also set defaults for spacing:

set tabstop=2 softtabstop=2 shiftwidth=2 expandtab

Later on, I use the FileType event to override the spacing default above with filetype-specific spacing:

" Syntax of these languages is fussy over tabs & spaces¬
autocmd FileType make setlocal ts=8 sts=8 sw=8 noexpandtab¬
autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab¬                                                   

" Customisations based on house-style (arbitrary)
autocmd FileType sh setlocal ts=4 sts=4 sw=4 expandtab
autocmd FileType vim setlocal ts=4 sts=4 sw=4 expandtab

Problem

The problem I am having is that sourcing my .vimrc will set the default values, but will not trigger the FileType event. This means that when I do a :write to my .vimrc while editting a file with filetype-specific spacing, the filetype-specific spacings get overridden by the defaults!

UPDATE: As pointed out by Ingo, the issue only arises in .vimrc and does not occur in any other files.

Example

As an example, when I am working on my .vimrc, initially the file-specific spacing (ts=4 sts=4 sw=4 expandtab) is enabled, but after I make some arbitrary change in my .vimrc, the default spacing (tabstop=2 softtabstop=2 shiftwidth=2 expandtab) is loaded but my file-specific spacing is NOT loaded (since the FileType event was not triggered by a write to my .vimrc) leaving me with the default spacing!

My question(s)

How can I override the default spacing with filetype specific spacings and preserve these even when auto-sourcing .vimrc?

If possible, I would like to accomplish this without getting rid of the autocmd's. Is that possible?

My hunch is that I should somehow manually trigger the FileType event when sourcing .vimrc Can this be done and is this the recommended approach?


Solution

  • I ended up solving this issue by grouping the sourcing autocmd with another autocmd with the same event

    " Reload changes to .vimrc automatically  
    autocmd BufWritePost ~/.vimrc source ~/.vimrc | setlocal filetype=vim
    

    I had tried this earlier, but I was also using the AirlineRefresh command for vim-airline as such:

    autocmd BufWritePost ~/.vimrc source ~/.vimrc | AirlineRefresh | setlocal filetype=vim

    which was giving me this error:

    E488: Trailing characters:  AirlineRefresh | setlocal filetype=vim

    Switching the order of AirlineRefresh and set local filetype=vim fixed the error and results in the desired behavior:

    autocmd BufWritePost ~/.vimrc source ~/.vimrc | setlocal filetype=vim | AirlineRefresh