本教程適用于剛剛使用mac的小白,大神可以路過~
MacOS的vim配置和Linux下面相似。在我電腦配置效果如下
1.前言
配置之前首先注意下兩個文件目錄的作用岖常,如下
/usr/bin
/usr/local/bin
這兩個目錄中歧寺,/usr/bin是用來存儲系統(tǒng)應用程序翅雏,受到分發(fā)管理工具的控制纵散,而/usr/local/bin存儲用戶自己安裝的程序梳码,這部分不會受自己控制隐圾,不會因為系統(tǒng)升級導致的覆蓋等改變。
2.安裝vim
如果沒有安裝brew边翁,首先需要安裝brew,參考這里
然后執(zhí)行下面的安裝命令
brew install vim
brew install macvim
然后執(zhí)行命令
which vim
如果出現(xiàn)下面的情況硕盹,那就說明安裝成功符匾。如果看到如圖/usr/local/bin/vim ,那么很好瘩例,系統(tǒng)已經(jīng)啟用了我們所安裝的vim啊胶,如果不是,而是系統(tǒng)安裝的/usr/bin, 那么請到/ect/paths 中修改環(huán)境變量順序垛贤。使用命令
vim /etc/paths
將順序調(diào)整為下圖焰坪,保證/usr/local/bin/vim在/usr/bin/vim的前面。
3.配置.vimrc文件
vim 的配置文件在根目錄的 .vimrc 文件中聘惦,如果沒有某饰,自己創(chuàng)建一個。執(zhí)行命令
cp /usr/share/vim/vimrc ~/.vimrc
這里配置一個常用的插件管理器vundle
git clone https://github.com/gmarik/vundle.git ~/.vim/bundle/Vundle.vim
編輯.vimrc文件善绎,配置文件如下
"顯示行號
set nu
"啟動時隱去援助提示
set shortmess=atI
"語法高亮
syntax on
"不需要備份
set nobackup
set nocompatible
"沒有保存或文件只讀時彈出確認
set confirm
"鼠標可用
set mouse=a
"tab縮進
set tabstop=4
set shiftwidth=4
set expandtab
set smarttab
"文件自動檢測外部更改
set autoread
"c文件自動縮進
set cindent
"自動對齊
set autoindent
"智能縮進
set smartindent
"高亮查找匹配
set hlsearch
"顯示匹配
set showmatch
"顯示標尺黔漂,就是在右下角顯示光標位置
set ruler
"去除vi的一致性
set nocompatible
"設置鍵盤映射,通過空格設置折疊
nnoremap <space> @=((foldclosed(line('.')<0)?'zc':'zo'))<CR>
""""""""""""""""""""""""""""""""""""""""""""""
"不要閃爍
set novisualbell
"啟動顯示狀態(tài)行
set laststatus=2
"淺色顯示當前行
autocmd InsertLeave * se nocul
"用淺色高亮當前行
autocmd InsertEnter * se cul
"顯示輸入的命令
set showcmd
"被分割窗口之間顯示空白
set fillchars=vert:/
set fillchars=stl:/
set fillchars=stlnc:/
" vundle 環(huán)境設置
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
"vundle管理的插件列表必須位于 vundle#begin() 和 vundle#end() 之間
call vundle#begin()
Plugin 'VundleVim/Vundle.vim'
Plugin 'altercation/vim-colors-solarized'
Plugin 'tomasr/molokai'
Plugin 'vim-scripts/phd'
Plugin 'Lokaltog/vim-powerline'
Plugin 'octol/vim-cpp-enhanced-highlight'
Plugin 'Raimondi/delimitMate'
" 插件列表結束
call vundle#end()
filetype plugin indent on
" 配色方案
set background=dark
colorscheme torte
"colorscheme molokai
"colorscheme phd
" 禁止顯示菜單和工具條
set guioptions-=m
set guioptions-=T
" 總是顯示狀態(tài)欄
set laststatus=2
" 禁止折行
set nowrap
" 設置狀態(tài)欄主題風格
let g:Powerline_colorscheme='solarized256'
syntax keyword cppSTLtype initializer_list
" 基于縮進或語法進行代碼折疊
"set foldmethod=indent
set foldmethod=syntax
" 啟動 vim 時關閉折疊代碼
set nofoldenable
"允許用退格鍵刪除字符
set backspace=indent,eol,start
"編碼設置
set encoding=utf-8
"共享剪切板
set clipboard=unnamed
" Don't write backup file if vim is being called by "crontab -e"
au BufWrite /private/tmp/crontab.* set nowritebackup nobackup
" Don't write backup file if vim is being called by "chpass"
au BufWrite /private/etc/pw.* set nowritebackup nobackup
如配置文件所示禀酱,Plugin '插件地址' 即為添加插件炬守,如:
Plugin 'dyng/ctrlsf.vim'
安裝插件前,先找到其在 github.com 的地址剂跟,再將配置信息其加入 .vimrc 中的call vundle#begin() 和 call vundle#end() 之間减途,最后進入 vim 執(zhí)行:
:PluginInstall
便安裝完成插件。
如需刪除插件曹洽,只需將 Plugin '插件地址' 刪除或者注釋掉鳍置,再進入 vim 執(zhí)行:
:PluginClean
便將插件刪除。
如需升級插件送淆,進入 vim 執(zhí)行:
:PluginUpdate
便完成升級墓捻。
4.配置自動補全
習慣了IDE,突然轉到vim坊夫,總是有點不習慣砖第,比如沒有語法提示就很麻煩,在vim里 肯定有神器环凿,那就是插件YouCompeleteMe了梧兼。在配置文件中配置這個插件
Bundle 'Valloric/YouCompleteMe'
然后執(zhí)行第3步的安裝插件的命令。
如果此時沒有安裝Cmake智听,先安裝
brew install CMake
然后執(zhí)行編譯(帶C的)羽杰,等待幾分鐘
cd ~/.vim/bundle/YouCompleteMe
./install.sh --clang-completer
接下來渡紫,才是最重要的!?既惕澎! 網(wǎng)上的一堆教程我覺得都是有問題的,看了很多的博客之后終于將語法提示解決了颜骤。這里需要感謝這篇文章唧喉。
正確的姿態(tài)如下:
首先建立在~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm中建立 .ycm_extra_conf.py文件,內(nèi)容如下
# 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/>
from distutils.sysconfig import get_python_inc
import platform
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',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-DNDEBUG',
# You 100% do NOT need -DUSE_CLANG_COMPLETER and/or -DYCM_EXPORT in your flags;
# only the YCM source code needs it.
'-DUSE_CLANG_COMPLETER',
'-DYCM_EXPORT=',
# THIS IS IMPORTANT! Without the '-x' 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 the '-x' flag.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x',
'c++',
'-isystem',
'../pybind11',
'-isystem',
'../BoostParts',
'-isystem',
get_python_inc(),
'-isystem',
'../llvm/include',
'-isystem',
'../llvm/tools/clang/include',
'-I',
'.',
'-I',
'./ClangCompleter',
'-isystem',
'./tests/gmock/gtest',
'-isystem',
'./tests/gmock/gtest/include',
'-isystem',
'./tests/gmock',
'-isystem',
'./tests/gmock/include',
'-isystem',
'./benchmarks/benchmark/include',
]
# Clang automatically sets the '-std=' flag to 'c++14' for MSVC 2015 or later,
# which is required for compiling the standard library, and to 'c++11' for older
# versions.
if platform.system() != 'Windows':
flags.append( '-std=c++11' )
# 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
#
# You can get CMake to generate this file for you by adding:
# set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )
# to your CMakeLists.txt file.
#
# 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 IsHeaderFile( filename ):
extension = os.path.splitext( filename )[ 1 ]
return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
def FindCorrespondingSourceFile( filename ):
if IsHeaderFile( filename ):
basename = os.path.splitext( filename )[ 0 ]
for extension in SOURCE_EXTENSIONS:
replacement_file = basename + extension
if os.path.exists( replacement_file ):
return replacement_file
return filename
def FlagsForFile( filename, **kwargs ):
# If the file is a header, try to find the corresponding source file and
# retrieve its flags from the compilation database if using one. This is
# necessary since compilation databases don't have entries for header files.
# In addition, use this source file as the translation unit. This makes it
# possible to jump from a declaration in the header file to its definition in
# the corresponding source file.
filename = FindCorrespondingSourceFile( filename )
if not database:
return {
'flags': flags,
'include_paths_relative_to_dir': DirectoryOfThisScript(),
'override_filename': filename
}
compilation_info = database.GetCompilationInfoForFile( filename )
if not compilation_info.compiler_flags_:
return None
# Bear in mind that compilation_info.compiler_flags_ does NOT return a
# python list, but a "list-like" StringVec object.
final_flags = list( compilation_info.compiler_flags_ )
# 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
return {
'flags': final_flags,
'include_paths_relative_to_dir': compilation_info.compiler_working_dir_,
'override_filename': filename
}
然后回到.vimrc中加上下面的配置
let g:ycm_global_ycm_extra_conf = '~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py'
let g:ycm_add_preview_to_completeopt = 0
let g:ycm_show_diagnostics_ui = 0
let g:ycm_server_log_level = 'info'
let g:ycm_min_num_identifier_candidate_chars = 2
let g:ycm_collect_identifiers_from_comments_and_strings = 1
let g:ycm_complete_in_strings=1
let g:ycm_key_invoke_completion = '<c-z>'
set completeopt=menu,menuone
noremap <c-z> <NOP>
" 換行的時候可以自動跳到下一行
imap {<CR> {<CR>}<ESC>O
let g:ycm_semantic_triggers = {
\ 'c,cpp,python,java,go,erlang,perl': ['re!\w{2}'],
\ 'cs,lua,javascript': ['re!\w{2}'],
\ }
let g:ycm_filetype_whitelist = {
\ "c":1,
\ "cpp":1,
\ "objc":1,
\ "sh":1,
\ "zsh":1,
\ "zimbu":1,
\ }
我們隨意打開一個cpp文件忍抽,可以看到下面的效果啦