在Ubuntu14.04中配置自己的GVIM

本文介绍了在Ubuntu 14.04上配置GVIM及其插件YouCompleteMe的详细步骤,包括安装vim、创建.vim目录、安装Vundle、设置字体和颜色方案、解决QFixToggle插件错误,以及YouCompleteMe的编译过程。通过这个教程,读者可以学会如何为GVIM安装和配置必要的工具。

注:保证你的Ubuntu能够联网

1、首先安装vim7.4以上版本,选择GTK版本(不要选择gnome版本,会出点小问题)

2、在~目录下创建目录.vim:mkdir ~/.vim

3、安装插件管理工具Vundle,将它放到.vim目录中:执行命令

git clone https://github.com/gmarik/vundle.git ~/.vim/bundle/vundle       (先安装git---sudo apt-get install git)

4、安装monaco字体(该字体是苹果上的,漂亮毋庸置疑):在终端执行命令 

curl -kL https://raw.github.com/cstrap/monaco-font/master/install-font-ubuntu.sh| bash (先安装curl工具---sudo apt-get install curl)

5、下载solarized颜色方案(我喜欢的代码背景颜色方案)并放到bundle目录下:执行命令

git clone git://github.com/altercation/vim-colors-solarized.git ~/.vim/bundle

6、在~目录下创建文件.vimrc:

 touch ~/.vimrc

7、使用我已经配好的myvimrc,将里面内容复制到创建好的.vimrc中,在最下面附上myvimrc。

8、在终端打开gvim,会出错,先不管,在命令行模式下执行命令”:BundleInstall,然后就等着自动安装.vimc中的插件吧,在安装过程中,

YouCompleteMe插件下载时间会很久,请慢慢等待。

9、插件安装完成后,会出错,原因是YouCompleteMe(最重要的插件,代码自动补全)没有编译,其他插件都不需要,只是这个插件比较特别,在下面会详细介绍编译方法。

10、先不管插件YouCompleteMe插件,在步骤8中安装完成后,还有个错误是QFixToggle插件,原因在.vimrc文件中有介绍,如下:

linux need exec 'dos2unix ~/.vim/bundle/QFixToggle/plugin/qfixtoggle.vim'

即只需要在终端执行命令:dos2unix ~/.vim/bundle/QFixToggle/plugin/qfixtoggle.vim,然后再重新安装下插件,只需再gvim的命令模式下执行命令:BundleUpddate即可。

11、编译YouCompleteMe插件(重头戏)

1)首先需要安装clang/llvm库

2)在http://llvm.org/releases/下载2个源码,我当时最新版本是3.6:

cfe-3.6.0.src.tar.xz   ,llvm-3.6.0.src.tar.xz

3)分别解压以上2个文件(首先将*.tar.xz解压为*.tar文件,再解压为可打开文件)

$ xz -d cfe-3.6.0.src.tar.xz                 
 $ tar -xvf cfe-3.6.0.src.tar                                  
$ xz -d llvm-3.6.0.src.tar.xz         
 $ tar -xvf llvm-3.6.0.src.tar

4)创建目录

llvm-clang: mkdir ~/llvm-clang

5)将clang源码移动到llvm的相应目录下,使得clang可以和llvm一起编译

$ mv cfe-3.6.src/ llvm-3.6.src/tools/clang/

6)将llvm移动到llvm-clang目录下

$ mv llvm-3.6.0.src ~/llvm-clang/

7)新建目录llvm-build: 

mkdir ~/llvm-clang/llvm-build

8)

$ cd ~/llvm-clang/llvm-build

9)

$ ../llvm-3.3.src/configure  --prefix=/usr/clang_3_6 --enable-optimized --enable-targets=host

10)

$ sudo make或sudo make j 4                                 (注,这一过程很漫长大概要2小时左右,慢慢等。。。)

11)

$ sudo make install

12) export PATH=/usr/clang_3_6/bin:$PATH                          #这一句最好写到~/.bashrc内

