您的位置:首页 > 其它

Vim插件之引入头文件

2013-04-09 21:03 141 查看
这几天一直在折腾Vim开发环境,Vim下面无法引入头文件,eclipse 的CDT好歹还有头文件提示(ominicomplete貌似我是无法完成的),eclipse JDT更是能够import类包

于是动手自己写了一个vim插件,其实也不是很方便,这个插件依赖A.vim和taglist.vim,基本原理是在某个单词(函数或类)tag上输入命令,先自动跳转到tag定义的文件,然后找到头文件,取出该文件的绝对路径,与tags目录进行比较,得到相对于tag的相对路径,所以,这也要求tags的设置是头文件的寻找路径,并且存在一定错误的几率,不过聊胜于无,能省力多少就省力多少吧。熟悉一下vim插件的开发

if exists("loaded_generate_include_corey")
finish
endif
let loaded_generate_include_corey=1

"将include语句添加到当前include语句之后
function <SID>AddIncludeClause(includeClause)
let s:curline=line(".")
while s:curline>0
let s:line=getline(s:curline)
if stridx(s:line,"#include")>=0
break
else
let s:curline-=1
endif
endwhile
call append(s:curline,a:includeClause)
endfunction

"判断是否为绝对路径
function IsAbsPath(path)
let s:firstChar=strpart(a:path,0,1)
if s:firstChar=="/"
return 1
else
return 0
endif
endfunction

"获取绝对路径,如果是相对路径会进行转换
function GetAbsPath(path)
let s:fc=strpart(a:path,0,1)
if IsAbsPath(a:path)
return a:path
elseif s:fc=="."
return substitute(a:path,"^\.",getcwd(),"")
else
return getcwd()."/".a:path
endif
endfunction
"是否是头文件
function IsHeadFile(path)
let s:extendname=strpart(a:path,strlen(a:path)-2,2)
if s:extendname==".h" || s:extendname==".H"
return 1
else
return 0
endif
endfunction

"获取tags变量的绝对路径
function GetTags()
let s:tagpaths=split(&tags,",")
let s:index=0
let s:abspaths=s:tagpaths
while s:index<len(s:tagpaths)
let s:abspath=GetAbsPath(get(s:tagpaths,s:index))
let s:abspathdir=GetCurDir(s:abspath)
"echo s:abspathdir
let s:abspaths[s:index]=s:abspathdir
"echo s:abspaths[s:index]
let s:index+=1
"add(s:abspaths,s:abspathdir)

endwhile
return s:abspaths
endfunction

"获取当前路径的文件夹
function GetCurDir(path)
return strpart(a:path,0,strridx(a:path,"/")+1)
endfunction

"打印tags,用于调试
function ShowTags()
echo GetTags()
endfunction
"获取头文件的相对路径
function GetHeaderFileName(headerFileAbsPath)
let index=0
let s:tl=GetTags()
while index<len(s:tl)
let _tag=get(s:tl,index)
if stridx(a:headerFileAbsPath,_tag)>=0
return substitute(a:headerFileAbsPath,_tag,"","")
else
let index+=1
endif
endwhile
return a:headerFileAbsPath
endfunction
"功能函数
function <SID>GoToTag()
try
"execute ":tag vector"
execute "normal \<C-]>"
if !IsHeadFile(bufname("%"))
execute ":A"
endif
let s:headname=bufname("%")
let s:absheadname=GetAbsPath(s:headname)
let s:relheadname=GetHeaderFileName(s:absheadname)

let s:clause="#include <". s:relheadname .">"
call setreg('',s:clause)
execute "normal \<C-t>"
call <SID>AddIncludeClause(s:clause)
catch
echo "include header failure,please save file at first!"
endtry
endfunction
"映射
nnoremap zx :call <SID>GoToTag()<CR>


我们只需要在响应的tag按下zz,就会将include <***>语句添加到当前文件的已有include语句后面
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: