macOS配置vim

本教程適用于剛剛使用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文件忍抽,可以看到下面的效果啦

在這里插入圖片描述
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末八孝,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子鸠项,更是在濱河造成了極大的恐慌干跛,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件祟绊,死亡現(xiàn)場離奇詭異楼入,居然都是意外死亡,警方通過查閱死者的電腦和手機牧抽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進店門浅辙,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人阎姥,你說我怎么就攤上這事记舆。” “怎么了呼巴?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵泽腮,是天一觀的道長。 經(jīng)常有香客問我衣赶,道長诊赊,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任府瞄,我火速辦了婚禮碧磅,結果婚禮上,老公的妹妹穿的比我還像新娘遵馆。我一直安慰自己鲸郊,他們只是感情好,可當我...
    茶點故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布货邓。 她就那樣靜靜地躺著秆撮,像睡著了一般。 火紅的嫁衣襯著肌膚如雪换况。 梳的紋絲不亂的頭發(fā)上职辨,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天盗蟆,我揣著相機與錄音,去河邊找鬼舒裤。 笑死喳资,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的腾供。 我是一名探鬼主播仆邓,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼台腥!你這毒婦竟也來了宏赘?” 一聲冷哼從身側響起绒北,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤黎侈,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后闷游,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體峻汉,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年脐往,在試婚紗的時候發(fā)現(xiàn)自己被綠了休吠。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,059評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡业簿,死狀恐怖瘤礁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情梅尤,我是刑警寧澤柜思,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站巷燥,受9級特大地震影響赡盘,放射性物質發(fā)生泄漏。R本人自食惡果不足惜缰揪,卻給世界環(huán)境...
    茶點故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一陨享、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧钝腺,春花似錦抛姑、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至僵驰,卻和暖如春喷斋,著一層夾襖步出監(jiān)牢的瞬間唁毒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工星爪, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留浆西,地道東北人。 一個月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓顽腾,卻偏偏與公主長得像近零,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子抄肖,可洞房花燭夜當晚...
    茶點故事閱讀 42,792評論 2 345

推薦閱讀更多精彩內(nèi)容