How to run a command immediately when starting vim?

I have a plugin (FindFile.vim) that should run :FindFileCache . whenever I run vim to collect a file cache for quick opening. I have to run it every time I run vim.

How can I write a command that runs once, every time vim starts?

+66
vim
Jul 25 '11 at 19:06
source share
4 answers

The best place to store your configuration files in your .vimrc file. However, this is too early, check out :h startup :

 At startup, Vim checks environment variables and files and sets values accordingly. Vim proceeds in this order: 1. Set the 'shell' and 'term' option *SHELL* *COMSPEC* *TERM* 2. Process the arguments 3. Execute Ex commands, from environment variables and/or files *vimrc* *exrc* 4. Load the plugin scripts. *load-plugins* 5. Set 'shellpipe' and 'shellredir' 6. Set 'updatecount' to zero, if "-n" command argument used 7. Set binary options 8. Perform GUI initializations 9. Read the viminfo file 10. Read the quickfix file 11. Open all windows 12. Execute startup commands 

As you can see, your .vimrc will be loaded before the plugins. If you put :FindFileCache . an error will occur in it, since this command will not exit (as long as it exists after loading the plugin in step 4).

To solve this problem, instead of directly executing the command, create an auto-command. Automatic commands execute some command when an event occurs. In this case, the VimEnter event looks accordingly (from :h VimEnter ):

  *VimEnter* VimEnter After doing all the startup stuff, including loading .vimrc files, executing the "-c cmd" arguments, creating all windows and loading the buffers in them. 

Then just put this line in your .vimrc:

 autocmd VimEnter * FindFileCache . 
+104
Jul 25 2018-11-11T00:
source share
β€” -

There is also the -c vim flag. I do this in my tmuxp configuration so that vim starts with a vertical split:

 vim -c "vnew" 
+51
Jan 07 2018-01-15T00:
source share

Create a file called ~/.vim/after/plugin/whatever_name_you_like.vim and fill it

 FindFileCache . 

The order of reading and executing scripts in vim directories is described in :help 'runtimepath'

+12
Jul 25 '11 at 19:08
source share

Put FindFileCache in .vimrc .

Autload commands are different and will not work for your scenario.

+1
Jul 25 '11 at 19:27
source share



All Articles