13)编译YouCompleMe所依赖的ycm_core.so以及ycm_support_libs库

在执行下面的命令之前,需要将上面生成的libclang.so拷贝到~/.vim/bundle/YouCompleteMe/third_party/ycmd/目录下。

cd ~
mkdir ycm_build
cd ycm_build
cmake -G "Unix Makefiles" . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp
cmake -G "Unix Makefiles" . -DPATH_TO_LLVM_ROOT=~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/llvm 
-DEXTERNAL_LIBCLANG_PATH=~/.vim/bundle/YouCompleteMe/third_party/ycmd/libclang.so ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp
make ycm_core
cp /usr/clang_3_6/lib/libclang.so ~/.vim/bundle/YouCompleteMe/python/libclang.so #这一步是为了使用新的libclang.so
make ycm_support_libs

14)配置.ycm_extra_conf.py ---在~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py这个文件的flags尾部添加:

'/usr/include',
'-isystem',
'/usr/include/c++/'
15)附上我的vimrc文件如下:

"~/.vimrc (configuration file for vim only)

" 设置标签栏的显示,0永远不显示,1两个以上显示,2永远显示
set showtabline=1

" Encoding related
set fileencodings=utf-8,gb2312,gbk,gb18030
set termencoding=utf-8

" 设置字体
if has("gui_running") 
set guifont=monaco\ 10
endif

"""""""""""""""""""""""""""""""""""""""""""""""""""""""
" 键盘命令
"""""""""""""""""""""""""""""""""""""""""""""""""""""""
nmap <leader>w :w!<cr>
nmap <leader>f :find<cr>

" 映射全选+复制 ctrl+a
map <C-A> ggVGY
map! <C-A> <Esc>ggVGY
map <F12> gg=G
" 选中状态下 Ctrl+c 复制
vmap <C-c> "+y
"去空行
" nnoremap <F2> :g/^\s*$/d<CR>
" 比较文件
nnoremap <C-F2> :vert diffsplit
" 新建标签
map <M-F2> :tabnew<CR>
" 列出树状文件目录
" map <F3> :tabnew .<CR>
" 打开树状文件目录
map <C-F3> \be
"C,C++ 按<F9>编译运行
map <F9> :call CompileRunGcc()<CR>
func! CompileRunGcc()
    exec "w"
    if &filetype == 'c'
        exec "!g++ % -o %<"
        exec "! ./%<"
    elseif &filetype == 'cpp'
        exec "!g++ % -o %<"
        exec "! ./%<"
    elseif &filetype == 'java'
        exec "!javac %"
        exec "!java %<"
    elseif &filetype == 'sh'
        :!./%
    endif
endfunc
"C,C++的调试
map <F10> :call Rungdb()<CR>
func! Rungdb()
    exec "w"
    exec "!g++ % -g -o %<"
    exec "!gdb ./%<"
endfunc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""
""实用设置
"""""""""""""""""""""""""""""""""""""""""""""""""""""""
"make 运行
:set makeprg=g++\ -Wall\ \ %
"自动保存
set autowrite
set ruler               " 打开状态栏标尺
set cursorline          " 突出显示当前行


"""""""""""""""""""""""""""""""""""""""""""""""""""""""
" vundle begin
"""""""""""""""""""""""""""""""""""""""""""""""""""""""
filetype off                " required!

set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

" let Vundle manage Vundle
Bundle 'gmarik/vundle'

" vim-scripts repos

"  Improved C++ STL syntax highlighting
Bundle 'STL-improved'

" Displays tags in a window, ordered by class etc, i used it instead of taglist
Bundle 'majutsushi/tagbar'
Bundle 'wesleyche/SrcExpl'

" recommend fetch it from https://github.com/tczengming/autoload_cscope.vim.git which support c and cpp
Bundle 'tczengming/autoload_cscope.vim'

