2

I have the following in my .vimrc so that it processes after saving

" source as soon as we write the vimrc file
if has("autocmd")
  autocmd bufwritepost .vimrc source $MYVIMRC
endif

However, I have a more involved file, and it appears that the time to post the vimrc file after save gets longer and longer and longer to where I have to quit out of my gvim session and start over.

Is there a 'clear workspace' or a better way to resolve this issue, so that I may stay within the comforts of my single gvim session all day?

Kevin Lee
  • 718
  • 6
  • 19
  • I'm sensing a tone there... I don't intend to work on this file every waking hour of my life, but the past day has been like that and the community is good at responding. Also anytime I try new things I throw it in vimrc, if you know of a better sandbox location please inform! – Kevin Lee Aug 02 '13 at 23:00
  • 1
    Use another file: 1. `:vs ~/temp.vim`. 2. Add your custom mappings and temporary stuff there. 3. `:so %`. At the end of the day, take the good stuff and put it in your `~/.vimrc` before discarding the temp file. – romainl Aug 03 '13 at 05:59

2 Answers2

14

Every time the autocmd is sourced it is added to the autocmd list. So you might be sourcing your vimrc thousands of times when you save because everytime you source you add the autocmd to the list. (You can see that the autocmd is added multiple time by doing :au bufwritepost)

To fix this you just need to wrap the autocmd in a augroup and clear the group when it is loaded.

augroup NAME_OF_GROUP
  autocmd!
  autocmd bufwritepost .vimrc source $MYVIMRC
augroup end

The autocmd! removes all autocmds from the group.

Help pages to read :h autocmd-define and :h autocmd-groups

FDinoff
  • 30,689
  • 5
  • 75
  • 96
5

Maybe you encountered a phenomenon that it outlined in

:h autocommand

The help sais:

When your .vimrc file is sourced twice, the autocommands will appear twice. To avoid this, put this command in your .vimrc file, before defining autocommands:

:autocmd!   " Remove ALL autocommands for the current group.

If you don't want to remove all autocommands, you can instead use a variable to ensure that Vim includes the autocommands only once:

:if !exists("autocommands_loaded")
:  let autocommands_loaded = 1
:  au ...
:endif

I get used to grouping of my autocommands like this

augroup BWCCreateDir
    autocmd!
    autocmd BufWritePre * :call s:MkNonExDir(expand('<afile>'), +expand('<abuf>'))
augroup END
user1146332
  • 2,630
  • 1
  • 15
  • 19