你的位置:首页 > 操作系统

[操作系统]打造VIM IDE(针对C语言开发者)


================================
使用vim打造IDE, 针对C语言开发者
建议使用gvim
================================

先上两个截图

 

 

# 安装ctags
1. 下载地址: http://ctags.sourceforge.net/

# 安装cscope
1. 下载地址: http://cscope.sourceforge.net/
2. 修改源码,使其支持递归搜索文件夹的软链接
   修改文件: dir.c
   修改方式: 替换函数调用 lstat 全部替换为 stat
3. 编译源码可能出现的错误
   错误: fatal error: curses.h: No such file or directory
   解决: sudo apt install libncurses5-dev libncursesw5-dev

# 安装ruby, command-t插件会用到
  sudo apt install ruby ruby-dev

# 安装vim, vim-gtk
  sudo apt install vim vim-gtk

# 在home目录下创建 .vimrc 并编辑
  1. 将附录1中 vimrc 的内容拷贝进去

# 在home目录下创建 .vim 目录
  1. 进入 .vim 目录
  2. 创建目录 autoload  bundle  colors  syntax

# 在 ~/.vim/colors 目录中创建 mycolor.vim 并编辑
  1. 将附录2中 mycolor.vim 的内容拷贝进去

# 在 ~/.vim/syntax 目录中创建 c.vim 并编辑
  1. 将附录3中 c.vim 的内容拷贝进去

# 下载插件 vundle 到 ~/.vim/bundle
  1. git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
  2. 需要安装 git
  3. vundle 可以自动安装和更新其他vim插件

# 下载插件 pathogen 到 ~/.vim/autoload
  1. curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
  2. 需要安装 curl
  3. pathogen 可以自动加载插件

# 安装其余 vim 插件
  1. 打开 vim 或 gvim
  2. 执行 :PluginInstall

# 编译 command-t插件
  1. 进入 ~/.vim/bundle/command-t/ruby/command-t目录
  2. 执行 ruby extconf.rb
  3. 执行 make

# 编译 YouCompleteMe 插件
  1. 进入 ~/.vim/bundle/YouCompleteMe
  2. 执行 ./install.py --clang-completer
  3. 需要安装 cmake

# 创建 tag 生成和高亮脚本
  1. 找一个地方创建 htags.sh 文件,注意同时修改 .vimrc 中该脚本的路径
  2. 将附录4中 htags.sh 的内容拷贝进去
  3. 给htags.sh增加执行权限 chmod u+x htags.sh


# 生成 ctags 和 cscope 的标签并高亮
  1. 在工程的根目录打开 gvim 或 vim
  2. 使用快捷键 \bt 创建 ctags的标签
  3. 使用快捷键 \bc 创建 cscope的标签
  4. 使用快捷见 \ht 对重新高亮标签
     *每次启动vim时会自动导入一次, 如果没有
      重新生成标签就不要重新导入

# 使用YouCompleteMe的自动补全功能
  1. 在工程的根目录或创建 .ycm_extra_conf.py
  2. 将附录5中 .ycm_extra_conf.py 内容拷贝到其中
  3. 根据工程修改其中的头文件路径

附录1 .vimrc

