VIM 使用指南
![]()
本文整合了 VIM 的美化配置、插件管理以及各主流 Linux 发行版的默认配置参考。
1. 美化配置
Section titled “1. 美化配置”以下是一份全面的 .vimrc 配置,涵盖外观增强、语法高亮、状态栏优化和导航改进。
-
备份现有配置:
Terminal window mv ~/.vimrc ~/.vimrc.bak -
将以下内容复制到
~/.vimrc文件:
" -- General Settings ----------------------------------------------------------set rulerfiletype offset backspace=2set nuset mouse=a
" -- Bootstrap -----------------------------------------------------------------set encoding=utf-8 " set vim encoding to UTF-8set nocompatible " use vim defaultsset history=1000 " boost historyset undolevels=1000 " boost undo levels
" -- Tmux Integration ----------------------------------------------------------if exists('$TMUX') set term=screen-256colorendif
if exists('$ITERM_PROFILE') if exists('$TMUX') let &t_SI = "\<Esc>[3 q" let &t_EI = "\<Esc>[0 q" else let &t_SI = "\<Esc>]50;CursorShape=1x7" let &t_EI = "\<Esc>]50;CursorShape=0x7" endifendif
" -- Backup and Swap -----------------------------------------------------------set backupset writebackupset swapfile
let s:vimdir=$HOME . "/.vim"let &backupdir=s:vimdir . "/backup"let &directory=s:vimdir . "/tmp"
if exists("*mkdir") if !isdirectory(s:vimdir) call mkdir(s:vimdir, "p") endif if !isdirectory(&backupdir) call mkdir(&backupdir, "p") endif if !isdirectory(&directory) call mkdir(&directory, "p") endifendif
set backupskip+=*.tmp
if has("persistent_undo") let &undodir=&backupdir set undofileendif
let &viminfo=&viminfo . ",n" . s:vimdir . "/.viminfo"
" -- Command Mode --------------------------------------------------------------set wildmenuset wildmode=longest:full,fullset wildignore+=.git,*.DS_Storeif exists ("&wildignorecase") set wildignorecaseendif
" -- Display -------------------------------------------------------------------set titleset lazyredrawset report=0set cursorline
if has("gui_running") set cursorcolumnendif
if exists("+showtabline") set showtabline=1endif
" -- Status Line ---------------------------------------------------------------if has("statusline") function! StatusLineUTF8() try let p = getpos('.') redir => utf8seq sil normal! g8 redir End call setpos('.', p) return substitute(matchstr(utf8seq, '\x\+ .*\x'), '\<\x\x', '0x\U&', 'g') catch return '?' endtry endfunction
function! StatusLineFileEncoding() return has("multi_byte") && strlen(&fenc) ? &fenc : '' endfunction
function! StatusLineUTF8Bomb() return has("multi_byte") && &fenc == 'utf-8' && &bomb?'+bomb' : '' endfunction
function! StatusLineCWD() let l:pwd = exists('$PWD') ? $PWD : getcwd() return substitute(fnamemodify(l:pwd, ':~'), '\(\~\?/[^/]*/\).*\(/.\{20\}\)', '\1...\2', '') endfunction
set laststatus=2 set statusline= set statusline+=%#Number# set statusline+=❐\ %02n set statusline+=\ \|\ set statusline+=%* set statusline+=%#Identifier# set statusline+=%f set statusline+=%* set statusline+=%#Special# set statusline+=%m set statusline+=%#Statement# set statusline+=%r set statusline+=%h set statusline+=%w set statusline+=%#Type# set statusline+=[%{&ff}] set statusline+=[ set statusline+=%{StatusLineFileEncoding()} set statusline+=%#Error# set statusline+=%{StatusLineUTF8Bomb()} set statusline+=%#Type# set statusline+=] set statusline+=%y set statusline+=\ \|\ set statusline+=%* set statusline+=%#Directory# set statusline+=%{StatusLineCWD()} set statusline+=\ set statusline+=%* set statusline+=%= set statusline+=%#Comment# set statusline+=%{v:register} set statusline+=\ set statusline+=%#Statement# set statusline+=[U+\%04B] set statusline+=[%{StatusLineUTF8()}] set statusline+=\ \|\ set statusline+=%#Comment# set statusline+=line\ %5l/%L\ set statusline+=●\ %02p%%,\ set statusline+=col\ %3vendif
set showcmdset cmdheight=1set shortmess=astT
if (&t_Co > 2 || has("gui_running")) && has("syntax") syntax onendif
match ErrorMsg '^\(<\|=\|>\)\{7\}\([^=].\+\)\?$'
if has("termguicolors") let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum" let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum" set termguicolorsendif
" -- Buffers -------------------------------------------------------------------set autoreadset fsync
" -- Navigation ----------------------------------------------------------------nnoremap <C-e> 2<C-e>nnoremap <C-y> 2<C-y>map <C-Up> <C-y>map <C-Down> <C-e>
set startofline
nnoremap j gjnnoremap <Down> gjnnoremap k gknnoremap <Up> gk
set scrolljump=1set scrolloff=4set sidescroll=1set sidescrolloff=4
" -- Editing -------------------------------------------------------------------set showmodeset nowrapset linebreak
if has("multi_byte") set showbreak=↪else set showbreak=>endif
set nojoinspacesset showmatchset matchtime=4set matchpairs+=<:>set virtualedit+=onemoreset smarttab
" -- Searching -----------------------------------------------------------------set wrapscanset incsearchif (&t_Co > 2 || has("gui_running")) set hlsearchendif
set ignorecaseset smartcase
" -- Spell Checking ------------------------------------------------------------set spelllang=enset nospell
" -- Snakemake Syntax Support --------------------------------------------------source $VIMRUNTIME/syntax/python.vimsyn keyword pythonStatement include workdir onsuccess onerrorsyn keyword pythonStatement ruleorder localrules configfilesyn keyword pythonStatement touch protected temp wrappersyn keyword pythonStatement input output params message threads resourcessyn keyword pythonStatement version run shell benchmark snakefile log scriptsyn keyword pythonStatement rule subworkflow nextgroup=pythonFunction skipwhitesyn keyword pythonBuiltin expand config temp protectedsyn match pythonFunction "\%(\%(rule\s\|subworkflow\s\)\s*\)\@<=\h*" containedsyn sync match pythonSync grouphere NONE "^\s*\%(rule\|subworkflow\)\s\+\h\w*\s*"let b:current_syntax = "snakemake"2. 插件管理(Vundle)
Section titled “2. 插件管理(Vundle)”使用 Vundle 管理 Vim 插件。
安装 Vundle
Section titled “安装 Vundle”mkdir -p ~/.vim/bundlegit clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim在 ~/.vimrc 中添加以下配置。所有 Plugin 命令必须放在 call vundle#begin() 和 call vundle#end() 之间:
set nocompatible " be iMproved, requiredfiletype off " required
" set the runtime path to include Vundle and initializeset rtp+=~/.vim/bundle/Vundle.vimcall vundle#begin()
" let Vundle manage Vundle, requiredPlugin 'VundleVim/Vundle.vim'
" Add your plugins herePlugin 'wakatime/vim-wakatime'Plugin 'editorconfig/editorconfig-vim'
call vundle#end() " requiredfiletype plugin indent on " required
" General settingsset rulerset nuset backspace=2set mouse=a启动 Vim 并运行安装命令:
vim +PluginInstall +qall或在 Vim 内部运行:
:PluginInstall3. 各发行版默认配置参考
Section titled “3. 各发行版默认配置参考”以下收集了主流 Linux 发行版的默认 .vimrc 配置,可用于参考或恢复默认行为。
Alpine Linux
Section titled “Alpine Linux”set nocompatible " Use Vim defaults (much better!)set bs=2 " Allow backspacing over everything in insert modeset ai " Always set auto-indenting onset history=50 " keep 50 lines of command historyset ruler " Show the cursor position all the time
" Don't use Ex mode, use Q for formattingmap Q gq
" When doing tab completion, give the following files lower priority.set suffixes+=.info,.aux,.log,.dvi,.bbl,.out,.o,.lo
set nomodelinesyntax onautocmd BufRead APKBUILD set filetype=shCentOS 7.6 / CentOS 8
Section titled “CentOS 7.6 / CentOS 8”if v:lang =~ "utf8$" || v:lang =~ "UTF-8$" set fileencodings=ucs-bom,utf-8,latin1endif
set nocompatible " Use Vim defaults (much better!)set bs=indent,eol,start " allow backspacing over everything in insert mode"set ai " always set autoindenting on"set backup " keep a backup fileset viminfo='20,\"50 " read/write a .viminfo file, don't store more " than 50 lines of registersset history=50 " keep 50 lines of command line historyset ruler " show the cursor position all the time
" Only do this part when compiled with support for autocommandsif has("autocmd") augroup redhat autocmd! " In text files, always limit the width of text to 78 characters " autocmd BufRead *.txt set tw=78 " When editing a file, always jump to the last cursor position autocmd BufReadPost * \ if line("'\"") > 0 && line ("'\"") <= line("$") | \ exe "normal! g'\"" | \ endif " don't write swapfile on most commonly used directories for NFS mounts or USB sticks autocmd BufNewFile,BufReadPre /media/*,/run/media/*,/mnt/* set directory=~/tmp,/var/tmp,/tmp " start with spec file template autocmd BufNewFile *.spec 0r /usr/share/vim/vimfiles/template.spec augroup ENDendif
if has("cscope") && filereadable("/usr/bin/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 $PWD/cscope.out " else add database pointed to by environment elseif $CSCOPE_DB != "" cs add $CSCOPE_DB endif set csverbendif
" Switch syntax highlighting on, when the terminal has colors" Also switch on highlighting the last used search pattern.if &t_Co > 2 || has("gui_running") syntax on set hlsearchendif
filetype plugin on
if &term=="xterm" set t_Co=8 set t_Sb=m set t_Sf=mendifFedora
Section titled “Fedora”" When started as "evim", evim.vim will already have done these settings.if v:progname =~? "evim" finishendif
" Use Vim settings, rather than Vi settings (much better!)." This must be first, because it changes other options as a side effect." Avoid side effects when it was already reset.if &compatible set nocompatibleendif
" When the +eval feature is missing, the set command above will be skipped." Use a trick to reset compatible only when the +eval feature is missing.silent! while 0 set nocompatiblesilent! endwhile
" Allow backspacing over everything in insert mode.set backspace=indent,eol,start
"set ai " always set autoindenting on"set backup " keep a backup fileset viminfo='20,\"50 " read/write a .viminfo file, don't store more " than 50 lines of registersset history=50 " keep 50 lines of command line historyset ruler " show the cursor position all the timeset showcmd " display incomplete commandsset wildmenu " display completion matches in a status line
set ttimeout " time out for key codesset ttimeoutlen=100 " wait up to 100ms after Esc for special key
" Show @@@ in the last line if it is truncated.set display=truncate
" Show a few lines of context around the cursor. Note that this makes the" text scroll if you mouse-click near the start or end of the window.set scrolloff=5
" Do incremental searching when it's possible to timeout.if has('reltime') set incsearchendif
" Do not recognize octal numbers for Ctrl-A and Ctrl-X, most users find it" confusing.set nrformats-=octal
" Only do this part when compiled with support for autocommandsif has("autocmd") augroup fedora autocmd! " In text files, always limit the width of text to 78 characters " autocmd BufRead *.txt set tw=78 " When editing a file, always jump to the last cursor position autocmd BufReadPost * \ if line("'\"") > 0 && line ("'\"") <= line("$") | \ exe "normal! g'\"" | \ endif " don't write swapfile on most commonly used directories for NFS mounts or USB sticks autocmd BufNewFile,BufReadPre /media/*,/run/media/*,/mnt/* set directory=~/tmp,/var/tmp,/tmp " start with spec file template " 1724126 - do not open new file with .spec suffix with spec file template " apparently there are other file types with .spec suffix, so disable the " template " autocmd BufNewFile *.spec 0r /usr/share/vim/vimfiles/template.spec augroup ENDendif
if has("cscope") && filereadable("/usr/bin/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 $PWD/cscope.out " else add database pointed to by environment elseif $CSCOPE_DB != "" cs add $CSCOPE_DB endif set csverbendif
" Switch syntax highlighting on, when the terminal has colors" Also switch on highlighting the last used search pattern.if &t_Co > 2 || has("gui_running") " Revert with ":syntax off". syntax on
" I like highlighting strings inside C comments. " Revert with ":unlet c_comment_strings". let c_comment_strings=1 set hlsearchendif
filetype plugin on
if &term=="xterm" set t_Co=8 set t_Sb=ESC[4%dm set t_Sf=ESC[3%dmendif
" Convenient command to see the difference between the current buffer and the" file it was loaded from, thus the changes you made." Only define it when not defined already." Revert with: ":delcommand DiffOrig".if !exists(":DiffOrig") command DiffOrig vert new | set bt=nofile | r ++edit # | 0d_ | diffthis \ | wincmd p | diffthisendif
if has('langmap') && exists('+langremap') " Prevent that the langmap option applies to characters that result from a " mapping. If set (default), this may break plugins (but it's backward " compatible). set nolangremapendif
" Don't wake up system with blinking cursor:" http://www.linuxpowertop.org/known.phplet &guicursor = &guicursor . ",a:blinkon0"OpenSUSE
Section titled “OpenSUSE”" /etc/vimrc (configuration file for vim only)" author: Klaus Franken <kfr@suse.de>" author: Werner Fink <werner@suse.de>" author: Florian La Roche <florian@suse.de>" version: 2017/04/28" commented lines start with `"'
function! SKEL_spec() 0r /usr/share/vim/current/skeletons/skeleton.spec language time en_US if $USER != '' let login = $USER elseif $LOGNAME != '' let login = $LOGNAME else let login = 'unknown' endif let newline = stridx(login, "\n") if newline != -1 let login = strpart(login, 0, newline) endif if $HOSTNAME != '' let hostname = $HOSTNAME else let hostname = system('hostname -f') if v:shell_error let hostname = 'localhost' endif endif let newline = stridx(hostname, "\n") if newline != -1 let hostname = strpart(hostname, 0, newline) endif exe "%s/specCURRENT_YEAR/" . strftime("%Y") . "/ge" exe "%s/specRPM_CREATION_DATE/" . strftime("%a\ %b\ %d\ %Y") . "/ge" exe "%s/specRPM_CREATION_AUTHOR_MAIL/" . login . "@" . hostname . "/ge" exe "%s/specRPM_CREATION_NAME/" . expand("%:t:r") . "/ge" setf specendfunction" enable syntax highlightingsyntax on
" automatically indent lines (default)" set noautoindent
" select case-insenitiv search (not default)" set ignorecase
" show cursor line and column in the status lineset ruler
" show matching bracketsset showmatch
" display mode INSERT/REPLACE/...set showmode
" changes special characters in search patterns (default)" set magic
" Required to be able to use keypad keys and map missed escape sequencesset esckeys
" get easier to use and more user friendly vim defaults" CAUTION: This option breaks some vi compatibility." Switch it off if you prefer real vi compatibilityset nocompatible
" allow backspacing over everything in insert modeset backspace=indent,eol,start
" Complete longest common string, then each full match" enable this for bash compatible behaviour" set wildmode=longest,full
" Try to get the correct main terminal typeif &term =~ "xterm" let myterm = "xterm"elseif &term =~ "screen" let myterm = "screen"else let myterm = &termendiflet myterm = substitute(myterm, "cons[0-9][0-9].*$", "linux", "")let myterm = substitute(myterm, "cons[0-9][0-9].*$", "linux", "")let myterm = substitute(myterm, "vt1[0-9][0-9].*$", "vt100", "")let myterm = substitute(myterm, "vt2[0-9][0-9].*$", "vt220", "")let myterm = substitute(myterm, "\\([^-]*\\)[_-].*$", "\\1", "")
" Here we define the keys of the NumLock in keyboard transmit mode of xterm" which misses or hasn't activated Alt/NumLock Modifiers. Often not defined" within termcap/terminfo and we should map the character printed on the keys.if myterm == "xterm" || myterm == "kvt" || myterm == "gnome" " keys in insert/command mode. map! <ESC>Oo : map! <ESC>Oj * map! <ESC>Om - map! <ESC>Ok + map! <ESC>Ol , map! <ESC>OM map! <ESC>Ow 7 map! <ESC>Ox 8 map! <ESC>Oy 9 map! <ESC>Ot 4 map! <ESC>Ou 5 map! <ESC>Ov 6 map! <ESC>Oq 1 map! <ESC>Or 2 map! <ESC>Os 3 map! <ESC>Op 0 map! <ESC>On . " 8bit control characters map! <Char-0x8F>o : map! <Char-0x8F>j * map! <Char-0x8F>m - map! <Char-0x8F>k + map! <Char-0x8F>l , map! <Char-0x8F>M map! <Char-0x8F>w 7 map! <Char-0x8F>x 8 map! <Char-0x8F>y 9 map! <Char-0x8F>t 4 map! <Char-0x8F>u 5 map! <Char-0x8F>v 6 map! <Char-0x8F>q 1 map! <Char-0x8F>r 2 map! <Char-0x8F>s 3 map! <Char-0x8F>p 0 map! <Char-0x8F>n . " keys in normal mode map <ESC>Oo : map <ESC>Oj * map <ESC>Om - map <ESC>Ok + map <ESC>Ol , map <ESC>OM map <ESC>Ow 7 map <ESC>Ox 8 map <ESC>Oy 9 map <ESC>Ot 4 map <ESC>Ou 5 map <ESC>Ov 6 map <ESC>Oq 1 map <ESC>Or 2 map <ESC>Os 3 map <ESC>Op 0 map <ESC>On . " 8bit control characters map <Char-0x8F>o : map <Char-0x8F>j * map <Char-0x8F>m - map <Char-0x8F>k + map <Char-0x8F>l , map <Char-0x8F>M map <Char-0x8F>w 7 map <Char-0x8F>x 8 map <Char-0x8F>y 9 map <Char-0x8F>t 4 map <Char-0x8F>u 5 map <Char-0x8F>v 6 map <Char-0x8F>q 1 map <Char-0x8F>r 2 map <Char-0x8F>s 3 map <Char-0x8F>p 0 map <Char-0x8F>n .endif
" xterm but without activated keyboard transmit mode" and therefore not defined in termcap/terminfo.if myterm == "xterm" || myterm == "kvt" || myterm == "gnome" " keys in insert/command mode. map! <Esc>[H <Home> map! <Esc>[F <End> map! <Char-0x8F>H <Home> map! <Char-0x8F>F <End> " Home/End: older xterms do not fit termcap/terminfo. map! <Esc>[1~ <Home> map! <Esc>[4~ <End> " Up/Down/Right/Left map! <Esc>[A <Up> map! <Esc>[B <Down> map! <Esc>[C <Right> map! <Esc>[D <Left> " 8bit control characters map! <Char-0x8F>A <Up> map! <Char-0x8F>B <Down> map! <Char-0x8F>C <Right> map! <Char-0x8F>D <Left> map! <Char-0x9B>5~ <PageUp> map! <Char-0x9B>6~ <PageDown> map! <Char-0x9B>2~ <Insert> map! <Char-0x9B>3~ <Delete> " KP_5 (NumLock off) map! <Esc>[E <Insert> " keys in normal mode map <ESC>[H 0 map <ESC>[F $ map <Char-0x8F>H 0 map <Char-0x8F>F $ " Home/End: older xterms do not fit termcap/terminfo. map <ESC>[1~ 0 map <ESC>[4~ $ " Up/Down/Right/Left map <ESC>[A k map <ESC>[B j map <ESC>[C l map <ESC>[D h " 8bit control characters map <Char-0x8F>A k map <Char-0x8F>B j map <Char-0x8F>C l map <Char-0x8F>D h map <Char-0x9B>5~ <PageUp> map <Char-0x9B>6~ <PageDown> map <Char-0x9B>2~ <Insert> map <Char-0x9B>3~ <Delete> " KP_5 (NumLock off) map <ESC>[E i map <Char-0x8F>E iendif
" xterm/kvt but with activated keyboard transmit mode." Sometimes not or wrong defined within termcap/terminfo.if myterm == "xterm" || myterm == "kvt" || myterm == "gnome" " keys in insert/command mode. map! <Esc>OH <Home> map! <Esc>OF <End> map! <ESC>O2H <Home> map! <ESC>O2F <End> map! <ESC>O5H <Home> map! <ESC>O5F <End> " Cursor keys which works mostly " map! <Esc>OA <Up> " map! <Esc>OB <Down> " map! <Esc>OC <Right> " map! <Esc>OD <Left> map! <Esc>[2;2~ <Insert> map! <Esc>[3;2~ <Delete> map! <Esc>[2;5~ <Insert> map! <Esc>[3;5~ <Delete> map! <Esc>O2A <PageUp> map! <Esc>O2B <PageDown> map! <Esc>O2C <S-Right> map! <Esc>O2D <S-Left> map! <Esc>O5A <PageUp> map! <Esc>O5B <PageDown> map! <Esc>O5C <S-Right> map! <Esc>O5D <S-Left> " KP_5 (NumLock off) map! <Esc>OE <Insert> " keys in normal mode map <ESC>OH 0 map <ESC>OF $ map <ESC>O2H 0 map <ESC>O2F $ map <ESC>O5H 0 map <ESC>O5F $ " Cursor keys which works mostly " map <ESC>OA k " map <ESC>OB j " map <ESC>OD h " map <ESC>OC l map <Esc>[2;2~ i map <Esc>[3;2~ x map <Esc>[2;5~ i map <Esc>[3;5~ x map <ESC>O2A ^B map <ESC>O2B ^F map <ESC>O2D b map <ESC>O2C w map <ESC>O5A ^B map <ESC>O5B ^F map <ESC>O5D b map <ESC>O5C w " KP_5 (NumLock off) map <ESC>OE iendif
if myterm == "linux" " keys in insert/command mode. map! <Esc>[G <Insert> " KP_5 (NumLock off) " keys in normal mode " KP_5 (NumLock off) map <ESC>[G iendif
if myterm == "screen" map! <ESC>[1;2D <S-Left> map! <ESC>[1;2C <S-Right> map! <ESC>[1;2A <S-Up> map! <ESC>[1;2B <S-Down> map! <ESC>[1;2H <Home> map! <ESC>[1;2F <End> map! <ESC>[2;2~ <Insert> map! <ESC>[3;2~ <Delete> map! <ESC>[5;2~ <PageUp> map! <ESC>[6;2~ <PageDown> map! <ESC>[1;5D <C-Left> map! <ESC>[1;5C <C-Right> map! <ESC>[1;5A <C-Up> map! <ESC>[1;5B <C-Down> map! <ESC>[1;5H <Home> map! <ESC>[1;5F <End> map! <ESC>[2;5~ <Insert> map! <ESC>[3;5~ <Delete> map! <ESC>[5;5~ <PageUp> map! <ESC>[6;5~ <PageDown> map! <ESC>[1;3D <A-Left> map! <ESC>[1;3C <A-Right> map! <ESC>[1;3A <A-Up> map! <ESC>[1;3B <A-Down> map! <ESC>[1;3H <Home> map! <ESC>[1;3F <End> map! <ESC>[2;3~ <Insert> map! <ESC>[3;3~ <Delete> map! <ESC>[5;3~ <PageUp> map! <ESC>[6;3~ <PageDown>endif
" This escape sequence is the well known ANSI sequence for" Remove Character Under The Cursor (RCUTC[tm])map! <Esc>[3~ <Delete>map <ESC>[3~ x
" Only do this part when compiled with support for autocommands.if has("autocmd") "Remember the positions in files with some git-specific exceptions" autocmd BufReadPost * \ if line("'\"") > 0 && line("'\"") <= line("$") \ && expand("%") !~ "COMMIT_EDITMSG" \ && expand("%") !~ "ADD_EDIT.patch" \ && expand("%") !~ "addp-hunk-edit.diff" \ && expand("%") !~ "git-rebase-todo" | \ exe "normal g`\"" | \ endifendif " has("autocmd")
" Changed default required by SuSE security team--be aware if enabling this" that it potentially can open for malicious users to do harmful things.set nomodeline
" Skeleton for spec filesautocmd BufNewFile *.spec call SKEL_spec()
" get easier to use and more user friendly vim defaults" /etc/vimrc ends here