" CmdlineComplete E.g: you want to search for "elephant" in the buffer, just type /ele and
" press Ctrl-P. So long as "elephant" is in the buffer, you will get "ele"
" completed into "elephant". 
Bundle 'CmdlineComplete'
Bundle 'Valloric/YouCompleteMe'
Bundle 'Valloric/ListToggle'

"Code snippets engine for Vim
Bundle 'xptemplate'

Bundle 'DoxygenToolkit.vim'

" C/C++ header files should be guarded against multiple inclusions using preprocessor directives
Bundle 'tczengming/headerGatesAdd.vim'

Bundle 'genutils'
Bundle 'lookupfile'

" Fuzzy file, buffer, mru, tag, ... finder with regexp support.
Bundle 'kien/ctrlp.vim'

" Fast file navigation
Bundle 'wincent/Command-T'

" Preview the definition of variables or functions in a preview window
Bundle 'autopreview'

" Echo the function declaration in the command line for C/C++
Bundle 'echofunc.vim'

Bundle 'grep.vim'
Bundle 'a.vim'
Bundle 'c.vim'
Bundle 'The-NERD-Commenter'
Bundle 'The-NERD-tree'

" Under linux need exec 'dos2unix ~/.vim/bundle/QFixToggle/plugin/qfixtoggle.vim'
Bundle 'QFixToggle'

Bundle 'Color-Sampler-Pack'
Bundle 'altercation/vim-colors-solarized'
Bundle 'txt.vim'

Bundle 'mru.vim'
Bundle 'YankRing.vim'

Bundle 'tpope/vim-surround.git'
Bundle 'ShowMarks'

" Display error marks on line which contain errors after compilation 
Bundle 'cuteErrorMarker'

"Bundle 'Lokaltog/vim-powerline'
Bundle 'bling/vim-airline'

Bundle 'git://github.com/Lokaltog/vim-easymotion.git'

" syntastic
Bundle 'scrooloose/syntastic'

" non github repos
" ...
filetype plugin indent on   " required! 
"""""""""""""""""""""""""""""""""""""""""""""""""""""""
" vundle end
"""""""""""""""""""""""""""""""""""""""""""""""""""""""

" solarized theme
set t_Co=256                " Explicitly tell vim that the terminal supports 256 colors, need before setting the colorscheme
let g:solarized_termcolors=256
colorscheme solarized
set background=dark
hi Normal  ctermfg=252 ctermbg=none     " Transparent background

" Enable syntax highlighting
syntax on

set sm                    " 显示括号配对

set number
set autochdir

set nobackup              " 设置不生成备份文件

" Set to auto read when a file is changed from the outside
set autoread

"set backupdir=~/.vim/backup
"set directory=~/.vim/backup
" set directory=.,$TEMP

set laststatus=2            " always have status-line'
"set statusline=%F%m%r%h%w\ %{&ff}\ %Y\ [ascii:%b\ hex:0x\%02.2B]\ [%{(&fenc\ ==\ \"\"?&enc:&fenc).(&bomb?\",BOM\":\"\")}]\ %=%l/%L,%v\ %p%%

" allow backspacing over everything in insert mode
set backspace=indent,eol,start

" Most commands for moving around will stop moving at the start and end of a line. You can change that with the 'whichwrap' option
set whichwrap+=b,s,<,>,[,]

" Tab related
set shiftwidth=4
set tabstop=4
set softtabstop=4
set expandtab               " Use spaces instead of tabs
                        
set list
set listchars=tab:\|\ ,     " display tab as '|'

