-4

I would like to call my Vim function once when vimrc is sourced.

I could put some global variables in my vimrc file and set them to be 0 or 1 etc.. In fact, that is what I'm doing for many functions. However, there are many global variables flying around in my vimrc file and it is painful to keep track of them.

 let g:Myfun_var1 =  '0'

    func! Myfun
        g:Myfun_var1 = '1'
    endfunc

I'm wondering whether there is way to achieve the result without using any global variables inside my function

By the way, I don't want to put my function in autoload folder ~/.vim/autoload. (I try to keep all functions in my vimrc file.)

  • 1
    Your question does not really make any sense. As @LucHermite writes in his answer, functions in .vimrc are generally called once when it is sourced. Then you mention global variables, but you do not provide any connection between them and the function you are talking about. Please improve the question! – Karl Yngve Lervåg Nov 7 '16 at 7:50
  • Actually I see two scenarios where a function may be called several times (in OP's context), and which require a special handling: 1- the .vimrc is sourced several times and the function really shall not be called several times. 2- There are complex uses of autocommands. In both cases, we really need to see more. – Luc Hermitte Nov 7 '16 at 9:11
3

As long as your function is called only from your .vimrc, it should be called once -- unless you source it several times, which is an exceptional scenario which doesn't deserve to spend too many time on it -- note that if this is your problem, then you could use a single script local variable (a global with a special scope -- this is comparable to static variables in C) to be sure a particular initialization is done only once.

If you're afraid to call it from plugins, well as long as you are responsible for the function name, and you know you call it from your .vimrc, why would you want to call it from a plugin?

I must admit I don't really see your problem, from your description I read that:

  • you define a function
  • you put it in your .vimrc
  • you call it from your .vimrc
  • you don't expect to call it several times

Then, don't call it several times. Doing so is a programming error. Trust yourself. You may add script global (s:foobar_function_has_been_executed) and use the new assert_true() functions to check what you're doing.

  • 1
    you could call the function on VimEnter autocommand. – Christian Brabandt Nov 7 '16 at 11:11

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.