有 vim 个完整的 #include 行

Have vim complete #include lines

假设您正在编辑一个 .c 文件,并且您在一行中:

#include {here}

然后你按tab键,有没有办法让它完成所有相对于当前目录的头文件以及所有系统范围的头文件,如stdio.h和stdlib.h?

可悲的是,:help compl-filename 说:

Note: the 'path' option is not used here (yet).

但是如何根据 Vim 文档中的示例将我们自己的自定义完成组合在一起?

这是我们要使用的内容,可在 :help complete-functions:

下找到
fun! CompleteMonths(findstart, base)
    if a:findstart
        " locate the start of the word
        let line = getline('.')
        let start = col('.') - 1
        while start > 0 && line[start - 1] =~ '\a'
            let start -= 1
        endwhile
        return start
    else
        " find months matching with "a:base"
        let res = []
        for m in split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec")
            if m =~ '^' . a:base
                call add(res, m)
            endif
        endfor
       return res
    endif
endfun
set completefunc=CompleteMonths

这是对其工作原理的高级解释:

The function is called in two different ways:

  • First the function is called to find the start of the text to be completed.
  • Later the function is called to actually find the matches.

在代码中,条件的第一部分处理第一次调用,不需要更改。我们要更改的是处理第二个调用的第二部分。由于我们想要 &path 中的文件,我们可以使用 :help globpath() 和给定的基数来列出 &path:help fnamemodify() 下的匹配文件,仅 return 文件名:

function! CompleteFromPath(findstart, base)
    if a:findstart
        " locate the start of the word
        let line = getline('.')
        let start = col('.') - 1
        while start > 0 && line[start - 1] =~ '\a'
            let start -= 1
        endwhile
        return start
    else
        return globpath(&path, a:base . '*.h', 0, 1)
            \ ->map({ idx, val -> fnamemodify(val, ':t') })
    endif
endfunction
set completefunc=CompleteFromPath