"===================通用配置======================"文件搜索路径set path=.,/usr/include,," 控制set nocompatible       "关闭vi兼容filetype off         "关闭文件类型侦测,vundle需要set fileencodings=utf-8,gbk  "使用utf-8或gbk编码方式syntax on           "语法高亮set backspace=2        "退格键正常模式set whichwrap=<,>,[,]     "当光标到行首或行尾,允许左右方向键换行set autoread         "文件在vim外修改过,自动重载   set nobackup         "不使用备份set confirm          "在处理未保存或只读文件时,弹出确认消息  set scrolloff=3        "光标移动到距离顶部或底部开始滚到距离set history=1000       "历史记录数set mouse=          "关闭鼠标set selection=inclusive    "选择包含最后一个字符set selectmode=mouse,key   "启动选择模式的方式set completeopt=longest,menu "智能补全,弹出菜单,无歧义时才自动填充set noswapfile        "关闭交换文件set hidden          "允许在有未保存的修改时切换缓冲区"显示colorscheme mycolor      "选择配色方案set t_Co=256         "可以使用的颜色数目set number          "显示行号set laststatus=2       "显示状态行set ruler           "显示标尺set showcmd          "显示输入的命令set showmatch         "高亮括号匹配set matchtime=1        "匹配括号高亮的时间(十分之一秒)set matchpairs={:},(:)     "匹配括号"{}""()"  set hlsearch         "检索时高亮匹配项set incsearch         "边检索边显示匹配set go-=T           "去除gvim的toolbar"格式set noexpandtab        "不要将tab转换为空格set shiftwidth=4       "自动缩进的距离,也是平移字符的距离set tabstop=4         "tab键对应的空格数set autoindent        "自动缩进set smartindent        "智能缩进"===================按键映射======================"按键映射的起始字符let mapleader = '\'       "使用Ctrl-l 和 Ctrl+h 切换标签页nnoremap <C-l> gt      nnoremap <c-h> gT"在行末加上分号nnoremap <silent> <Leader>; :<Esc><End>a<Space>;<Esc><Down>"保存nnoremap <C-s> :w<CR>"替换nnoremap <C-h> :%s/<C-R>=expand("<cword>")<CR>/<C-R>=expand("<cword>")<CR>"===================插件管理======================" 下载vundle" git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim" 下载pathogen" curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim" 将vundle加入到runtime pathset rtp+=~/.vim/bundle/Vundle.vim" 下载到bundle目录的插件call vundle#begin()" plugin on GitHub repoPlugin 'VundleVim/Vundle.vim'Plugin 'scrooloose/nerdtree'Plugin 'Lokaltog/vim-powerline.git'Plugin 'wincent/command-t'Plugin 'Valloric/YouCompleteMe'Plugin 'tomtom/tlib_vim'Plugin 'tomtom/viki_vim'" plugin from http://vim-scripts.org/vim/scripts.htmlPlugin 'taglist.vim'Plugin 'EasyGrep'" Git plugin not hosted on GitHub" Plugin 'git://...'" git repos on your local machine" Plugin 'file://...'call vundle#end()filetype plugin indent on  " required"===================插件配置======================"-----pathogen-----execute pathogen#infect() "-----NERDTree-----let g:NERDTreeCaseSensitiveSort = 1let g:NERDTreeWinSize = 25let g:NERDTreeWinPos = "right"nnoremap <silent> <Leader>t :NERDTreeToggle<CR> nnoremap <silent> <Leader>o :NERDTreeFind<CR>"-----Powerline-----set fillchars+=stl:\ ,stlnc:\let g:Powerline_symbols = 'compatible'let g:Powerline_stl_path_style = 'filename' "只显示文件名"-----Command-T-----let g:CommandTFileScanner = 'ruby'  "使用ruby作为文件浏览器let g:CommandTTraverseSCM = 'dir'  "根目录为执行vim时所在的目录 "打开文件跳转nnoremap <silent> <Leader>f :CommandT<CR>"-----taglist-----let Tlist_Show_One_File = 1      "只显示当前文件的taglistlet Tlist_Exit_OnlyWindow = 1     "taglist是最后一个窗口时退出vimlet Tlist_Use_Left_Window = 1     "在左侧窗口显示taglistlet Tlist_GainFocus_On_ToggleOpen = 1 "打开taglist时,光标停在taglist窗口let Tlist_Auto_Update = 1        "自动更新" 打开标签浏览器nnoremap <silent><Leader>dt :Tlist<CR>" 重新生成标签 nnoremap <silent><Leader>bt :!~/Myfiles/Tool/sh/ctags/hitags.sh<CR>" 高亮标签nnoremap <silent><Leader>ht :so tags.vim<CR>"-----cscope-----"加载cscope库if filereadable("cscope.out")  cs add cscope.outendifset cscopequickfix=s-,c-,d-,i-,t-,e- "使用quickfix窗口显示结果set cst               "跳转时也使用cscope库"打开引用窗口nnoremap <silent><Leader>cw :cw<CR>"重新生成索引文件nnoremap <silent><Leader>bc :!cscope -Rbq<CR>"s: 查找本C符号"g: 查找本定义"d: 查找本函数调用的函数"c: 查找调用本函数的函数"t: 查找本字符串"e: 查找本egrep模式"f: 查找本文件"i: 查找包含本文件的文件nnoremap <C-\>s :scs find s <C-R>=expand("<cword>")<CR><CR>nnoremap <C-\>g :scs find g <C-R>=expand("<cword>")<CR><CR>nnoremap <C-\>c :scs find c <C-R>=expand("<cword>")<CR><CR>nnoremap <C-\>t :scs find t <C-R>=expand("<cword>")<CR><CR>nnoremap <C-\>e :scs find e <C-R>=expand("<cword>")<CR><CR>nnoremap <C-\>f :scs find f <C-R>=expand("<cfile>")<CR><CR>nnoremap <C-\>i :scs find i <C-R>=expand("<cfile>")<CR><CR>nnoremap <C-\>d :scs find d <C-R>=expand("<cword>")<CR><CR>"-----YouCompleteMe-----let g:ycm_server_python_interpreter= '/usr/bin/python2'let g:ycm_global_ycm_extra_conf = '~/.ycm_extra_conf.py' "默认配置文件let g:ycm_key_invoke_completion = '<C-Tab>'     "跨文件补全let g:ycm_confirm_extra_conf = 0          "关闭加载配置文件提示let g:ycm_cache_omnifunc = 0            "关闭补全缓存let g:ycm_enable_diagnostic_signs = 0        "关闭诊断提示符let g:ycm_enable_diagnostic_highlighting = 1    "关闭诊断高亮"let g:ycm_show_diagnostics_ui = 0          "关闭诊断uilet g:ycm_min_num_of_chars_for_completion = 3    "n字符开始自动补全"获取变量类型nnoremap <silent><Leader>yt :YcmCompleter GetType<CR>"跳转定义或声明nnoremap <silent><Leader>yg :YcmCompleter GoTo<CR>"跳转包含文件nnoremap <silent><Leader>yi :YcmCompleter GoToInclude<CR>"打开诊断信息nnoremap <silent><Leader>yd :YcmDiags<CR>"-----EasyGrep-----let EasyGrepMode = 2    "根据文件类型搜索相应文件let EasyGrepRecursive = 1  "递归搜索let EasyGrepCommand = 1   "使用greplet EasyGrepJumpToMatch = 0 "不要跳转

 

