首页 > 代码库 > vim使用配置(转)
vim使用配置(转)
在终端下使用vim进行编辑时,默认情况下,编辑的界面上是没有行号的、语法高亮度显示、智能缩进等功能的。
为了更好的在vim下进行工作,需要手动配置一个配置文件: .vimrc
在启动vim时,当前用户根目录下的 .vimrc 文件会被自动读取,该文件可以包含一些设置甚至脚本,所以,一般情况下把 .vimrc文件创建在当前用户的根目录下比较方便,即创建的命令为:
$vim ~/.vimrc
设置完成后
$:x 或者 $:wq
进行保存退出即可。
下面给出一个例子,已经很详细了,是某位大神的配置文件,这里对其表示敬意。
"双引号开始的行为注释行,下同。
" File: _vimrc" Author: xuleaper<xuleaper@gmail.com>" Description: xuleaper‘s personal vim config file." Last Modified: $Id: _vimrc 467 2012-09-08 03:49:05Z $" Blog: http://www.gracecode.com/" Since:2010-06-15" History:" 2012-06-08" +vundle支持,更加灵活的管理插件" 2012-01-20" +整理vimrc结构" 2011-09-08" +在网络配置文件的基础上,编写自己的vimrc"=============================" vimrc_structure" |" +--Environment setting" |" +--Multi_language setting" |" +--GUI_laguage setting" |" +--AutoCmd" |" +--Plugin configure" |" +--Script‘s function" |" +--Key shortcut" |" ---Bundle setting"=============================if exists("mingcheng") finishendiflet g:mingcheng = 1if v:version < 700 echoerr ‘This _vimrc requires Vim 7 or later.‘ quitendif" ============" Environment" ============" Color Schemeif has(‘syntax‘) " 默认编辑器配色 au BufNewFile,BufRead,BufEnter,WinEnter * colo desert " 各不同类型的文件配色不同 au BufNewFile,BufRead,BufEnter,WinEnter *.wiki colo void " 保证语法高亮 syntax onendif" 保留历史记录set history=500" 行控制set linebreakset nocompatibleset textwidth=80set wrap" 标签页set tabpagemax=9set showtabline=2" 控制台响铃set noerrorbellsset novisualbellset t_vb=" 行号和标尺set numberset rulerset rulerformat=%15(%c%V\ %p%%%)" 命令行于状态行set ch=2set stl=\ [File]\ %F%m%r%h%y[%{&fileformat},%{&fileencoding}]\ %w\ \ [PWD]\ %r%{GetPWD()}%h\ %=\ [Line]%l/%L\ %=\[%P]set ls=2 " 始终显示状态行set wildmenu "命令行补全以增强模式运行" 定义 <Leader> 为逗号let mapleader = ","let maplocalleader = ","" Search Optionset hlsearch " Highlight search thingsset magic " Set magic on, for regular expressionsset showmatch " Show matching bracets when text indicator is over themset mat=2 " How many tenths of a second to blinkset noincsearch" 制表符set tabstop=4set expandtabset smarttabset shiftwidth=4set softtabstop=4" 状态栏显示目前所执行的指令set showcmd " 缩进set autoindentset smartindent" 自动重新读入set autoread" 插入模式下使用 <BS>、<Del> <C-W> <C-U>set backspace=indent,eol,start" 设定在任何模式下鼠标都可用" 自动改变当前目录if has(‘netbeans_intg‘) set autochdirendif" 备份和缓存set nobackup"set noswapfile" 自动完成set complete=.,w,b,k,t,iset completeopt=longest,menu" 代码折叠set foldmethod=marker" 共享外部剪贴板set clipboard+=unnamed"设置快速编辑.vimrc文件 ,e 编辑.vimrc" 快速修改 vimrc 文件if has("win32") map <silent> <leader>e :e $VIM/_vimrc<cr>else map <silent> <leader>e :e $VIM/.vimrc<cr>endif"保存.vimrc文件后会自动调用新的.vimrcautocmd! bufwritepost _vimrc source $VIM/_vimrc" ======================" Multi_language setting" default encoding UTF " ======================if has("multi_byte") set encoding=utf-8 "set fenc=cp936 " English messages only "language messages zh_CN.utf-8 if has(‘win32‘) language chinese let &termencoding=&encoding endif set fencs=utf-8,gbk,chinese,latin1 set formatoptions+=mM set nobomb " 不使用 Unicode 签名 if v:lang =~? ‘^\(zh\)\|\(ja\)\|\(ko\)‘ set ambiwidth=double endifelse echoerr "Sorry, this version of (g)vim was not compiled with +multi_byte"endif" 永久撤销,Vim7.3 新特性if has(‘persistent_undo‘) set undofile " 设置撤销文件的存放的目录 if has("unix") set undodir=/tmp/,~/tmp,~/Temp else set undodir=d:/temp/ endif set undolevels=1000 set undoreload=10000endif" Diff 模式的时候鼠标同步滚动 for Vim7.3if has(‘cursorbind‘) set cursorbindend"============" GUI setting" ===========if has(‘gui_running‘) " 只显示菜单 set guioptions=mcr " 高亮光标所在的行 set cursorline if has("win32") " Windows 兼容配置 source $VIMRUNTIME/mswin.vim source $VIMRUNTIME/menu.vim source $ViMRUnTIME/delmenu.vim " f11 最大化 nmap <f11> :call libcallnr(‘fullscreen.dll‘, ‘ToggleFullScreen‘, 0)<cr> nmap <Leader>ff :call libcallnr(‘fullscreen.dll‘, ‘ToggleFullScreen‘, 0)<cr> " 字体配置 exec ‘set guifont=‘.iconv(‘Consolas‘, &enc, ‘gbk‘).‘:h12:cANSI‘ exec ‘set guifontwide=‘.iconv(‘Microsoft\ YaHei‘, &enc, ‘gbk‘).‘:h12:cGB2312‘ endif " Under Linux/Unix etc. if has("unix") && !has(‘gui_macvim‘) set guifont=Courier\ 10\ Pitch\ 11 endif " Under the Mac(MacVim) if has("mac") || has("gui_macvim") if has("gui_macvim") " MacVim 下的字体配置 set guifont=Courier_New:h14 set guifontwide=YouYuan:h14 " 半透明和窗口大小 set transparency=2 set lines=200 columns=120 " 使用 MacVim 原生的全屏幕功能 let s:lines=&lines let s:columns=&columns func! FullScreenEnter() set lines=999 columns=999 set fu endf func! FullScreenLeave() let &lines=s:lines let &columns=s:columns set nofu endf func! FullScreenToggle() if &fullscreen call FullScreenLeave() else call FullScreenEnter() endif endf set guioptions+=e " Mac 下,按 <Leader>ff 切换全屏 nmap <f11> :call FullScreenToggle()<cr> nmap <Leader>ff :call FullScreenToggle()<cr> " I like TCSH :^) set shell=/bin/tcsh " Set input method off set imdisable " Set QuickTemplatePath let g:QuickTemplatePath = $HOME.‘/.vim/templates/‘ " 如果为空文件,则自动设置当前目录为桌面 lcd ~/Desktop/ endif endifendif" =========" AutoCmd" =========if has("autocmd") filetype plugin indent on " 括号自动补全 func! AutoClose() :inoremap ( ()<ESC>i :inoremap " ""<ESC>i :inoremap ‘ ‘‘<ESC>i :inoremap { {}<ESC>i :inoremap [ []<ESC>i :inoremap ) <c-r>=ClosePair(‘)‘)<CR> :inoremap } <c-r>=ClosePair(‘}‘)<CR> :inoremap ] <c-r>=ClosePair(‘]‘)<CR> endf func! ClosePair(char) if getline(‘.‘)[col(‘.‘) - 1] == a:char return "\<Right>" else return a:char endif endf""""""""""""""""""""""""""""""""""""""""""""" augroup vimrcEx au! autocmd FileType text setlocal textwidth=80 autocmd BufReadPost * \ if line("‘\"") > 0 && line("‘\"") <= line("$") | \ exe "normal g`\"" | \ endif augroup END"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Auto close quotation marks for PHP, Javascript, etc, file au FileType php,javascript,c,cpp exe AutoClose() " JavaScript 语法高亮 au FileType html,javascript let g:javascript_enable_domhtmlcss = 1 au BufRead,BufNewFile *.js setf jquery " 给各语言文件添加 Dict if has(‘win32‘) let s:dict_dir = $VIM.‘\vimfiles\dict\‘ else let s:dict_dir = $HOME."/.vim/dict/" endif let s:dict_dir = "setlocal dict+=".s:dict_dir au FileType php exec s:dict_dir."php_funclist.dict" au FileType css exec s:dict_dir."css.dict" au FileType javascript exec s:dict_dir."javascript.dict" " 格式化 JavaScript 文件 au FileType javascript map <f12> :call g:Jsbeautify()<cr> au FileType javascript set omnifunc=javascriptcomplete#CompleteJS " 增加 ActionScript 语法支持 au BufNewFile,BufRead,BufEnter,WinEnter,FileType *.as setf actionscript " CSS3 语法支持 au BufRead,BufNewFile *.css set ft=css syntax=css3 " 增加 Objective-C 语法支持 au BufNewFile,BufRead,BufEnter,WinEnter,FileType *.m,*.h setf objc " 将指定文件的换行符转换成 UNIX 格式 au FileType php,javascript,html,css,python,vim,vimwiki set ff=unix " 自动最大化窗口 if has(‘gui_running‘) if has("win32") au GUIEnter * simalt ~x "elseif has("unix") "au GUIEnter * winpos 0 0 "set lines=999 columns=999 " 给 Win32 下的 gVim 窗口设置透明度 au GUIEnter * call libcallnr("vimtweak.dll", "SetAlpha", 225) endif endifendif" =================" Plugin Configure" ================="neocomplcache setting" VIM HTML 插件let g:no_html_toolbar = ‘yes‘"""""""""""""""""""""""""""""""""""""""""""""""""""""" VimWiki 配置if !exists("g:vimwiki_list") let g:vimwiki_list = [ \{"path": "~/Wiki/Default/", "path_html": "~/Sites/wiki/", \ "html_footer": "~/Wiki/Default/footer.tpl", "html_header": "~/Wiki/Default/header.tpl", \ "auto_export": 1}, \{"path": "~/Wiki/WebWW/", "path_html": "~/Sites/webww/", "auto_export": 1} \] let g:vimwiki_auto_checkbox = 0 if has(‘win32‘) " 注意! " 1、如果在 Windows 下,盘符必须大写 " 2、路径末尾最好加上目录分隔符 let s:vimwiki_root = "$VIM/Vimwiki" let g:vimwiki_list = [ \{"path": s:vimwiki_root."/Default/", \ "html_footer": s:vimwiki_root."/Default/footer.html", \ "html_header": s:vimwiki_root."/Default/header.html", \ "path_html": s:vimwiki_root."/Default/_output/", "auto_export": 1}, \{"path": s:vimwiki_root."/WebWW/", \"path_html": s:vimwiki_root."/WebWW/html/", "auto_export": 1} \] let g:vimwiki_w32_dir_enc = ‘cp936‘ endif au FileType vimwiki set ff=unix fenc=utf8 noswapfile nobackup "au FileType vimwiki imap <C-t> <c-r>=TriggerSnippet()<cr> nmap <C-i><C-i> :VimwikiTabGoHome<cr> nmap <Leader>ii :VimwikiTabGoHome<cr>endif" on Windows, default charset is gbkif has("win32") let g:fontsize#encoding = "cp936"endif""""""""""""""""""""""""""""""""""""" PYTHON 相关的设置"设置= + - * 前后自动空格"设置,后面自动添加空格au FileType python inoremap <buffer>= <c-r>=EqualSign(‘=‘)<CR>au FileType python inoremap <buffer>+ <c-r>=EqualSign(‘+‘)<CR>au FileType python inoremap <buffer>- <c-r>=EqualSign(‘-‘)<CR>au FileType python inoremap <buffer>* <c-r>=EqualSign(‘*‘)<CR>au FileType python inoremap <buffer>/ <c-r>=EqualSign(‘/‘)<CR>au FileType python inoremap <buffer>> <c-r>=EqualSign(‘>‘)<CR>au FileType python inoremap <buffer>< <c-r>=EqualSign(‘<‘)<CR>au FileType python inoremap <buffer>: <c-r>=Swap()<CR>au FileType python inoremap <buffer>, ,<space>" ==================" script‘s functions "===================" 获取当前目录func! GetPWD() return substitute(getcwd(), "", "", "g")endf" 跳过页头注释,到首行实际代码func! GotoFirstEffectiveLine() let l:c = 0 while l:c<line("$") && ( \ getline(l:c) =~ ‘^\s*$‘ \ || synIDattr(synID(l:c, 1, 0), "name") =~ ".*Comment.*" \ || synIDattr(synID(l:c, 1, 0), "name") =~ ".*PreProc$" \ ) let l:c = l:c+1 endwhile exe "normal ".l:c."Gz\<CR>"endf" 返回当前时期func! GetDateStamp() return strftime(‘%Y-%m-%d‘)endfunction" 全选func! SelectAll() let s:current = line(‘.‘) exe "norm gg" . (&slm == "" ? "VG" : "gH\<C-O>G")endfunc" From an idea by Michael Naumannfunc! VisualSearch(direction) range let l:saved_reg = @" execute "normal! vgvy" let l:pattern = escape(@", ‘\\/.*$^~[]‘) let l:pattern = substitute(l:pattern, "\n$", "", "") if a:direction == ‘b‘ execute "normal ?" . l:pattern . "^M" elseif a:direction == ‘gv‘ call CmdLine("vimgrep " . ‘/‘. l:pattern . ‘/‘ . ‘ **/*.‘) elseif a:direction == ‘f‘ execute "normal /" . l:pattern . "^M" endif let @/ = l:pattern let @" = l:saved_regendfunc"函数后面加上!是防止vimrc文件重新载入时报错"实现光标位置自动交换:) --> ):function! Swap() if getline(‘.‘)[col(‘.‘) - 1] =~ ")" return "\<ESC>la:" else return ":" endifendf"""""""""""""""""""""""""""""""""""""""""实现+-*/前后自动添加空格,逗号后面自动添加空格,适用python"支持+= -+ *= /+格式function! EqualSign(char) if a:char =~ ‘=‘ && getline(‘.‘) =~ ".*(" return a:char endif let ex1 = getline(‘.‘)[col(‘.‘) - 3] let ex2 = getline(‘.‘)[col(‘.‘) - 2] if ex1 =~ "[-=+><>\/\*]" if ex2 !~ "\s" return "\<ESC>i".a:char."\<SPACE>" else return "\<ESC>xa".a:char."\<SPACE>" endif else if ex2 !~ "\s" return "\<SPACE>".a:char."\<SPACE>\<ESC>a" else return a:char."\<SPACE>\<ESC>a" endif endifendf """"""""""""""""""""""""""""""""""""""""""""""""""""""""SwitchToBuf()实现它在所有标签页的窗口中查找指定的文件名,如果找到这样一个窗口,"就跳到此窗口中;否则,它新建一个标签页来打开vimrc文件"上面自动编辑.vimrc文件用到的函数function! SwitchToBuf(filename) let bufwinnr = bufwinnr(a:filename) if bufwinnr != -1 exec bufwinnr . "wincmd w" return else " find in each tab tabfirst let tab = 1 while tab <= tabpagenr("$") let bufwinnr = bufwinnr(a:filename) if bufwinnr != -1 exec "normal " . tab . "gt" exec bufwinnr . "wincmd w" return endif tabnext let tab = tab + 1 endwhile " not exist, new tab exec "tabnew " . a:filename endifendfunction"""""""""""""""""""""""""""""""""""""""""""""""""""Last change用到的函数,返回时间,能够自动调整位置function! TimeStamp(...) let sbegin = ‘‘ let send = ‘‘ if a:0 >= 1 let sbegin = a:1.‘\s*‘ endif if a:0 >= 2 let send = ‘ ‘.a:2 endif let pattern = ‘Last Change: .\+‘ \. send let pattern = ‘^\s*‘ . sbegin . pattern . ‘\s*$‘ let now = strftime(‘%Y-%m-%d %H:%M:%S‘, \localtime()) let row = search(pattern, ‘n‘) if row == 0 let now = a:1 . ‘ Last Change: ‘ \. now . send call append(2, now) else let curstr = getline(row) let col = match( curstr , ‘Last‘) let spacestr = repeat(‘ ‘,col - 1) let now = a:1 . spacestr . ‘Last Change: ‘ \. now . send call setline(row, now) endifendfunction" =============" Key Shortcut" =============nmap <C-t> :tabnew<cr>nmap <C-p> :tabprevious<cr>nmap <C-n> :tabnext<cr>nmap <C-k> :tabclose<cr>nmap <C-Tab> :tabnext<cr> for i in range(1, &tabpagemax) exec ‘nmap <A-‘.i.‘> ‘.i.‘gt‘endfor" 插件快捷键nmap <C-d> :NERDTree<cr>nmap <C-e> :BufExplorer<cr>nmap <F2> :BufExplorer<cr>" 插入模式按 F4 插入当前时间imap <F4> <C-r>=GetDateStamp()<cr>map <F6> zM " 关闭所有折map <F7> zR " 打开所有折叠nmap <F8> :TagbarToggle<cr>map <F12> :!ctags -R<CR>map <C-F12> :!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q .<CR>" 新建 XHTML 、PHP、Javascript 文件的快捷键nmap <C-c><C-h> :NewQuickTemplateTab xhtml<cr>nmap <C-c><C-p> :NewQuickTemplateTab php<cr>nmap <C-c><C-j> :NewQuickTemplateTab javascript<cr>nmap <C-c><C-c> :NewQuickTemplateTab css<cr>nmap <Leader>ca :Calendar<cr>nmap <Leader>mr :MRU<cr>nmap <Leader>dd :NERDTreeToggle<cr>nmap <Leader>bf :BufExplorer<cr>nmap <Leader>tb :TagbarToggle<cr>" 直接查看第一行生效的代码nmap <C-g><C-f> :call GotoFirstEffectiveLine()<cr>" 按下 Q 不进入 Ex 模式,而是退出nmap Q :x<cr>"==================" Bundle setting" =================set nocompatible " be iMproved filetype off " required! set rtp+=$VIM/vimfiles/bundle/vundle/ "call vundle#rc(‘$VIM/vimfiles/bundle‘) " let Vundle manage Vundle " required! " My Bundles here: " original repos on github "======================================== " non github repos "======================================== "call pathogen#infect("$vim/vimfiles/bundle") filetype plugin indent on " required!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。