打造VIM利器

工欲善其事,必先利其器,第一次从头开始打造自己的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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容