附录2 mycolor.vim

" Vim color file" Maintainer:  Hans Fugal <hans@fugal.net>" Last Change:  $Date: 2004/06/13 19:30:30 $" Last Change:  $Date: 2004/06/13 19:30:30 $" URL:    http://hans.fugal.net/vim/colors/desert.vim" Version:  $Id: desert.vim,v 1.1 2004/06/13 19:30:30 vimboss Exp $" cool help screens" :he group-name" :he highlight-groups" :he cterm-colorsset background=darkif version > 580  " no guarantees for version 5.8 and below, but this makes it stop  " complaining  hi clear  if exists("syntax_on")  syntax reset  endifendiflet g:colors_name="desert"hi Normal  guifg=White guibg=grey20" highlight groupshi Cursor  guibg=khaki guifg=slategrey"hi CursorIM"hi Directory"hi DiffAdd"hi DiffChange"hi DiffDelete"hi DiffText"hi ErrorMsghi VertSplit  guibg=#c2bfa5 guifg=grey50 gui=nonehi Folded  guibg=grey30 guifg=goldhi FoldColumn  guibg=grey30 guifg=tanhi IncSearch  guifg=slategrey guibg=khaki"hi LineNrhi ModeMsg  guifg=goldenrodhi MoreMsg  guifg=SeaGreenhi NonText  guifg=LightBlue guibg=grey30hi Question  guifg=springgreenhi Search  guibg=peru guifg=wheathi SpecialKey  guifg=yellowgreenhi StatusLine  guibg=#c2bfa5 guifg=black gui=nonehi StatusLineNC  guibg=#c2bfa5 guifg=grey50 gui=nonehi Title  guifg=indianredhi Visual  gui=none guifg=khaki guibg=olivedrab"hi VisualNOShi WarningMsg  guifg=salmon"hi WildMenu"hi Menu"hi Scrollbar"hi Tooltip" syntax highlighting groupshi Comment  guifg=SkyBluehi Constant  guifg=#ffa0a0hi Identifier  guifg=palegreenhi Statement  guifg=khakihi PreProc  guifg=indianredhi Type    guifg=darkkhakihi Special  guifg=navajowhite"hi Underlinedhi Ignore  guifg=grey40"hi Errorhi Todo    guifg=orangered guibg=yellow2" color terminal definitionshi SpecialKey  ctermfg=darkgreenhi NonText  cterm=bold ctermfg=darkbluehi Directory  ctermfg=darkcyanhi ErrorMsg  cterm=bold ctermfg=7 ctermbg=1hi IncSearch  cterm=NONE ctermfg=yellow ctermbg=greenhi Search  cterm=NONE ctermfg=grey ctermbg=bluehi MoreMsg  ctermfg=darkgreenhi ModeMsg  cterm=NONE ctermfg=brownhi LineNr  ctermfg=3hi Question  ctermfg=greenhi StatusLine  cterm=bold,reversehi StatusLineNC cterm=reversehi VertSplit  cterm=reversehi Title  ctermfg=5hi Visual  cterm=reversehi VisualNOS  cterm=bold,underlinehi WarningMsg  ctermfg=1hi WildMenu  ctermfg=0 ctermbg=3hi Folded  ctermfg=darkgrey ctermbg=NONEhi FoldColumn  ctermfg=darkgrey ctermbg=NONEhi DiffAdd  ctermbg=4hi DiffChange  ctermbg=5hi DiffDelete  cterm=bold ctermfg=4 ctermbg=6hi DiffText  cterm=bold ctermbg=1hi Comment  ctermfg=darkcyanhi Constant  ctermfg=brownhi Special  ctermfg=5hi Identifier  ctermfg=6hi Statement  ctermfg=3hi PreProc  ctermfg=5hi Type    ctermfg=2hi Underlined  cterm=underline ctermfg=5hi Ignore  cterm=bold ctermfg=7hi Ignore  ctermfg=darkgreyhi Error  cterm=bold ctermfg=7 ctermbg=1"vim: sw=4

 

