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?

  • 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: augroup reload_vimrc | 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 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

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
| improve this answer | |
  • 1
    OP, I've edited to explain the code. If you feel that is inappropriate, rollback and ping me and I'll add my own answer. – D. Ben Knoble Nov 10 '19 at 16:41
  • Well, thank you. – stimulate Nov 10 '19 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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