在Ubuntu14.04中配置自己的GVIM

来源:互联网 发布:linux shell 编辑:程序博客网 时间:2024/06/05 09:51

注:保证你的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_buildcd ycm_buildcmake -G "Unix Makefiles" . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cppcmake -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/cppmake ycm_corecp /usr/clang_3_6/lib/libclang.so ~/.vim/bundle/YouCompleteMe/python/libclang.so #这一步是为了使用新的libclang.somake 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 relatedset fileencodings=utf-8,gb2312,gbk,gb18030set termencoding=utf-8" 设置字体if has("gui_running") set guifont=monaco\ 10endif"""""""""""""""""""""""""""""""""""""""""""""""""""""""" 键盘命令"""""""""""""""""""""""""""""""""""""""""""""""""""""""nmap <leader>w :w!<cr>nmap <leader>f :find<cr>" 映射全选+复制 ctrl+amap <C-A> ggVGYmap! <C-A> <Esc>ggVGYmap <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'        :!./%    endifendfunc"C,C++的调试map <F10> :call Rungdb()<CR>func! Rungdb()    exec "w"    exec "!g++ % -g -o %<"    exec "!gdb ./%<"endfunc"""""""""""""""""""""""""""""""""""""""""""""""""""""""""实用设置""""""""""""""""""""""""""""""""""""""""""""""""""""""""make 运行:set makeprg=g++\ -Wall\ \ %"自动保存set autowriteset ruler               " 打开状态栏标尺set cursorline          " 突出显示当前行"""""""""""""""""""""""""""""""""""""""""""""""""""""""" vundle begin"""""""""""""""""""""""""""""""""""""""""""""""""""""""filetype off                " required!set rtp+=~/.vim/bundle/vundle/call vundle#rc()" let Vundle manage VundleBundle 'gmarik/vundle'" vim-scripts repos"  Improved C++ STL syntax highlightingBundle 'STL-improved'" Displays tags in a window, ordered by class etc, i used it instead of taglistBundle 'majutsushi/tagbar'Bundle 'wesleyche/SrcExpl'" recommend fetch it from https://github.com/tczengming/autoload_cscope.vim.git which support c and cppBundle '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 VimBundle 'xptemplate'Bundle 'DoxygenToolkit.vim'" C/C++ header files should be guarded against multiple inclusions using preprocessor directivesBundle 'tczengming/headerGatesAdd.vim'Bundle 'genutils'Bundle 'lookupfile'" Fuzzy file, buffer, mru, tag, ... finder with regexp support.Bundle 'kien/ctrlp.vim'" Fast file navigationBundle 'wincent/Command-T'" Preview the definition of variables or functions in a preview windowBundle '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'" syntasticBundle 'scrooloose/syntastic'" non github repos" ...filetype plugin indent on   " required! """""""""""""""""""""""""""""""""""""""""""""""""""""""" vundle end"""""""""""""""""""""""""""""""""""""""""""""""""""""""" solarized themeset t_Co=256                " Explicitly tell vim that the terminal supports 256 colors, need before setting the colorschemelet g:solarized_termcolors=256colorscheme solarizedset background=darkhi Normal  ctermfg=252 ctermbg=none     " Transparent background" Enable syntax highlightingsyntax onset sm                    " 显示括号配对set numberset autochdirset nobackup              " 设置不生成备份文件" Set to auto read when a file is changed from the outsideset autoread"set backupdir=~/.vim/backup"set directory=~/.vim/backup" set directory=.,$TEMPset 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 modeset 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' optionset whichwrap+=b,s,<,>,[,]" Tab relatedset shiftwidth=4set tabstop=4set softtabstop=4set expandtab               " Use spaces instead of tabs                        set listset 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,(0set autoindent      " always set autoindenting onset smartindentset 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 010set nf=" In Visual Block Mode, cursor can be positioned where there is no actual characterset ve=blockset 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 commandsset incsearch   " do incremental searchingset hlsearch    " highlight searchset magic       " Enable magic matchingset showmatch   " show matching parenset wildmenu    " enables a menu at the bottom of the vim/gvim window."set mouse=a    " Enable mouse usage (all modes) in terminals" showmarks settinglet showmarks_enable = 0            " disable showmarks when vim startuplet showmarks_include = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"let showmarks_ignore_type = "hqm"   " help, Quickfix, non-modifiable" NERDTree options" Auto change the root directorylet NERDTreeChDirMode=2let g:NERDTreeWinSize = 20" Tagbar optionslet g:tagbar_width = 25let 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>hnnoremap <C-j> <C-W>jnnoremap <C-k> <C-W>knnoremap <C-l> <C-W>linoremap <C-h> <Esc><C-W>hinoremap <C-j> <Esc><C-W>jinoremap <C-k> <Esc><C-W>kinoremap <C-l> <Esc><C-W>l" Set Up and Down non-linewisenoremap <Up> gknoremap <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 modevnoremap < <gvvnoremap > >gv" open ctags entries in a new tabnnoremap <silent><Leader><C-]> <C-w><C-]><C-w>Tset pastetoggle=<F2>" grep.vimlet 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>" autopreviewlet g:AutoPreview_enabled = 0let 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 = 2let g:LookupFile_PreserveLastPattern = 0        "Don't save last pattern"let g:LookupFile_PreservePatternHistory = 1    "Save historylet g:LookupFile_AlwaysAcceptFirst = 1          "Enter to open 1stlet g:LookupFile_AllowNewFiles = 0              "Don't allow create fileif filereadable("./filenametags")               "Set namelet g:LookupFile_TagExpr ='"./filenametags"'endif"ctrlplet g:ctrlp_user_command = 'find %s -type f'set tags=tags;" -- cscope --let g:autocscope_menus=0if 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=0endifnmap <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 searchnmap <silent> <leader><cr> :noh<cr>" Underlined long linesau 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.vimau 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'\"" |      \ endiffunction! 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)    endifendfunctionautocmd 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    endforendfunctionnmap <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"endfunctionnmap <leader>c4 <Esc>:call DoxygenOneLineCommentTag()<CR>i" Enter key will simply select the highlighted menu item, just as <C-Y> doesinoremap <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 modennoremap <leader>jd :YcmCompleter GoToDefinitionElseDeclaration<CR>    "按,jd会跳转到定义" 自动补全配置set completeopt=longest,menu    "让Vim的补全菜单行为与一般IDE一致let g:ycm_confirm_extra_conf=0  " Do not ask when starting vimlet g:ycm_cache_omnifunc=0 "ensure that the omnicompletion engine is requeried on every keypresslet 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 xtemplatelet 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++'


让你们看看我的效果图:




0 0