vimvim-plugincscope

Why is autoload cscope.out enabled only after opening vim for the second time


What I want to do is to create a new cscope database based on different file types every time I open vim, and then automatically load cscope.out

I edit my .vimrc, based on this article: how to auto load cscope.out in vim

But it only autoloads cscope.out the second time I open vim, the first time I open vim, it always show no cscope connection

What should I change?

Here is my settings:

if !filereadable("cscope.out")
    autocmd BufRead,BufNewFile *.py !find / -name "*.py" > ~/cscope.files; cscope -Rbq -i ~/cscope.files
    autocmd BufRead,BufNewFile *.java !find / -name "*.java" > ~/cscope.files; cscope -Rbq -i ~/cscope.files
    autocmd BufRead,BufNewFile *.c !find / -name "*.c" -o -name "*.h" > ~/cscope.files; cscope -Rbq -i ~/cscope.files
    autocmd BufRead,BufNewFile *.cpp !find / -name "*.cpp" -o -name "*.hpp" -o -name "*.h" > ~/cscope.files; cscope -Rbq -i ~/cscope.files
    autocmd BufRead,BufNewFile *.hpp !find / -name "*.cpp" -o -name "*.hpp" -o -name "*.h" > ~/cscope.files; cscope -Rbq -i ~/cscope.files
endif

" setting location of cscope db & cscopetag
let CSCOPE_DB="~/cscope.out"                
                                                                              
if has("cscope")
"   set csprg=/usr/local/bin/cscope
    set csto=0
    set cst
    set nocsverb
    " add any database in current directory
    if filereadable("cscope.out")
        cs add cscope.out
    " else add database pointed to by environment
    elseif $CSCOPE_DB != ""
        cs add $CSCOPE_DB
    endif
    set csverb
endif


Solution

  • In the "autocommand" block, you add autocommands to the default autocommand group. They will be executed later, when you edit a *.py file or whatever. At this point, no database is created.

    In the "cscope" block, you point cscope to a database but no database has been created.

    After your vimrc is sourced, the *.py file is loaded and the database is created but the code in charge of the cscope setup has already run so cscope doesn't know about your database.

    The next time you run Vim, the database is already there because it has been created during the previous run, so code that sets up cscope does its job as expected and cscope gets a proper database.

    You should be able to solve your problem by postponing the cscope step to after the database has been created, which sounds like a perfect use case for :help job_start().