" Indent related, see indent.txt
" gN Place C++ scope declarations N characters from the indent of the
"    block they are in.  (default 'shiftwidth').  A scope declaration
"    can be "public:", "protected:" or "private:".
" :N Place case labels N characters from the indent of the switch()
" N-s namespace 
" (N    When in unclosed parentheses, indent N characters from the line with the unclosed parentheses.
set cinoptions=g0,:0,N-s,(0

set autoindent      " always set autoindenting on
set smartindent

set mps+=<:>        " also apply matching to < and >
set hid             " allow to change buffer without saving 
set shortmess=atI   " shortens messages to avoid 'press a key' prompt 
set lazyredraw      " do not redraw while executing macros (much faster)

" Set Number format to null(default is octal) , when press CTRL-A on number
" like 007, it would not become 010
set nf=

" In Visual Block Mode, cursor can be positioned where there is no actual character
set ve=block

set ignorecase  " Set search/replace pattern to ignore case 
set smartcase   " Set smartcase mode on, If there is upper case character in the search patern, the 'ignorecase' option will be override.
set showcmd     " display incomplete commands
set incsearch   " do incremental searching
set hlsearch    " highlight search
set magic       " Enable magic matching
set showmatch   " show matching paren
set wildmenu    " enables a menu at the bottom of the vim/gvim window.
"set mouse=a    " Enable mouse usage (all modes) in terminals

" showmarks setting
let showmarks_enable = 0            " disable showmarks when vim startup
let showmarks_include = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
let showmarks_ignore_type = "hqm"   " help, Quickfix, non-modifiable

" NERDTree options
" Auto change the root directory
let NERDTreeChDirMode=2
let g:NERDTreeWinSize = 20

" Tagbar options
let g:tagbar_width = 25

let g:DoxygenToolkit_blockHeader="--------------------------------------------------------------------------"
let g:DoxygenToolkit_blockFooter="--------------------------------------------------------------------------"
let g:DoxygenToolkit_authorName="youdao5657@163.com" 
let g:DoxygenToolkit_versionString="0.1.00"
let g:DoxygenToolkit_briefTag_funcName="yes"
autocmd BufNewFile *.{h,hpp,c,cpp} DoxAuthor 

" Switching between buffers. 
nnoremap <C-h> <C-W>h
nnoremap <C-j> <C-W>j
nnoremap <C-k> <C-W>k
nnoremap <C-l> <C-W>l
inoremap <C-h> <Esc><C-W>h
inoremap <C-j> <Esc><C-W>j
inoremap <C-k> <Esc><C-W>k
inoremap <C-l> <Esc><C-W>l

" Set Up and Down non-linewise
noremap <Up> gk
noremap <Down> gj

" use Meta key(Windows:Alt) to move cursor in insert mode. 
" Note: if system install "Lingoes Translator", 
"   you will need change/disabled hot key. 
noremap! <M-j> <Down>
noremap! <M-k> <Up>
noremap! <M-h> <left>
noremap! <M-l> <Right>

" allow multiple indentation/deindentation in visual mode
vnoremap < <gv
vnoremap > >gv

" open ctags entries in a new tab
nnoremap <silent><Leader><C-]> <C-w><C-]><C-w>T

set pastetoggle=<F2>

" grep.vim
let g:Grep_Skip_Dirs = 'RCS CVS SCCS .git .svn'
let g:Grep_Skip_Files = '*.out *.bak *~ *.swp *.log *tags *.o *.a *.so'
nnoremap <silent> <F3> :Grep<CR>
nnoremap <silent> <F4> :Rgrep<CR>

" autopreview
let g:AutoPreview_enabled = 0
let g:EchoFuncKeyNext='<C-n>' 
let g:EchoFuncKeyPrev='<C-p>'
nnoremap <F6> :AutoPreviewToggle<CR>
inoremap <F6> <ESC>:AutoPreviewToggle<CR> 

