1

I wanted to have my vimrc automatically update when I write to a .vim file using this autocmd:

autocmd BufWritePost *.vim,$MYVIMRC source $MYVIMRC

But for some reason when I have this enabled and then do :w in my vimrc, my vimrc is pasted into my current buffer at the cursor position. How can I prevent this, and why does source behave like this?

stimulate
  • 171
  • 1
  • 9
  • If you do :source $MYVIMRC manually, does this happen? If so, its probably a bug in your vimrc – D. Ben Knoble Nov 10 '19 at 14:08
  • No, it did not happen if I sourced manually.. I don't exactly know what does it but with this code it works:
      autocmd! |
      autocmd BufWritePost *.vim,vimrc,$MYVIMRC ++once source $MYVIMRC | e |
    augroup END
    
    – stimulate Nov 10 '19 at 14:17
  • 2
    Feel free to post it as an answer. I can explain what it does, but the original issue may be a quirk of your vimrc. See https://vi.stackexchange.com/q/2003/10604 – D. Ben Knoble Nov 10 '19 at 14:19
  • 1
    It would still be nice to understand why the original autocmd wasn't working... Anything specific in your vimrc that was causing that problem? – filbranden Nov 10 '19 at 17:25

1 Answers1

1

This code works:

augroup reload_vimrc
    autocmd!
    autocmd BufWritePost *.vim,vimrc,$MYVIMRC ++once source $MYVIMRC | e
augroup END

It

  1. does the augroup group/autocmd! dance to set up a group and clear any commands already in it
  2. establishes a one-time (++once) autocmd that
    1. sources the vimrc
    2. uses :edit to re-edit the current file (effectively sourcing its ftplugins and such again)
  3. Ends the group
D. Ben Knoble
  • 26,070
  • 3
  • 29
  • 65
stimulate
  • 171
  • 1
  • 9