工欲善其事,必先利其器,第一次從頭開始打造自己的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, "http:// Copyright (C) 2014 - All Rights Reserved")
call append(line("."), "http:// 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