附录3 c.vim

"not wrapset nowrapif filereadable("tags.vim")  so tags.vimendifhi cFunction guifg=LightGreenhi cMacro  guifg=LightRedhi cGlobal  guifg=LightBluehi cMember  guifg=LightMagentahi def link cTypedef cType

 

附录4 htags.sh

#!/bin/bashctags -R --fields=+l ;awk -F '"' '$2 ~ /^\tf/  {print $1 "\n"}' tags | awk '$1 ~ /^[a-zA-Z]/ {print "syn keyword cFunction " $1}' 1> tags.vim ;awk -F '"' '$2 ~ /^\t[de]/ {print $1 "\n"}' tags | awk '$1 ~ /^[a-zA-Z]/ {print "syn keyword cMacro " $1}'  1>> tags.vim ;awk -F '"' '$2 ~ /^\tt/  {print $1 "\n"}' tags | awk '$1 ~ /^[a-zA-Z]/ {print "syn keyword cTypedef " $1}' 1>> tags.vim ;awk -F '"' '$2 ~ /^\tv/  {print $1 "\n"}' tags | awk '$1 ~ /^[a-zA-Z]/ {print "syn keyword cGlobal " $1}'  1>> tags.vim ;

 

附录5 .ycm_extra_conf.py

import osflags = [  '-x',  'c',  '-Wall',  '-DOS=LINUX',  '-I./mycode/igmpsnoop/h',  '-I./mycode/mldsnoop/h',  '-I./mycode/head_files',  '-I./mycode/g8132/inc',  '-I./mycode/nqa/inc',  '-I./mycode/mplste/inc',  '-I./mycode/mplsoam/inc',  '-I./mycode/cli',  '-I./mycode/trill/inc',  '-I./mycode/igmpsnoop_onu/inc',  '-I./mycode/hqos/inc',  '-I./mycode/qos/inc',  '-I./mycode/mplsqos/inc',  '-I./mycode/pim/inc',  '-I./USP_HEADFILE/protocol/acl/h',  '-I./USP_HEADFILE/protocol/hwroute/h',  '-I./USP_HEADFILE/protocol/uspIf/inc',  '-I/home/taopeng/Workspace/vmware/linux_share/osal_linux/inc',  '-I/home/taopeng/Workspace/vmware/linux_share/usp_linux3.12.17/inc']def MakeFinalFlag():  workDir = os.path.dirname(os.path.abspath(__file__)) finalFlags = [] for flag in flags:  if flag.startswith('-I'):   path = flag[len('-I'):]   flag = '-I' + os.path.join(workDir, path)    finalFlags.append(flag) return finalFlags def FlagsForFile(fileName, **kwargs):  return {  'flags': MakeFinalFlag(),  'do_cache': True }if __name__ == '__main__':  print(FlagsForFile("test"))