" --lookupfile--
"  script to generate filenametags
"  #!/bin/sh
"  # generate tag file for lookupfile plugin, use absolute path
"  echo -e "!_TAG_FILE_SORTED\t2\t/2=foldcase/" > filenametags
"  find `pwd` -not -regex '.*\.\(png\|gif\)' -type f -printf "%f\t%p\t1\n" | \
"      sort -f >> filenametags 
"      
let g:LookupFile_MinPatLength = 2
let g:LookupFile_PreserveLastPattern = 0        "Don't save last pattern
"let g:LookupFile_PreservePatternHistory = 1    "Save history
let g:LookupFile_AlwaysAcceptFirst = 1          "Enter to open 1st
let g:LookupFile_AllowNewFiles = 0              "Don't allow create file
if filereadable("./filenametags")               "Set name
let g:LookupFile_TagExpr ='"./filenametags"'
endif

"ctrlp
let g:ctrlp_user_command = 'find %s -type f'

set tags=tags;

" -- cscope --
let g:autocscope_menus=0
if has("cscope") 
    set csprg=/usr/bin/cscope
    set csto=0
    set cst
    set nocsverb
    " add any database in current directory
    if filereadable("cscope.out")
        cs add cscope.out
    " else add database pointed to by enviroment
    elseif $CSCOPE_DB != ""
        cs add $CSCOPE_DB
    endif
    set csverb
    " Use both cscope and ctag
    set cscopetag
    " Show msg when cscope db added
    set cscopeverbose
    " Use cscope for definition search first
    set cscopetagorder=0
endif

nmap <C-_>s :cs find s <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>g :cs find g <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>c :cs find c <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>t :cs find t <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>e :cs find e <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>f :cs find f <C-R>=expand("<cfile>")<CR><CR>
nmap <C-_>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
nmap <C-_>d :cs find d <C-R>=expand("<cword>")<CR><CR>

" fix ctrl+] incorrect when cscope togethoer with tag 
nmap <C-]> :tj <C-R>=expand("<cword>")<CR><CR>

"Fast remove highlight search
nmap <silent> <leader><cr> :noh<cr>

" Underlined long lines
au BufRead,BufNewFile *.asm,*.c,*.cpp,*.java,*.cs,*.sh,*.lua,*.pl,*.pm,*.py,*.rb,*.hs,*.vim 2match Underlined /.\%81v/

" Highlight long lines
"au BufWinEnter * let w:m1=matchadd('Search', '\%<88v.\%>81v', -1)
"au BufWinEnter * let w:m2=matchadd('ErrorMsg', '\%>80v.\+', -1)

"highlight .txt, required txt.vim
au BufRead,BufNewFile * setfiletype txt

"au BufWritePost       .vimrc              source %

" Restore the last quit position when open file. 
 autocmd BufReadPost * 
    \ if line("'\"") > 0 && line("'\"") <= line("$") | 
     \     exe "normal g'\"" | 
     \ endif

function! AutoUpdateTheLastUpdateInfo()
    let s:original_pos = getpos(".")
    let s:regexp = "^\\s*\\([#\\\"\\*]\\|\\/\\/\\)\\s\\?[lL]ast \\([uU]pdate\\|[cC]hange\\):"
    let s:lu = search(s:regexp)
    if s:lu != 0
        let s:update_str = matchstr(getline(s:lu), s:regexp)
        call setline(s:lu, s:update_str . strftime("%Y-%m-%d %H:%M:%S", localtime()))
        call setpos(".", s:original_pos)
    endif
endfunction
autocmd BufWritePost *.{h,hpp,c,cpp} call AutoUpdateTheLastUpdateInfo()
autocmd BufNewFile *.{h,hpp,c,cpp} exec 'call append(0, "\/\/ Last Update:" . strftime("%Y-%m-%d %H:%M:%S", localtime()))'

function! ToggleNERDTreeAndTagbar()
    let w:jumpbacktohere = 1

    " Detect which plugins are open
    if exists('t:NERDTreeBufName')
        let nerdtree_open = bufwinnr(t:NERDTreeBufName) != -1
    else
        let nerdtree_open = 0
    endif
    let tagbar_open = bufwinnr('__Tagbar__') != -1

    " Perform the appropriate action
    if nerdtree_open && tagbar_open
        NERDTreeClose
        TagbarClose
    elseif nerdtree_open
        TagbarOpen
    elseif tagbar_open
        NERDTree
    else
        NERDTree
        TagbarOpen
    endif

    " Jump back to the original window
    for window in range(1, winnr('$'))
        execute window . 'wincmd w'
        if exists('w:jumpbacktohere')
            unlet w:jumpbacktohere
            break
        endif
    endfor
