VIM使用(三)

Vim自動補全神器:YouCompleteMe

 

Ubuntu下,先經過Bundle安裝插件:javascript

Bundle 'Valloric/YouCompleteMe'
Bundle 'scrooloose/syntastic'php

Bundle 'Valloric/ListToggle'html

Bundle 'SirVer/ultisnips'java

 

 

YouCompleteMe的特別之處

基於語義補全

總所周知,Vim是一款文本編輯器。也就是說,其最基礎的工做就是編輯文本,無論該文本的內容是什麼。在Vim被程序員所使用後,其慢慢的被肩負了與IDE同樣的工做,文本自動補全(ie.acp,omnicppcompleter),代碼檢查(Syntastic)等等工做。python

針對文本自動補全這個功能來講,主要有兩種實現方式。c++

  • 基於文本

咱們經常使用的omnicppcompleter,acp,vim自帶的c-x, c-n的實現方式就是基於文本。更通俗的說法,其實就是一個字:git

其經過文本進行一些正則表達式的匹配,再根據生成的tags(利用ctags生成)來實現自動補全的效果。程序員

  • 基於語義

顧名思義,其是經過分析源文件,通過語法分析之後進行補全。因爲對源文件進行分析,基於語義的補全能夠作到很精確。可是這顯然是vim所不可能支持的。並且通過這麼多年發展,因爲語法分析有很高的難度,也一直沒有合適的工具出現。直到,由apple支持的clang/llvm橫空出世。YouCompleteMe也正是在clang/llvm的基礎上進行構建的。github

整合實現了多種插件

  • clang_complete
  • AutoComplPop
  • Supertab
  • neocomplcache
  • Syntastic(相似功能,僅僅針對c/c++/obj-c代碼)

支持語言

  • c
  • c++
  • obj-c
  • c#
  • python

對於其餘的語言,會調用vim設置的omnifunc來匹配,所以一樣支持php,ruby等語言。正則表達式

已知的有 * javascript —-tern_for_vim * ruby/java —-eclim

 

使用感覺

  • 和IDE同樣,自動補全,
  • 根據include的文件進行補全
  • 不用再蹩腳的生成tags
  • 補全很是精準,並且速度很快,不會有延遲(之前在大項目上,acp用起來實在是很卡)
  • 支持相似tags的跳轉,跳到定義處以及使用處
  • 出錯提示很智能,而且用起來真的是如絲般柔滑,不用輸入:w進行強制檢測

編譯:

等待vundle將YouCompleteMe安裝完成

然後進行編譯安裝:

sudo apt-get install python-dev
cd ~/.vim/bundle/YouCompleteMe ./install --clang-completer

 

若是不須要c-family的補全,能夠去掉--clang-completer。若是須要c#的補全,請加上--omnisharp-completer。

正常來講,YCM會去下載clang的包,若是已經有,也能夠用系統--system-libclang。

就這樣,安裝結束。打開vim,若是沒有提示YCM未編譯,則說明安裝已經成功了。

配置

不一樣於不少vim插件,YCM首先須要編譯,另外還須要有配置。在vim啓動後,YCM會找尋當前路徑以及上層路徑的.ycm_extra_conf.py.在~/.vim/bundle/YouCompleteMe/cpp/ycm/.ycm_extra_conf.py中提供了默認的模板。也能夠參考個人(就在模板上改改而已)。不過這個解決了標準庫提示找不到的問題。

通常來講,我會在~目錄下放一個默認的模板,然後再根據不一樣的項目在當前目錄下再拷貝個.ycm_extra_conf.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',
'/Library/Developer/CommandLineTools/usr/include',
'-isystem',
'/Library/Developer/CommandLineTools/usr/bin/../lib/c++/v1',
]
 
# 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
  }

YouCompleteMe提供的其餘功能

YCM除了提供了基本的補全功能,自動提示錯誤的功能外,還提供了相似tags的功能:

  • 跳轉到定義GoToDefinition
  • 跳轉到聲明GoToDeclaration
  • 以及二者的合體GoToDefinitionElseDeclaration

能夠在.vimrc中配置相應的快捷鍵。

1
2
3
nnoremap <leader>gl :YcmCompleter GoToDeclaration<CR>
nnoremap <leader>gf :YcmCompleter GoToDefinition<CR>
nnoremap <leader>gg :YcmCompleter GoToDefinitionElseDeclaration<CR>

另外,YCM也提供了豐富的配置選項,一樣在.vimrc中配置。具體請參考

1
2
let g:ycm_error_symbol = '>>'
let g:ycm_warning_symbol = '>*'

同時,YCM能夠打開location-list來顯示警告和錯誤的信息:YcmDiags。我的關於ycm的配置以下:

1
2
3
4
5
6
7
" for ycm
let g:ycm_error_symbol = '>>'
let g:ycm_warning_symbol = '>*'
nnoremap <leader>gl :YcmCompleter GoToDeclaration<CR>
nnoremap <leader>gf :YcmCompleter GoToDefinition<CR>
nnoremap <leader>gg :YcmCompleter GoToDefinitionElseDeclaration<CR>
nmap <F4> :YcmDiags<CR>

YCM提供的跳躍功能採用了vim的jumplist,往前跳和日後跳的快捷鍵爲Ctrl+O以及Ctrl+I。

 

UltiSnips簡介:

詳細參考:http://mednoter.com/UltiSnips.html

UltiSnips 只是個引擎,須要搭配預設的代碼塊才能運轉起來,如下是我建立的幾個經常使用代碼塊。

代碼塊集合 honza/vim-snippets 經過Bundle安裝:

Bundle 'honza/vim-snippets'

