工欲善其事,必先利其器,第一次从头开始打造自己的vim,特记录下流程~
安装插件有:bundle, YouCompleteMe, NERDTree, TagList, winmanager
-
安装VIM
因为要安装补全神器YouCompleteMe, 所以经历了好一番折腾,首先要升级vim,vim版本要求7.4以上,可通过vim --version查看当前版本,要注意还需要正确安装python的扩展
下载源码编译安装,参考 http://www.linuxidc.com/Linux/2014-04/99717.htm
如果缺少库的话需要安装某些库,可能需要安装python-devel(python-devel-2.6.6-52.el6.x86_64)和ncurses-devel(ncurses-devel-5.7-3.20090208.el6.i686)
编译安装:./configure --with-features=huge --enable-rubyinterp --enable-pythoninterp --with-python-config-dir=/usr/lib64/python2.6/config --enable-perlinterp --enable-gui=gtk2 --enable-cscope --enable-luainterp --enable-perlinterp --enable-multibyte --prefix=/usr/local/vim74/
--with-python-config-dir:要找到python-devel的库的安装路径,我的安装后在/usr/lib64/python2.6/config路径下
--prefix:代表要安装的路径
安装完成后,直接拿软链链过去即可,ln -s /usr/local/vim74/bin/vim /usr/bin/vim
- 安装bundle和其他插件
bundle可用来管理vim的插件,支持自动下载安装
git clone https://github.com/gmarik/vundle.git
下载安装上面提到的所有插件,YouCompleteMe还需要更进一步的手动编译安装,先下载下来
~/.vim/bundle/vundle
然后,编辑~/.vimrc文件
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
"
Plugin 'VundleVim/Vundle.vim'
Plugin 'Valloric/YouCompleteMe'
let g:ycm_global_ycm_extra_conf = '~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py'
let g:ycm_confirm_extra_conf=0 "关闭加载.ycm_extra_conf.py提示
nnoremap <leader>jd :YcmCompleter GoToDefinitionElseDeclaration<CR>
let g:ycm_collect_identifiers_from_tag_files = 1
let g:ycm_semantic_triggers = {
\ 'c' : ['->', ' ', '.', ' ', '(', '[', '&'],
\ 'cpp,objcpp' : ['->', '.', ' ', '(', '[', '&', '::'],
\ 'perl' : ['->', '::', ' '],
\ 'php' : ['->', '::', '.'],
\ 'cs,java,javascript,d,vim,python,perl6,scala,vb,elixir,go' : ['.'],
\ 'ruby' : ['.', '::'],
\ 'lua' : ['.', ':']
\ }Plugin 'scrooloose/nerdtree'
Plugin 'taglist.vim'
"如果Taglist窗口是最后一个窗口时退出VIM
let Tlist_Exit_OnlyWindow = 1
let Tlist_Ctags_Cmd="/usr/bin/ctags" "将taglist与ctags关联
Plugin 'winmanager'
let g:winManagerWindowLayout="NERDTree|TagList"
let g:NERDTree_title="[NERDTree]"
function! NERDTree_Start()
exec 'NERDTree'
endfunction
function! NERDTree_IsValid()
return 1
endfunction
nmap <silent> <F2> :if IsWinManagerVisible() <BAR> WMToggle<CR> <BAR> else <BAR> WMToggle<CR>:q<CR> endif <CR><CR>
" All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" :PluginList - lists configured plugins
" :PluginInstall - installs plugins; append!
to update or just :PluginUpdate
" :PluginSearch foo - searches for foo; append!
to refresh local cache
" :PluginClean - confirms removal of unused plugins; append!
to auto-approve removal
"
" see :h vundle for more details or wiki for FAQ
" Put your non-Plugin stuff after this line
"
保存退出,打开vim,输入 :BundleInstall 进行自动安装
- 安装YouCompleteMe
./install.sh --clang-completer 参数是为了支持c/c++ 的补全
安装成功后,会在YouCompleteMe的文件夹下出现ycm_core.so和libclang.so.3.8,代表编译成功
但运行的时候可能会出现错误,我的环境出现了glibc版本较低的问题,打开~/.vimrc可以看到错误(类似"libc.so.6: version `GLIBC_2.14' not found"),参考http://blog.csdn.net/bboxhe/article/details/46849167
升级GLIBC到最高版本,错误就没有了
此时运行YouCompleteMe发现,无法对系统库进行自动补全,是因为用到了clang的一些库文件,根据上面的链接,直接下载编译好的clang
wget http://llvm.org/releases/3.5.1/clang+llvm-3.5.1-x86_64-fedora20.tar.xz
xz -d clang+llvm-3.5.1-x86_64-fedora20.tar.xz
tar xvf clang+llvm-3.5.1-x86_64-fedora20.tar
cd clang+llvm-3.5.1-x86_64-fedora20
然后cd到clang可执行文件的文件夹,执行
echo | clang -std=c++11 -stdlib=libc++ -v -E -x c++ -
需要将产生的头文件放到~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py文件中,YouCompleteMe就是根据此python文件寻找相应的头文件进行补全(在vimrc的配置中已经默认加载此全局文件,也可以写在源文件的文件夹下面,会层层向上寻找此文件进行加载)
修改后的.py文件为
# This file is NOT licensed under the GPLv3, which is the license for the rest of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to http://unlicense.org/
import os
import ycm_core
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
#'-Werror',
#'-Wc++98-compat',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-stdlib=libc++',
# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which
# language to use when compiling headers. So it will guess. Badly. So C++
# headers will be compiled as C headers. You don't want that so ALWAYS specify
# a "-std=<something>".
# For a C project, you would set this to something like 'c99' instead of
# 'c++11'.
'-std=c++11',
# ...and the same thing goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x',
'c++',
'-I',
'.',
'-isystem',
'/usr/include',
'-isystem',
'/usr/local/include',
'-isystem',
'/data/tool/clang+llvm-3.5.1-x86_64-fedora20/bin/../include/c++/v1',
'-isystem',
'/data/tool/clang+llvm-3.5.1-x86_64-fedora20/bin/../lib/clang/3.5.1/include'
]
# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''
if os.path.exists( compilation_database_folder ):
database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
database = None
SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]
def DirectoryOfThisScript():
return os.path.dirname( os.path.abspath( file ) )
def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
if not working_directory:
return list( flags )
new_flags = []
make_next_absolute = False
path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
for flag in flags:
new_flag = flag
if make_next_absolute:
make_next_absolute = False
if not flag.startswith( '/' ):
new_flag = os.path.join( working_directory, flag )
for path_flag in path_flags:
if flag == path_flag:
make_next_absolute = True
break
if flag.startswith( path_flag ):
path = flag[ len( path_flag ): ]
new_flag = path_flag + os.path.join( working_directory, path )
break
if new_flag:
new_flags.append( new_flag )
return new_flags
def IsHeaderFile( filename ):
extension = os.path.splitext( filename )[ 1 ]
return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
def GetCompilationInfoForFile( filename ):
# The compilation_commands.json file generated by CMake does not have entries
# for header files. So we do our best by asking the db for flags for a
# corresponding source file, if any. If one exists, the flags for that file
# should be good enough.
if IsHeaderFile( filename ):
basename = os.path.splitext( filename )[ 0 ]
for extension in SOURCE_EXTENSIONS:
replacement_file = basename + extension
if os.path.exists( replacement_file ):
compilation_info = database.GetCompilationInfoForFile(
replacement_file )
if compilation_info.compiler_flags_:
return compilation_info
return None
return database.GetCompilationInfoForFile( filename )
def FlagsForFile( filename, **kwargs ):
if database:
# Bear in mind that compilation_info.compiler_flags_ does NOT return a
>
# python list, but a "list-like" StringVec object
compilation_info = GetCompilationInfoForFile( filename )
if not compilation_info:
return None
final_flags = MakeRelativePathsInFlagsAbsolute(
compilation_info.compiler_flags_,
compilation_info.compiler_working_dir_ )
# NOTE: This is just for YouCompleteMe; it's highly likely that your project
# does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR
# ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT.
#try:
# final_flags.remove( '-stdlib=libc++' )
#except ValueError
# pass
else:
relative_to = DirectoryOfThisScript()
final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )
return {
'flags': final_flags,
'do_cache': True
}
上述黑体部分-isystem替换为上面clang命令后的文件路径即可,这样,利用YCM就可以自动补全系统库,并使用\jd跳转至定义或声明处;ctrl+o返回
在自己所在项目的根结点下建立.ycm_extra_conf.py,在项目子文件夹下写代码时,会向上一直寻找.ycm_extra_conf.py,加载.(当前目录),因此也就能够正常加载下面所有的头文件,只要路径保持一致
我的环境,因为proto文件编译在单独的文件夹下,因此还要单独加入对应的文件夹,-I表示用户自定义的头文件
'-I',
'/data/trunk/build64_release'
至此,已经完全可以抛弃ctags了
- vim其他配置
func SetTitle()
if &filetype == 'python'
call setline(1, "#!/usr/bin/env python")
call append(line("."), "# -- coding: utf-8 --")
call append(line(".")+1, """"")
call append(line(".")+2, "File: ".expand("%"))
call append(line(".")+3, "Author: tianxinheihei")
call append(line(".")+4, "Date: ".strftime("%Y/%m/%d %H:%M:%S"))
call append(line(".")+5, """"")
call append(line(".")+6, "")
elseif &filetype == 'sh'
call setline(1, "#!/bin/bash")
call append(line("."), "# Copyright (C) 2014- All Rights Reserved")
call append(line(".")+1, "# Author: tianxinheihei")
call append(line(".")+2, "")
else
call setline(1, "// Copyright (C) 2014 - All Rights Reserved")
call append(line("."), "// Author: tianxinheihei")
call append(line(".")+1, "")
endif
endfunction
set backspace=indent,eol,start
set nu
set tabstop=2
set expandtab
set shiftwidth=2
set smartindent
"set fileencodings=utf-8,gb2312,usc-bom,cp936,euc-cn
:set pastetoggle=<F9>
autocmd BufNewFile *.cpp,*.[ch],*.sh,*.py call SetTitle() | exe "normal G" 可以自动填补文件头
if has("autocmd")
au BufReadPost * if line("'"") > 1 && line("'"") <= line("$") | exe "normal! g'"" | endif
endif "打开文件后光标定位到上次位置
set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [POS=%l,%v][%p%%]\ %{strftime("%d/%m/%y\ -\ %H:%M")} "状态行显示的内容
set laststatus=2 " 启动显示状态行(1),总是显示状态行(2)
set hlsearch
set fencs=utf-8,ucs-bom,shift-jis,gb18030,gbk,gb2312,cp936
set termencoding=utf-8
set encoding=utf-8
set fileencodings=ucs-bom,utf-8,cp936
set fileencoding=utf-8