endfunction

nmap <F8> :call ToggleNERDTreeAndTagbar()<CR>

function! DoxygenOneLineCommentTag()
    exe "normal A\t"
    let l:wRow = line(".")
    let l:wCol = col(".")
    while l:wCol < 36
        exe "normal A    "
        let l:wCol = col(".")
    endwhile
    exe "normal A/**<  */"
    exe "normal 2h"
endfunction
nmap <leader>c4 <Esc>:call DoxygenOneLineCommentTag()<CR>i

" Enter key will simply select the highlighted menu item, just as <C-Y> does
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
" 上下左右键的行为会显示其他信息
inoremap <expr> <Down> pumvisible() ? "\<C-n>" : "\<Down>"
inoremap <expr> <up> pumvisible() ? "\<C-p>" : "\<Up>"
inoremap <expr> <PageDown> pumvisible() ? "\<PageDown>\<C-p>\<C-n>" : "\<PageDown>"
inoremap <expr> <PageUp> pumvisible() ? "\<PageUp>\<C-p>\<C-n>" : "\<PageUp>"

autocmd InsertLeave * if pumvisible() == 0|pclose|endif   " autoclose preview window when leave insert mode
nnoremap <leader>jd :YcmCompleter GoToDefinitionElseDeclaration<CR>    "按,jd会跳转到定义

" 自动补全配置
set completeopt=longest,menu    "让Vim的补全菜单行为与一般IDE一致

let g:ycm_confirm_extra_conf=0  " Do not ask when starting vim
let g:ycm_cache_omnifunc=0 "ensure that the omnicompletion engine is requeried on every keypress
let g:ycm_seed_identifiers_with_syntax=1    " 语法关键字补全
let g:ycm_global_ycm_extra_conf = '~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py'
let g:ycm_complete_in_comments = 1          " 在注释中也能补全
let g:ycm_complete_in_strings = 1           " 在字符串中输入也能补全
let g:ycm_auto_trigger = 1                  " turn on YCM's identifier completer and the semantic triggers

" make YCM compatible with xtemplate
let g:ycm_key_list_select_completion = ['<c-n>', '<Down>']
let g:ycm_key_list_previous_completion = ['<c-p>', '<Up>']

let g:ycm_collect_identifiers_from_tags_files=1         " 开启YCM基于标签引擎
let g:ycm_min_num_of_chars_for_completion=2         " 从第2个键入字符就开始罗列匹配项
let g:ycm_cache_omnifunc=0     " 禁止缓存匹配项,每次都重新生成匹配项

let g:syntastic_error_symbol = 'x'
let g:syntastic_warning_symbol = '⚠'

" NERDCommenter插件设置
map <C-F11> <leader>cc               "单行注释
map <C-F12> <leader>ca               "多行代码注释
map <F11>   <leader>cu               "取消注释

" whether to show balloons  press <leader>l to toogle
" let g:syntastic_enable_balloons = 1
" let g:syntastic_always_populate_loc_list = 1
" syntastic
" let g:syntastic_error_symbol = 'x'
" let g:syntastic_warning_symbol = '⚠'
" let g:syntastic_check_on_open = 1
" let g:syntastic_cpp_include_dirs = ['/usr/include/']
" let g:syntastic_cpp_remove_include_errors = 1
" let g:syntastic_cpp_check_header = 1
" let g:syntastic_cpp_compiler = 'clang++'
" let g:syntastic_cpp_compiler_option = '-std=c++11 -stdlib=libstdc++'


让你们看看我的效果图:




评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值