如何检查ALE是否找到compile_commands.json并动态配置编译选项?
解决方案
ALE本身并没有提供g:ale_found_compile_commands_file这类全局变量来直接检测是否成功找到compile_commands.json文件,所以你给出的那段Vimscript无法直接生效。不过可以通过自己实现查找逻辑来达成需求,具体步骤如下:
1. 编写Vimscript函数模拟ALE的查找规则
ALE查找compile_commands.json的逻辑是从当前打开文件所在目录向上遍历,直到根目录或找到目标文件。我们可以用Vimscript实现相同的查找逻辑:
function! HasCompileCommands() abort " 获取当前文件所在的绝对路径目录 let l:current_dir = expand('%:p:h') " 向上遍历目录,直到根目录 while l:current_dir != '/' && l:current_dir != '.' " 检查当前目录下是否存在可读的compile_commands.json if filereadable(l:current_dir . '/compile_commands.json') return 1 endif " 进入父目录 let l:current_dir = fnamemodify(l:current_dir, ':h') endwhile return 0 endfunction
2. 根据查找结果设置选项
调用上面的函数,动态设置g:ale_c_cc_options:
" 确保ALE启用了compile_commands.json解析(默认已启用,显式设置更稳妥) let g:ale_c_parse_compile_commands = 1 if HasCompileCommands() let g:ale_c_cc_options = '' else let g:ale_c_cc_options = '-ansi -pedantic -Wall' endif
这个方案的核心是通过模拟ALE的目录遍历逻辑,自行判断compile_commands.json是否存在,从而实现不同的选项配置。
内容的提问来源于stack exchange,提问作者sage
相关产品推荐
相关产品推荐

