有vim完整的#include行

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

#include {here}

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

回答

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

注意:此处(尚未)使用 'path' 选项。

但是如何根据 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

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

该函数以两种不同的方式调用:

  • 首先调用该函数以查找要完成的文本的开头。
  • 稍后调用该函数以实际查找匹配项。

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

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


以上是有vim完整的#include行的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>