" if compiled with --enable-cscope
if has("cscope")
	if exists("g:loaded_cscope_plus") || &cp
		finish
	endif


	set tags+=./tags	" in file directory
	set tags+=tags		" in current directory
	"for when programming in build dir
	set tags+=../tags

	function! GetLocalCscopeDb(pathname)
		if !isdirectory(a:pathname) ||  a:pathname == $HOME || a:pathname == '/'
			return
		endif
		let s:cscopefile = a:pathname."/cscope.out"
		if filereadable(s:cscopefile)
			echo "Add cscope db for ".a:pathname
			execute "cscope add ".s:cscopefile." ".a:pathname
		endif
		unlet s:cscopefile
		call GetLocalCscopeDb(fnamemodify(a:pathname, ":h"))
	endfunction
	command! LoadLocalCscopeDb :call GetLocalCscopeDb(expand("%:p:h"))

	function! GetCscopeDb(pathname)
		if !isdirectory(a:pathname) ||  a:pathname == $HOME || a:pathname == '/'
			return
		endif

		let l:has_link  = 0
		let l:tag_found = 0
		if resolve(a:pathname) != a:pathname
			let l:has_link = 1
		endif

		let s:cscopefile = $HOME."/.vim/cscope/".substitute(a:pathname, '/', '_', 'g').".cscope"
		if filereadable(s:cscopefile)
			execute "cscope add ".s:cscopefile
			let l:tag_found = 1
		endif

		if l:tag_found == 0 && l:has_link == 1
			let s:cscopefile = $HOME."/.vim/cscope/".substitute(resolve(a:pathname), '/', '_', 'g').".cscope"
			if filereadable(s:cscopefile)
				execute "cscope add ".s:cscopefile
				let l:tag_found = 1
			endif
		endif

		unlet s:cscopefile

		call GetCscopeDb(fnamemodify(a:pathname, ":h"))
	endfunction

	function! GenerateCscopeDb()
		let path = input('Create cscope db for: ', getcwd(), 'dir')

		echohl WarningMsg
		echo "Please wait, generating cscope db..."

		let file = tempname()
		let cscopefile = $HOME."/.vim/cscope/".substitute(path, '/', '_', 'g').".cscope"
		call system("cd ".path."; find . -name '*.c' -or -name '*.h' > ".file."; cscope -b -i ".file." -f ".cscopefile)
		call delete(file)

		redraw
		echo "Please wait, generating cscope db... Done"
		echohl None

		call GetCscopeDb(path)
	endfunction
	command! GenerateCscopeDb :call GenerateCscopeDb()
endif
" Let autotags find all cscodepeDb
"	LoadLocalCscopeDb

""	if has("cscope")
""	    map <F9>   :call GetCscopeDb(expand("%:p:h")) <CR><CR>
""	    map <S-F9> :call GenerateCscopeDb() <CR><CR>
""	    map <M-F9> :call GetLocalCscopeDb(expand("%:p:h"))  <CR><CR>
""	endif

" cat Makefile | grep '\-I\/' | tr '[:space:]' '\n' | grep '\-I/' | sort -u | tr '\n' ' '
" build tags database with shift+F8 or alt+F8 to ignore /usr/include
"        --c++-kinds=+p  : Adds prototypes in the database for C/C++ files.
"        --fields=+iaS   : Adds inheritance (i), access (a) and function 
"                          signatures (S) information.
"        --extra=+q      : Adds context to the tag name. Note: Without this
"                          option, the script cannot get class members.
let g:build_cmd="make"
func! MenuCB(id, result)
	if a:result == 1
		silent exec "!echo '==Building ctags database==' && ctags --fields=+iaS --extra=+q --totals -R --c++-kinds=+p --exclude=.ccls-cache"
		silent exec "!echo '==Adding system headers==' && find -exec gcc -M  '{}' \\; 2>&- | tr '[:space:]' '\\n' | grep '^/.*' | sort -u | ctags --c-kinds=+px --c++-kinds=+px --fields=+iaS --extra=+q -aL-"
		silent exec "!echo '==Building cscope database==' && cscope -bR"
		silent "cscope reset"
		silent "cscope add cscope.out"
		exec 'redraw!'
	elseif a:result == 2
		silent exec "!echo '==Building ctags database==' && ctags --fields=+iaS --extra=+q --totals -R --c++-kinds=+p"
		silent exec "!echo '==Building cscope database==' && cscope -bkR"
		silent "cscope reset"
		silent "cscope add cscope.out"
		exec 'redraw!'
	elseif a:result == 3
		call AutotagsUpdate()
	elseif a:result == 4
		call AutotagsAdd()
	elseif a:result == 5
		execute "!" . g:build_cmd . " --dry-run --always-make | grep -wE 'gcc|g++|cc' | grep -w '\\-c' | jq -nR '[inputs|{directory:\".\", command:., file: match(\" [^ ]+$\").string[1:]}]' > compile_commands.json"
	elseif a:result == 6 "https://github.com/rizsotto/Bear
		execute "!bear --" g:build_cmd "--always-make"
	elseif a:result == 7 "https://github.com/nickdiego/compiledb
		execute "!compiledb -n" g:build_cmd
	elseif a:result == 8 "https://github.com/rizsotto/scan-build
		execute "!analyze-build"
	endif
endfunc

command! ShowMenuCodeDb
			\ :call popup_menu(['tag/csope', 'tag/cscope Kernel', 'Autotags update', 'Autotags add dependancy','simple compile_commands', 'bear', "compiledb", "analyse build"], #{
			\ title: "Code database for ".g:build_cmd,
			\ callback: 'MenuCB', highlight: 'Question', padding: [1,1,0,1]} )


if v:version >= 800 " or 820?
	noremap <S-F8> :ShowMenuCodeDb <CR>
else
	noremap <S-F8> :call MenuCB(0, 1)<CR>
endif
map <M-F8> :call MenuCB(0, 2)<CR>
