1

My .vimrc includes the following lines:

if filereadable("my_source")
    :source my_source
endif

That is, if the file 'my_source' exists in the folder where I open vim and it is readable, it is loaded automatically.

However, if I am editing a file in that folder and open another file (also in that same folder) via :tabe, the source file 'my_source' is not loaded in the latter. Why? How can I have it automatically loaded when I open a new tab?

2

You need to use an autocommand to accomplish this, as your .vimrc is only sourced once on startup. As their name would suggest, autocmds allow for defining a series of commands that should occur automatically when certain events are fired.

I recommend you read about them in Vim's help pages, as they are a ubiquitous and incredibly useful component. In the meantime, this should cover your needs adequately:

augroup MyAutoCmds
    autocmd!
    autocmd BufNewFile,BufRead,VimEnter *
      \ if filereadable('my_source') | source my_source | endif
augroup END

I highly recommend that you read this and this on why augroup is used here, and why you should be sure to use it yourself. In short, the main reason is to act as a guard when you re-source your .vimrc, otherwise the autocommands would be defined multiple times, and thus run multiple times!

  • 1
    For augroup to be effective, you need autocmd! as the first line inside t – D. Ben Knoble Jul 21 '18 at 3:29
  • @D.BenKnoble Whoops, completely forgot to add that. Thanks – ZeroKnight Jul 21 '18 at 3:30
  • @ZeroKnight , I get the error Error detected while processing BufRead Auto commands for "*": E15: Invalid expression: filereadable('my_source') source my_source endif – Godoy Jul 21 '18 at 5:58
  • 1
    @Galvane My bad, the if syntax is a bit...particular in an autocmd statement. I've edited the answer. – ZeroKnight Jul 21 '18 at 7:55
1

the statements in .vimrc are executed only once. You could create an autocommand for this matter.

Find details in :help autocommand

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.