让Vim打造成强大的IDE,附_vimrc的配置和使用

来源:互联网 发布:乐清知临中学地址 编辑:程序博客网 时间:2024/06/10 22:50

最近在搞linux,没有好用的IDE,想到了VIM.

配置 了下VImrc文件。发现挺好用的。这里总结下使用方法。

首先环境准备,下载windows下的VIM .GVIM。我的版本是V7.4.

然后把_vimrc配置文件放到安装目录下。这个配置文件是之前别人写好的,用着有点儿问题特意改了下。稍后附件中会附带这个。直接能用。

这里总结下 使用方法,省的时间一长又忘记了。

进入目录的方法:

按 : 号,

输入 :E  D://

则自动会进入到D盘的路径下。同理,打开GVIM后,需要进入 工作目录(如: E://work//myprj),则直接输入  :E E://work//myprj

使能ctag和 cscope,方便查找与跳转。在当前目录下,执行:  SrcInit()即可 。

自动的会去执行ctag和cscope指令,生成相关的配置。

至于快捷键,这里不介绍了。直接查看_vimrc文件即可。想添加新功能,新快捷键,直接编辑这个文件即可。

最后,还有wmmanager和taglist插件。最好都安装下。

这样才能有 类似工程目录的效果。

关于vim,有个吐槽是快捷键像 复制粘贴等,在linux和windows下都通用的,但vim不行。其实配置下也是可以的。

从网上找到方案如下:

" 映射全选+复制 ctrl+a
map <C-A> ggvG
" map! <C-A> <Esc>ggVGY
" map <F12> gg=G
" 选中状态下 Ctrl+c 复制
vmap <C-c> "+y
"在插入模式中使用Ctrl+v粘贴全局剪贴板内容
inoremap <C-v> <esc>:set paste<cr>mui<C-R>+<esc>mv'uV'v=:set nopaste<cr>

"在Visual模式中使用Ctrl+c复制内容到全局剪贴板
vnoremap <C-c> "+y

"在Visual模式中使用Ctrl+x剪切内容到全局剪贴板
vnoremap <C-x> "+x

"新建标签  
map <M-F2> :tabnew<CR>  
"列出当前目录文件  
map <C-F3> :tabnew .<CR>  

"在插入模式中使用Ctrl+v粘贴全局剪贴板内容
inoremap <C-v> <esc>:set paste<cr>mui<C-R>+<esc>mv'uV'v=:set nopaste<cr>

"在Visual模式中使用Ctrl+c复制内容到全局剪贴板
vnoremap <C-c> "+y

"在Visual模式中使用Ctrl+x剪切内容到全局剪贴板
vnoremap <C-x> "+x

附个截图:



附:_vimrc配置文件:

" Setting some decent VIM settings for programmingset ai                          " set auto-indenting on for programmingset showmatch                   " automatically show matching brackets. works like it does in bbedit.set vb                          " turn on the "visual bell" - which is much quieter than the "audio blink"set ruler                       " show the cursor position all the timeset laststatus=2                " make the last line where the status is two lines deep so you can see status alwaysset backspace=indent,eol,start  " make that backspace key work the way it shouldset nocompatible                " vi compatible is LAMEset background=dark             " Use colours that work well on a dark background (Console is usually black)set showmode                    " show the current modesyntax on                       " turn syntax highlighting on by default" Show EOL type and last modified timestamp, right after the filenameset statusline=%<%F%h%m%r\ [%{&ff}]\ (%{strftime(\"%H:%M\ %d/%m/%Y\",getftime(expand(\"%:p\")))})%=%l,%c%V\ %P"------------------------------------------------------------------------------" Only do this part when compiled with support for autocommands.if has("autocmd")    "Set UTF-8 as the default encoding for commit messages    autocmd BufReadPre COMMIT_EDITMSG,git-rebase-todo setlocal fileencodings=utf-8    "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`\"" |      \ endif      autocmd BufNewFile,BufRead *.patch set filetype=diff      autocmd BufNewFile,BufRead *.diff set filetype=diff      autocmd Syntax diff      \ highlight WhiteSpaceEOL ctermbg=red |      \ match WhiteSpaceEOL /\(^+.*\)\@<=\s\+$/      autocmd Syntax gitcommit setlocal textwidth=74endif " has("autocmd")" General optionsyntax enableset ruler numberset hlsearch incsearchset autowrite nobackupset ignorecaseset linebreakset mouse=aset cindent shiftwidth=4 tabstop=4set backspace=2set formatoptions=tcqorset scrolloff=6set tags=tags,tagsx,..\tags;set autochdirset path=**set laststatus=2set grepprg=gfind\ .\ -name\ \"*.[chs]\"\ -exec\ grep\ -iHn\ <cword>\ {}\ ;set shellpipe=2>&1\|teecompiler! gcccolorscheme tortehi StatusLine gui=reverse " guifg=darkgrey guibg=cyanhi cursorline guibg=grey30hi cursorcolumn guibg=grey20hi Search guifg=cyannmap ,d :bd<cr>nmap ,4 :set ts=4<cr>nmap tt "Ayynmap <space>f :find nmap <space>g :tag nmap <space>i [I"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Enhanced up-down-motionsnmap ff zznmap fj zbnmap fk ztnmap fm ztMnmap f, zbMnmap <space>j :call ToggleJK()<cr>let s:jk_func = 0function ToggleJK()if s:jk_func == 0nmap j <Down>zznmap k <Up>zzlet s:jk_func = 1hi StatusLine guifg=darkcyan ctermbg=11elseunmap junmap klet s:jk_func = 0hi StatusLine guifg=blue ctermbg=15endifendfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Enhanced code navigation & source code managementnmap ,. :cs find s <cword><cr>nmap ,, <C-]>nmap ,m <C-T>nmap ,j <C-^>nmap ,a :lv <cword> **/*.[chsCHS]<cr>" Update settings affected by the location of source code root directoryfunction UpdateSetting(path)execute 'set path=**,' . a:path . '/**'execute 'nmap ,a :lv <cword> ' . a:path . '/**/*.[chsCHS]<cr>'endfunction" To decide location of the source code root directorylet g:src_root = "."call UpdateSetting(g:src_root)" Rebuild environment according to source code root directorycommand -nargs=1 SrcInit call SrcInit(<f-args>)function SrcInit(str)let g:src_root = a:str" let g:src_root = resolve(getcwd() . "\\" . a:str)TagUpdatecall Warning("Now src_root: " . g:src_root)endfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Work directory type: git working copy or svn working copyfunction CheckWorkDirType()let str = system("git status")let ret = stridx(str, "branch")if ret != -1 | return "git" | endiflet str = system("svn info")let ret = stridx(str, "UUID")if ret != -1 | return "svn" | endifreturn "dir"endfunctionlet g:wd_type = CheckWorkDirType()function GetRevision()if g:wd_type == "git"let str = system("git log --pretty=%h")return str[0:6]elseif g:wd_type == "svn"let str = system("svn info")let i1 = stridx(str, "Revision")let i2 = match(str, "\n", i1)return str[i1+10 : i2-1]elsereturn "0"endifendfunctionlet g:wd_rev  = GetRevision()set statusline=%{g:wd_type}:%n>\ %<%f\ %h%m%r%w%y%=%-5B%-15.(%l/%L,\ %c%V%)\ %Pset titlestring=%F\ %=%{g:wd_type}:%{g:wd_rev}"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Function keys"nmap <special> <F1> :make!<cr>"lne # 显示下一个quickfix(location list)项nmap <special> <F1> :lne<cr>nmap <special> <F2> :lp<cr>nmap <special> <F3> :lnewer \| lli<cr>nmap <special> <F4> :lolder \| lli<cr>nmap <special> <F5> :cn<cr>nmap <special> <F6> :cp<cr>nmap <special> <F7> :call ToggleView()<cr>nmap <special> <F8> :TagUpdate<cr>if g:wd_type == "git"nmap <special> <F9>  :call GitStatus()<cr>nmap <special> <F10> :call GitLog()<CR>nmap <special> <F11> :call GitLog(bufname(""))<CR>nmap <special> <F12> :call GitDiff()<CR>elsenmap <special> <F9>  :call SvnStatus()<cr>nmap <special> <F10> :call SvnLog()<CR>nmap <special> <F11> :call SvnLog(bufname(""))<CR>nmap <special> <F12> :call SvnDiff()<CR>endif"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" For cscopeif has("cscope")set csprg=cscope csto=0 cst nocsverbif filereadable("cscope.out") " add any database in current directorycs add cscope.outelseif $CSCOPE_DB != "" " else add database pointed to by environmentcs add $CSCOPE_DBendifset csverbendif"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Save a string into a temp file and view in vimlet s:file_tmp = tempname() . "-zt"function ViewInTmpFile(str)let alist = split(a:str, "\n")call writefile(alist, s:file_tmp, 'b')let cmd = "view +setlocal\\ nomodifiable " . s:file_tmpexecute cmdendfunction" Save a command output into a temp file and view in vimfunction CmdInTmpFile(cmd)let ret = system(a:cmd)call ViewInTmpFile(ret)redrawecho "Command: " . a:cmdendfunctionfunction Warning(msg)echohl LineNr | echo a:msg | echohl Noneendfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Enhanced searchset updatetime=800hi MatchParen guifg=white guibg=grey40hi xx1 guibg=blue guifg=lightyellowhi xx2 guibg=darkgreen guifg=lightyellowhi xx3 guibg=orange guifg=lightyellow" Highlight the word under cursornmap ,8 :autocmd! CursorHold<cr>nmap ,9 :autocmd! CursorHold * nested silent! call CursorWord()<cr>nmap <space>7 :call matchadd("xx3", '\c\<' . expand('<cword>') . '\>', 11, 4)<cr>nmap <space>8 :exe '2match xx1 /\c\<' . expand('<cword>') . '\>/'<cr>nmap <space>9 :exe 'match xx2 /\c\<' . expand('<cword>') . '\>/'<cr>nmap <space>0 :exe 'call clearmatches() \| nohlsearch'<cr>let s:cursor_match_id = 0function CursorWord()call matchdelete(s:cursor_match_id)let s:cursor_match_id = matchadd("MatchParen", '\c\<' . expand('<cword>') . '\>', -1)endfunctioncommand -nargs=* -complete=tag_listfiles Vvim call Vvim(<f-args>)function Vvim(...)let searchpath = g:src_root . '/**/*.[chsCHS]'if a:0 == 0let pattern = expand("<cword>")let cmd = "lv /" . pattern . "/ " . expand("%")call matchadd("Pmenu", '\c' . pattern)elseif a:0 == 1let cmd = "lv /" . a:1 . "/ " . searchpathcall matchadd("Pmenu", '\c' . a:1)elseif a:0 == 2let ptn1 = a:1 . '.*' . a:2let ptn2 = a:2 . '.*' . a:1let pattern = '\(' . ptn1 . '\)\|\(' . ptn2 . '\)'let cmd = "lv /" . pattern . "/ " . searchpathcall matchadd("Pmenu", '\c' . a:1)call matchadd("Todo", '\c' . a:2)elselet cmd = "lv /" . a:1 . "/ " . expand("%")call matchadd("Pmenu", '\c' . a:1)endiftryecho cmdexecute cmdcatch /^Vim(lvimgrep)/call Warning("vim: No match")returnendtryendfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Git operations"let s:gitlogcmd="git log --pretty=\"%h: %Cgreen%s %C(cyan)<%an>%Creset <%ai>\" ""let s:gitlogcmd="git log --pretty=\"%h: %s <%an> <%ai>\" "let s:gitlogcmd="git log --encoding=cp936 --decorate -- "let s:diffmode = 0 " diffmode: 0 for whole source code tree, 1 for current file only.command -nargs=1 Git call Git(<f-args>)function Git(str)let gitprg = "\"c:\\program files\\git\\bin\\git.exe\" " . a:strecho system(gitprg)endfunctionfunction GitDiff()if s:diffmode == 0call CmdInTmpFile("git diff -- " . g:src_root)elsecall CmdInTmpFile("git diff -- " . bufname(""))call Warning("Diff mode: " . s:diffmode)endifset filetype=diffendfunctionfunction GitStatus()let g:wd_rev = GetRevision()echo "Work dir:" getcwd()echo "Src root:" g:src_rootecho "Git rev :" g:wd_revecho "Git branches:"Git branchecho "======================================="Git statusendfunctionfunction GitLog(...)if a:0 == 0let s:diffmode = 0call CmdInTmpFile(s:gitlogcmd . g:src_root)elselet s:diffmode = 1call CmdInTmpFile(s:gitlogcmd . a:1)endifendfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Svn operationsfunction Svn(str)let svnprg = "\"c:\\program files\\TortoiseSvn\\bin\\svn.exe\" " . a:strlet ret = system(svnprg)let xx = split(ret, "\n")let yy = sort(xx)let zz = join(yy, "\n")echo zzendfunctionfunction SvnDiff()if s:diffmode == 0call CmdInTmpFile("svn diff " . g:src_root)elsecall CmdInTmpFile("svn diff " . bufname(""))call Warning("Diff mode: " . s:diffmode)endifset filetype=diffendfunctionfunction SvnStatus()let g:wd_rev = GetRevision()echo "Work dir:" getcwd()echo "Src root:" g:src_rootecho "Svn rev :" g:wd_revcall Svn("status " . g:src_root)echo "======================================="call Svn("info")endfunctionfunction SvnLog(...)if a:0 == 0let s:diffmode = 0call CmdInTmpFile("svn log " . g:src_root)elselet s:diffmode = 1call CmdInTmpFile("svn log " . a:1)endifendfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" View patches according to svn revision number & git hash valuecommand -nargs=0 ViewRevision call ViewRevision(expand("<cword>"))function ViewRevision(rev)if g:wd_type == "git"call CmdInTmpFile("git show " . a:rev)elseif g:wd_type == "svn"call CmdInTmpFile("svn diff -c " . a:rev)elsecall Warning("No source control")endifendfunction" View blame result of current filecommand -nargs=0 Blame call Blame(expand("%"))function Blame(filename)let pos = getpos(".")if g:wd_type == "git"call CmdInTmpFile("git blame " . a:filename)elseif g:wd_type == "svn"call CmdInTmpFile("svn blame " . a:filename)elsecall Warning("No source control")returnendifcall setpos(".", pos)endfunction" Git commit in vimcommand -nargs=0 Gitcommit call Gitcommit()function Gitcommit()echo system("git diff --stat")let msg = input("Commit msg: ", "", "tag")if strlen(msg) == 0echo "Commit cannelled"returnendiflet cmd = "git commit -a -m \"" . msg . "\""echo cmdecho system(cmd)let g:wd_rev = GetRevision()endfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" tags and cscope database" let s:tagfile = tempname() . "-ztg"let s:tagfile = "tags"let s:csfile = "cscope.out"" let s:csfile = tempname() . "-zcs"function RemoveFile(filename)if filereadable(a:filename)let ret = delete(a:filename)if ret == 0echo a:filename . " removed."elsecall Warning("Fail to remove " . a:filename)endifendifendfunction" Function BuildTag(): Update tags and cscope databasecommand -nargs=0 TagUpdate call BuildTag(g:src_root)function BuildTag(path)if cscope_connection()==1cs kill -1endifcall RemoveFile(s:tagfile)call RemoveFile(s:csfile)update" Create tag filelet cmd = "ctags -R --tag-relative=yes --extra=+q --fields=+ias "" let cmd = cmd . "-f " . s:tagfile . " " . a:pathecho cmdecho system(cmd)if filereadable(s:tagfile)let cmd = "set tags=" . s:tagfileexecute cmdecho "** Ctags updated **"elsecall Warning("** Failed to update ctags **")endif" Create CS databaselet cmd = "cscope -Rb -v" " let cmd = "cscope -Rb -v -s " " let cmd = cmd . a:path." -f " . s:csfileecho cmdecho system(cmd)if filereadable(s:csfile)let cmd = "cs add " . s:csfileexecute cmdecho "** CS updated **"elsecall Warning("** Failed to update CS **")endifcall UpdateSetting(a:path)endfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Cleanup before vim exitautocmd VimLeavePre * call CleanupStuff()function CleanupStuff()if cscope_connection() == 1cs kill -1endifcall RemoveFile(s:tagfile)call RemoveFile(s:csfile)call RemoveFile(s:file_tmp)endfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Coding style: Format C code with your favorite style, format a whole file.command -nargs=0 Indentlzw call Indentlzw()function Indentlzw()let fcur = bufname("")let cmd = "indent -gnu -npsl -ts4 -i4 -bli0 -npcs -nut -fc1 -ncs -st " . fcurcall CmdInTmpFile(cmd)set filetype=cendfunction" Another style, change current file directly, no backup.command -nargs=0 Indentlzwex call Indentlzwex()function Indentlzwex()let fcur = bufname("")let cmd = "indent -gnu -npsl -ts4 -i4 -bli0 -npcs -nut -fc1 -ncs " . fcursetlocal autoreadecho system(cmd)execute "checktime " . fcurredrawset autoread<endfunction" Format selected code only.command -range -nargs=0 Rind <line1>,<line2>call Indentrange()function Indentrange() rangelet src = getline(a:firstline, a:lastline)let ftmp = tempname() . "-zi"call writefile(src, ftmp, 'b')let cmd = "indent -gnu -npsl -ts4 -i4 -bli0 -npcs -nut -fc1 -ncs " . ftmplet result = system(cmd)execute a:firstline . "," . a:lastline . "d"execute a:firstline-1 . "read " . ftmpredrawcall RemoveFile(ftmp)endfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Display timecommand -nargs=0 Timex call Timex()function Timex()echo strftime("%Y-%m-%d %H:%M:%S (%W%w)")endfunction" Online translationcommand -nargs=1 Dict call Dict(<f-args>)function Dict(word)let ftmp = tempname() . "-zd-" . a:wordlet cmd = "wget -O " . ftmp . " http://dict.baidu.com/s?wd=" . a:wordecho system(cmd)execute "vi " . ftmpendfunction" Online manpagecommand -nargs=+ Manp call Manp(<f-args>)function Manp(word, sec)let cachedir = "e:\\mydoc\\manpage\\"let fname = cachedir . a:word . "." . a:sec . ".man"if filereadable(fname)echo "file ready."elseif a:sec == "" | let a:sec = "all" | endiflet website = " \"http://man.he.net/?topic="let cmd = "wget -O " . fname . website . a:word . "§ion=" . a:sec . "\""echo system(cmd)endifexecute "vi " . fnamesetlocal filetype=man nomodifiable readonlyendfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Program buildlet s:buildprg='!make 'if filereadable("build.bat") | let s:buildprg='!build.bat ' | endifif filereadable("a.bat")     | let s:buildprg='!a.bat '     | endifcommand -nargs=? Build call Build(<q-args>)function Build(arg)exe s:buildprg . a:arg . ' 2>&1| tee ' . s:file_tmpexe 'cf ' . s:file_tmpendfunctioncommand -nargs=? -complete=file Cppcheck call Cppcheck(<f-args>)function Cppcheck(arg)exe '!cppcheck.exe --enable=all --template=gcc ' . a:arg . ' 2>&1| tee ' . s:file_tmpexe 'cf ' . s:file_tmpendfunction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Temporary settingsfiletype plugin onset completeopt=menuonenmap ,t :tag Main_Code<cr>nmap ,r :tag ProcFunc<cr>nmap ,n :exec "tag " . expand("<cword>") . "_Proxy"<cr>command -nargs=0 Gsh !"C:\Program Files\Git\bin\sh.exe" --login -icommand -nargs=0 Cmd exe '!start C:\tools\console2\console.exe -d ' . expand('%:p:h')command -nargs=? Bbb exe '!git commit -a -m "v: ' . <q-args> . '"'""""""""""""""""""""""""""""""""""""""""""""taglist插件配置"?let Tlist_Show_One_File = 1 ? ? ? ? ? ?"不同时显示多个文件的tag,只显示当前文件的"?let Tlist_Exit_OnlyWindow = 1 ? ? ? ? ?"如果taglist窗口是最后一个窗口,则退出vim"?let Tlist_Use_Right_Window = 1 ? ? ? ? "在右侧窗口中显示taglist窗口" """""""""""""""""""""""""""""""""""""""Taglist快捷键定义" taglist打开与关闭的切换,TlistOpen打开" nmap tl :TlistToggle<cr> ?""""""""""""""""""""""""""""""""""""""""""""WinManager 文件管理器插件配置let g:winManagerWindowLayout='FileExplorer'nmap wm :WMToggle

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""键盘命令""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""nmap <leader>w :w!<cr>nmap <leader>f :find<cr>" 映射全选+复制 ctrl+amap <C-A> ggVGYmap! <C-A> <Esc>ggVGYmap <F12> gg=G" 选中状态下 Ctrl+c 复制vmap <C-c> "+y"新建标签  map <M-F2> :tabnew<CR>  "列出当前目录文件  map <C-F3> :tabnew .<CR>  "共享剪贴板  set clipboard+=unnamed "自动保存set autowriteset ruler                   " 打开状态栏标尺set cursorline              " 突出显示当前行set magic                   " 设置魔术set guioptions-=T           " 隐藏工具栏set guioptions-=m           " 隐藏菜单栏"set statusline=\ %<%F[%1*%M%*%n%R%H]%=\ %y\ %0(%{&fileformat}\ %{&encoding}\ %c:%l/%L%)\" 设置在状态行显示的信息set foldcolumn=0set foldmethod=indent set foldlevel=3 set foldenable              " 开始折叠



原创粉丝点击