若是想本身建立代碼塊,也參考:http://mednoter.com/UltiSnips.html的內容.

 

 這個插件很簡單,給你看個人設置好了:

NeoBundle 'SirVer/ultisnips'
let g:UltiSnipsSnippetDirectories=['UltiSnips']
let g:UltiSnipsSnippetsDir = '~/.vim/UltiSnips'
let g:UltiSnipsExpandTrigger = '<Tab>'
let g:UltiSnipsListSnippets = '<C-Tab>'
let g:UltiSnipsJumpForwardTrigger = '<Tab>'
let g:UltiSnipsJumpBackwardTrigger = '<S-Tab>'

 

哦,對了,我想起來一件事情。g:UltiSnipsSnippetDirectories 選項的值必須是文件夾名稱(能夠是多個),而且這個(些)文件夾必須存在於 runtimepath 中的某一項之下。好比說 ~/.vim 就是 runtimepath 中的一項。默認的文件夾 UltiSnips 會自動建立,若是你換了,那你必須保證這個文件夾是存在的。我看你換成了 snippets,若是你事先安裝過 SnipMate,那麼 snippets 纔會存在,不然你得自行建立。g:UltiSnipsSnippetDirectories 選項的做用是指定 UltiSnips 的搜索路徑,你找不到 snippets 的緣由大概就是這樣。

解釋爲何錯了真的很累,換個角度告訴你,若是你作對了是什麼樣子的:

    1. let g:UltiSnipsSnippetsDir = '~/.vim/UltiSnips' 這個設置會確保 snippets 都在指定的文件夾內(你本身編輯的也會保存在這裏,若是你用了第三方的而且還要進一步編輯,你得確保都複製到了這裏)
      請輸入圖片描述

    2. let g:UltiSnipsSnippetDirectories = ['UltiSnips'] 這個設置會告訴 UltiSnips 去哪兒找 snippets,能夠是多個地方,因此若是你用第三方的 snippets,和上一個設置不在一塊兒的話,你得把它們的路徑放這裏。要注意的是,這個數組裏的每一項都必須在 runtimepath 其中的一項之下,因此不肯定的話,先看看 runtimepath 的值。
      請輸入圖片描述

    3. 若上述兩點都作對了,那麼在任意類型文件打開的前提下輸入 :UltiSnipsEdit 都會打開對應類型的 snippets,能不能用,哪些能用,一看便知。

 

 注:代碼片斷的擴展引用

  •       好比在 cpp.snippets 文件的第一行增長一句 extends c ,在打開一個cpp 文件時,會首先查找搜索路徑內的全部 c.snippets 文件,因此能夠很容易複用已有的代碼片斷文件。

相關的配置內容:

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'
"
"    YouCompleteMe 設置
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

let g:ycm_global_ycm_extra_conf = '~/.vim/.ycm_extra_conf.py'
let g:ycm_confirm_extra_conf = 0

let g:ycm_collect_identifiers_from_tags_files = 1
"settags+=./.tags

nnoremap <leader>gl :YcmCompleter GoToDeclaration<CR>
nnoremap <leader>gf :YcmCompleter GoToDefinition<CR>
nnoremap <leader>gg :YcmCompleter GoToDefinitionElseDeclaration<CR>

let g:ycm_key_list_select_completion = [ ' <c-n> ', ' <Down> '] 
let g:ycm_key_list_previous_completion = ['<c-p>', '<Up>']


"設置error和warning的提示符,若是沒有設置,ycm會以syntastic的  
" g:syntastic_warning_symbol 和 g:syntastic_error_symbol 這兩個爲準  
let g:ycm_error_symbol='>>'  
let g:ycm_warning_symbol='>*' 


let g:ycm_complete_in_comments = 1  "在註釋輸入中也能補全
let g:ycm_complete_in_strings = 1   "在字符串輸入中也能補全

"每次從新生成匹配項,禁止緩存匹配項  
let g:ycm_cache_omnifunc=0  

"不查詢ultisnips提供的代碼模板補全,若是須要,設置成1便可  
let g:ycm_use_ultisnips_completer=1  


let g:ycm_seed_identifiers_with_syntax=1   "語言關鍵字補全, 不過python關鍵字都很短,因此,須要的本身打開

" 直接觸發自動補全 " 修改對C函數的補全快捷鍵,默認是CTRL + space,修改成ALT + ;  
let g:ycm_key_invoke_completion = '<M-c>'

nnoremap <F5> :YcmForceCompileAndDiagnostics<CR>

set completeopt=menuone,longest
set pumheight=15

" 黑名單,不啓用
let g:ycm_filetype_blacklist = {
      \ 'tagbar' : 1,
      \ 'gitcommit' : 1,
      \}
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'
"
"    UltiSnips 設置
" ultisnips內置了不少代碼片斷,而且支持自定義。
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""


" Snippets are separated from the engine. Add this if you want them:
"Plugin 'honza/vim-snippets'

" Trigger configuration. Do not use <tab> if you use https://github.com/Valloric/YouCompleteMe.
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"

" If you want :UltiSnipsEdit to split your window.
"let g:UltiSnipsEditSplit="vertical"


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'
"
"    syntastic 設置  用於語法檢查
" syntastic 與 YouComleteMe 結合對語法 進行檢查,並將警告和錯誤信息顯示在行號那一欄的左側。添加下面的命令安裝 syntastic:
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:syntastic_error_symbol=''
let g:syntastic_warning_symbol=''
let g:syntastic_enable_highlighting = 1
let g:syntastic_stl_format = '[%E{Err: %fe #%e}%B{, }%W{Warn: %fw #%w}]'
相關文章
相關標籤/搜索