vim配置


Download

Notes

备份一发 vim 的配置,感觉可以抛弃 sublime text 和 codeblocks 了…

  • 单个英文的双引号(")开始行注释,类似于 C/C++ 的 //,同样,也并不作为注释结束符(不像 /* ... */
  • 如果没有set nobackup,在用 vim 编辑完一个本来存在的文件后,会产生一个备份文件,文件名是形如:原文件名~
  • map 定义键的映射(快捷键)
  • 编译函数 Compile_iTom! 开头的那些是调用系统命令(cmd),其中 gcc、g++、javac、java、python 这些要先配置好相应的环境变量
  • monokai/molokai 主题要下载(上面的网址),放在 vim 的安装路径里一个叫做colors 的目录下(如:D:\software\Vim\vim74\colors
  • 改完中文编码后,发现命令行的vim中文乱码了,所以将编码设置调到 gvim 时才用,见 if has ("gui_running") 内的设置。
  • 设置中文菜单和信息后,发现命令行的 vim 会有乱码…不搞了,设回英语。
  • 参考了几个博客,改了 n 多次之后,好像终于将大括号补全调成了类似 sublime text 的模式了,即输入{后如果补全为{},并不马上换行,要按一下回车才换,而且自动缩进,见 Carrage_Return 函数。
  • NERD Tree 插件实现了树形目录,如果不用 Vundle,手动安装的方法是:下载解压后,里面的文件夹有autoloaddoclibnerdtree_pluginpluginsyntax这几个,全部复制到D:\software\Vim\vimfiles里面,(这是 Windows 版的做法,这个文件夹里本来就有些同名的文件夹,那就合并它们就好)。
  • Commentary 要设置commentstring以支持其它文件类型的注释,见后面配置文件。 命令是 toggle 的,自动注释/反注释。
    • gc注释选中的行(可视模式用);
    • gcc注释当前行;
    • :1,10Commentary命令注释 1 到 10 行。为了方便,将命令名Commentary改成CB(用户自定义命令必须大写字母开头),就将commentary.vim
      command! -range -bar Commentary call s:go(<line1>,<line2>)
      
      改成:
      command! -range -bar CB call s:go(<line1>,<line2>)
      
  • 新增命令W(大写),亦是保存,但若尾行非空,则新增一空行作尾行
  • 显示特殊字符(tab、space 那些,listchars)时,将主题文件中 hi SpecialKey 的内容注掉,改成:hi! link SpecialKey Commenthi后要带个!才行),即将特殊字符的配色改成注释的配色,就不会过分明显,如图:
    SpecialKey
  • 想用 Vundle,用:
    # 这里 clone 的路径与配置文件中 `call vundle#begin()` 的路径一致,
    # 可以保证那个目录存在,否则会报错
    # linux
    git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
    # win7
    git clone https://github.com/VundleVim/Vundle.vim.git %USERPROFILE%/vimfiles/bundle/Vundle.vim
    
    安装先,用法见 [22]。在 vimrc 写好之后,在命令行执行 vim +PluginInstall +qall 或在 vim 内执行 :PluginInstall 以安装插件。
    • 推荐在 vim 里面安装,如果有 error,它会提示你按小写 l 查看 log)
    • 关代理! 我设置了 github 走代理,开了代理软件之后 Vundle 反而连不上 github,一直报 443 time out。
  • 用 [38] 支持 dos batch 的缩进,手动将其文件 dosbatch.vim 复制去 indent/ 下。
  • 保存时自动根据 expandtab 状态转换行首空格/缩进,参考 [40],见 Before_Saving 函数。需根据 tabstop(一缩进对几空格)调整命令中的空格数 参考 [41] 用 repeat 函数自适应 tabstop,参考 [42] 用 silent! 前缀忽略 s 命令找不到 pattern(即无需 retab)时的报错。

vimrc

  • 这些配置代码可以直接添加到原来那份 .vimrc / _vimrc 里(可能要改些细节,比如字体)
"--- Vundle ---"
set nocompatible " 必须
filetype off     " 必须,临时关闭,后面有重新打开
if(has("win32") || has("win64") || has("win95") || has("win16"))
	" windows
	set rtp+=$HOME/vimfiles/bundle/Vundle.vim
	call vundle#begin('$HOME/vimfiles/bundle')
else
	" linux
	set rtp+=~/.vim/bundle/Vundle.vim
	call vundle#begin('~/.vim/bundle')
endif
" 这里 begin 和 end 中间,按格式写要安装的插件,见 [22]
Plugin 'VundleVim/Vundle.vim'
" Plugin 'tpope/vim-commentary'
Plugin 'https://gitee.com/bigfacecat924/vim-commentary'
" Plugin 'preservim/nerdtree'
Plugin 'https://gitee.com/xie-xiaopeng/nerdtree'
" Plugin 'Vimjas/vim-python-pep8-indent'
Plugin 'https://gitee.com/tyloeng/vim-python-pep8-indent'
" Plugin 'jiangmiao/auto-pairs'
" Plugin 'https://gitee.com/rulei_mirror/auto-pairs'
" Plugin 'altercation/solarized'
Plugin 'https://gitee.com/liazpg/solarized'
" Plugin 'tomasiser/vim-code-dark'
Plugin 'https://gitee.com/bigfacecat924/vim-code-dark'
Plugin 'vim-scripts/dosbatch-indent'
call vundle#end()         " 必须
filetype plugin indent on " 必须,Vundle 要,写在这

"--- Setting ---"
"set nocompatible " 不兼容 vi
"filetype plugin indent on " 自动探测文件类型
set autoread " 文件在别的地方被改,则自动重新加载
set autochdir " 自动 cd 到当前文件所在目录
set nobackup " 不产生备份文件
"set noundofile " 不产生 .un~ 文件
if(has("win32") || has("win64") || has("win95") || has("win16"))
	set undodir=$HOME/vimundo " 将 .un~ 文件统一放到 undodir
else
	set undodir=$HOME/.vim/vimundo " 将 .un~ 文件统一放到 undodir
endif
if !isdirectory(&undodir)
    call mkdir(&undodir, "p", 0700)
endif
set hlsearch " 高亮匹配的字符串
set incsearch " 搜索时逐字符高亮(而不是等按完回车才高亮)
set backspace=indent,eol,start
set listchars=precedes:<,extends:>,tab:\|\ ,eol:¬,space:·
"set list " 显示特殊字符
let mapleader = '\'

"--- comment string ---"
" 默认用 #
"setlocal commentstring=#\ %s
" C/C++、Java 注释设为 //(空格)
autocmd FileType c,cpp,cc,java,h,hpp setlocal commentstring=//\ %s
" python、shell 为 #(空格)
autocmd FileType python,shell setlocal commentstring=#\ %s
" lua、sql 为 --(空格)
autocmd FileType lua,sql setlocal commentstring=--\ %s
" matlab 为 %(空格)
autocmd FileType matlab setlocal commentstring=%\ %s
" dosbatch 为 @REM(空格)
autocmd FileType dosbatch setlocal commentstring=\@REM\ %s

"--- Encoding ---"
set encoding=utf-8
set fileencoding=utf-8
if(has("win32") || has("win64") || has("win95") || has("win16"))
	"set termencoding=chinese " chinese是个变量
	source $VIMRUNTIME/delmenu.vim
	source $VIMRUNTIME/menu.vim
	"language messages zh_CN.utf-8
	"language messages none
	"set langmenu=none
endif
"set fileformats=unix,dos
"set fileformat=unix " 即换成 `\n` 换行
"set fileformat=dos " 即换成 `\r\n` 换行

"--- Tab ---"
set tabstop=4 " tab 宽度为 4 个空格
set softtabstop=4
set shiftwidth=4
set smartindent " 智能缩进
set cindent " C/C++ 风格缩进
set noexpandtab " tab 不转成空格
" 如果是 python,则 tab 转空格
autocmd FileType python set expandtab
autocmd FileType xml,html call Setup_XHTML()
function Setup_XHTML()
	" XML、HTML 格式设置
	set tabstop=2
	set softtabstop=2
	set shiftwidth=2
endfunction

"--- Line Wrapping ---"
set nowrap " 不要折行
" sidescroll: {0: 一次扩展半屏, 1: 续字符扩展(更流畅)}
"set sidescroll=1
" 折行时,使 j/k 可以在折行内上下移动(而不是一次跳掉整行)
noremap <slient> <expr> j (v:count == 0 ? 'gj' : 'j')
noremap <slient> <expr> k (v:count == 0 ? 'gk' : 'k')

"--- Theme ---"
syntax enable
syntax on " 语法高亮
set number " 显示行号
set ruler " 显示位置
set showcmd " 显示命令
set showmode " 显示模式
set showmatch
"set ignorecase
set smartcase
set cursorline " 高亮当前行
if(has("win32") || has("win64") || has("win95") || has("win16"))
	set t_Co=256 " codedark 主题配套设置
	set t_ut= " codedark 主题配套设置
	if has ("gui_running")
		"set cursorline " 高亮当前行
		colorscheme solarized " gVim 用 solarized 主题
	else
		"colorscheme codedark
		colorscheme desert
	endif
	set guifont=Consolas:h13:cANSI " 英文字体
	set guifontwide=YouYuan:h13 " 中文字体
endif

"--- 按时间调背景明暗:windows GUI + solarized ---"
"autocmd GUIEnter * simalt ~x " 初始最大化
autocmd GUIEnter * call Init_GUI()

func! Init_GUI()
    " config window
    set guioptions-=m " 隐藏菜单栏
    set guioptions-=T " 隐藏工具栏
    " simalt ~x
    set lines=32 columns=110

    " choose background
    " 凌晨
    let dawn_hour = 6
	let dawn_minute = 30
	" 夜晚
    let night_hour = 17
    let night_minute = 30
    " 现在
    let hour = strftime('%H')
    let minute = strftime('%M')
    " echo hour . ":" . minute
    if hour < dawn_hour
		set background=dark
	elseif (hour == dawn_hour) && (minute < dawn_minute)
		set background=dark
	elseif hour < night_hour
        set background=light
    elseif (hour == night_hour) && (minute < night_minute)
        set background=light
    else
        set background=dark
    endif
endfunc

"--- Buffer ---"
" 向前
noremap <C-Left> gT
inoremap <C-Left> <ESC>gTa
vnoremap <C-Left> <ESC>gT
" 向后
noremap <C-Right> gt
inoremap <C-Right> <ESC>gta
vnoremap <C-Right> <ESC>gt
" 打开
noremap <C-t> :tabe 
inoremap <C-t> <ESC>:tabe 
vnoremap <C-t> <ESC>:tabe 
" 关闭 <- Ctrl-w 跟窗口切换冲突,打开目录时不方便
"noremap <C-w> :q<CR>
"inoremap <C-w> <ESC>:q<CR>
"vnoremap <C-w> <ESC>:q<CR>

"--- NERDTree ---"
" F2 开/关
noremap <F2> :NERDTreeToggle<CR>
inoremap <F2> <ESC>:NERDTreeToggle<CR>
" Ctrl + F2 指定目录打开
noremap <C-F2> :NERDTree
inoremap <C-F2> <ESC>:NERDTree

"--- Code Folding ---"
set foldenable " 开启代码折叠
set foldmethod=manual " 手动设置折叠,用 zf 命令创建折叠
" Ctrl-f 展开或收起折叠,本来用 zo 展开,zc 再折起
nnoremap <C-f> @=((foldclosed(line('.')) < 0) ? 'zc':'zo')<CR>

"--- 全选 ---"
inoremap <C-a> <ESC>ggvG$
noremap <C-a> ggvG$

"--- 复制、剪切、粘贴 ---"
" 用 Ctrl + insert、shift + insert 就行
"vnoremap <C-S-c> "+y 
"vnoremap <C-x> "+x
"noremap <C-S-v> "+p
"inoremap <C-S-v> <ESC>"+pa


"--- 交换窗口位置 ---"
nmap <silent> <leader>mw :call MarkWindowSwap()<CR>
nmap <silent> <leader>pw :call DoWindowSwap()<CR>

function! MarkWindowSwap()
    let g:markedWinNum = winnr()
endfunction

function! DoWindowSwap()
    "Mark destination
    let curNum = winnr()
    let curBuf = bufnr( "%" )
    exe g:markedWinNum . "wincmd w"
    "Switch to source and shuffle dest->source
    let markedBuf = bufnr( "%" )
    "Hide and open so that we aren't prompted and keep history
    exe 'hide buf' curBuf
    "Switch to dest and shuffle source->dest
    exe curNum . "wincmd w"
    "Hide and open so that we aren't prompted and keep history
    exe 'hide buf' markedBuf 
endfunction


"--- F9 编译运行 ---"
noremap <F9> :call Compile_iTom()<CR>
inoremap <F9> <ESC>:call Compile_iTom()<CR>

func! Compile_iTom()
	exec "w"
	if &filetype == 'c'
		exec "! gcc % -o %<"
		exec "! ./%<"
	elseif &filetype == 'cpp'
		exec "! g++ % -o %<"
		exec "! ./%<"
	elseif &filetype == 'java'
		exec "! javac %"
		exec "! java %<"
	elseif &filetype == 'python'
		exec "! python %"
	elseif &filetype == 'matlab'
		exec "! octave %"
	elseif &filetype == 'sh'
		exec "! bash %"
	elseif &filetype == 'dosbatch'
		exec "! %"
	elseif &filetype == 'ps1'
		exec "! powershell -executionpolicy bypass -File %"
	endif
endfunc


"--- 尖括号 ---"
autocmd FileType xml,html inoremap < <lt>><Left>|
	inoremap > <C-r>=Close_Pair('>')<CR>

"--- 左括号 ---"
inoremap ( <C-r>=Open_Pair('(', ')')<CR>
"inoremap [ <C-r>=Open_Pair('[', ']')<CR>
inoremap { <C-r>=Open_Pair('{', '}')<CR>

func! Open_Pair(open, close)
    let line = getline('.')
	let nxt_char = line[col('.') - 1]
    if col('.') > strlen(line) || nxt_char == ' '
		return a:open.a:close."\<Left>"
    elseif nxt_char == a:close
        return a:open
	elseif nxt_char == ')' || nxt_char == ']' || nxt_char == '}'
		return a:open.a:close."\<Left>"
	else
		return a:open
    endif
endfunc

"--- 右括号 ---"
inoremap ) <C-r>=Close_Pair(')')<CR>
inoremap ] <C-r>=Close_Pair(']')<CR>
inoremap } <C-r>=Close_Pair('}')<CR>

func! Close_Pair(char)
	if getline('.')[col('.') - 1] == a:char
		return "\<Right>"
	else
		return a:char
	endif
endfunc

"--- 引号 ---"
inoremap " <C-r>=Same_Pair('"')<CR>
inoremap ' <C-r>=Same_Pair("'")<CR>
inoremap ` <C-r>=Same_Pair('`')<CR>

func! Same_Pair(char)
    let line = getline('.')
	let pair = a:char.a:char."\<Left>"
    if col('.') > strlen(line) " || line[col('.') - 1] == ' '
        return pair
    elseif line[col('.') - 1] == a:char
        return "\<Right>"
    else
		let pre_char = line[col('.') - 2]
		let nxt_char = line[col('.') - 1]
		if pre_char == '(' && nxt_char == ')'
			return pair
        elseif pre_char == '[' && nxt_char == ']'
            return pair
        elseif pre_char == '{' && nxt_char == '}'
            return pair
        elseif pre_char == '<' && nxt_char == '>'
            return pair
		else
			return a:char
		endif
    endif
endfunc


"--- 回车 ---"
autocmd FileType h,c,cpp,java,python,sh,dosbatch inoremap <CR> <C-r>=Carrage_Return()<CR>

func! Carrage_Return()
	let line = getline('.')
	let pre_char = line[col('.') - 2]
	let nxt_char = line[col('.') - 1]
	if &filetype == 'dosbatch'
		if pre_char == '(' && nxt_char == ')'
			return "\<CR>\<Up>\<ESC>A\<CR>"
		endif
	elseif pre_char == '{' && nxt_char == '}'
		return "\<CR>\<Up>\<ESC>A\<CR>"
    endif
	return "\<CR>"
endfunc


"--- 退格 ---"
inoremap <BS> <C-r>=Back_Space()<CR>

func! Back_Space()
	let line = getline('.')
	let pre_char = line[col('.') - 2]
	let nxt_char = line[col('.') - 1]
	let del_pair = "\<BS>\<DEL>"
	if pre_char == '(' && nxt_char == ')'
		return del_pair
	elseif pre_char == '[' && nxt_char == ']'
		return del_pair
	elseif pre_char == '{' && nxt_char == '}'
		return del_pair
	elseif pre_char == '<' && nxt_char == '>'
		return del_pair
	elseif pre_char == '"' && nxt_char == '"'
		return del_pair
	elseif pre_char == "'" && nxt_char == "'"
		return del_pair
	elseif pre_char == '`' && nxt_char == '`'
		return del_pair
	else
		return "\<BS>"
	endif
endfunc


"--- 缩进 ---"
"autocmd FileType h,c,cpp,java,python inoremap <S-TAB> <C-r>=Tabulator()<CR>

func! Tabulator()
    if strlen(getline('.')) < 1
        return "\<BS>\<CR>"
    else
        return "\<TAB>"
    endif
endfunc


"--- 保存前:删行未空白、文末空行,再补一个文末的空行 ---"
autocmd BufWritePre * call Before_Saving()

func! Before_Saving()
    " 删行末空白,注意 `\\` 转义
    exec "%s/\\s\\+$//e"

	" retab 行首空格、缩进
	" 用 `repeat` 自适应 `tabstop`
	" 用 `silent!` 避免 `s` 命令找不到 pattern(即无需 retab)时的报错
	if 0 == &expandtab
		let retabcmd = "silent! %s/\\(^\\s*\\)\\@<=" . repeat(' ', &tabstop) . "/\\t/g"
	else " expandtab
		let retabcmd = "silent! %s/\\(^\\s*\\)\\@<=\\t/" . repeat(' ', &tabstop) . "/g"
	endif
	exec retabcmd

    " _vimrc/.vimrc 中保留 :tabe 后的空格
    let this_file = expand('%')
    if this_file == '_vimrc' || this_file == '.vimrc'
        exec "%s/:tabe$/:tabe /e"
    endif

    " 删文末空行
    let ln_nb = prevnonblank('$')
    let ln_eof = line('$')
    if ln_eof > ln_nb + 1
        exec (ln_nb + 1) . "," . ln_eof . "d"
    endif
    " 补文末空行
    if prevnonblank('$') == line('$')
        call append(line('$'), "")
    endif
endfunc


"--- highlight current word ---"
" From: https://stackoverflow.com/questions/25227281/how-to-auto-highlight-the-current-word-in-vim
" Highlight all instances of word under cursor, when idle.
" Useful when studying strange source code.
" Type z/ to toggle highlighting on/off.
nnoremap z/ :if AutoHighlightToggle()<Bar>set hls<Bar>endif<CR>
function! AutoHighlightToggle()
    let @/ = ''
    if exists('#auto_highlight')
        au! auto_highlight
        augroup! auto_highlight
        setl updatetime=4000
        echo 'Highlight current word: off'
        return 0
    else
        augroup auto_highlight
            au!
            au CursorHold * let @/ = '\V\<'.escape(expand('<cword>'), '\').'\>'
        augroup end
        setl updatetime=500 " after how long of cursor hold before highlighting
        echo 'Highlight current word: ON'
        return 1
    endif
endfunction

Reference

  1. 【Vim】使用map自定义快捷键
  2. 自己动手扩展vim插件——配色篇
  3. vim的shiftwidth、tabstop、softtabstop设置
  4. vim、gvim 在 windows 下中文乱码的终极解决方案
  5. 谈谈Unicode编码,简要解释UCS、UTF、BMP、BOM等名词
  6. vim 括号补全小技巧
  7. 禁止vim生成 un~文件
  8. gvim 语言设置
  9. vim括号匹配等跳转技巧
  10. Vim快速移动光标至行首和行尾
  11. 怎样让一个vim脚本只对特定文件类型有效?
  12. GitHub - Valloric/YouCompleteMe: A code-completion engine for Vim
  13. [Hacking VIM]之定制:切换菜单和工具栏
  14. VIM个性化配置
  15. 每日一Vim(15)折叠(fold)
  16. Vim插件之vim-commentary
  17. How to add a command in vim editor?
  18. 你认为最好看的 Vim 配色方案(color scheme)是哪款?
  19. Vim查找替换 & 正则表达式
  20. vim - show whitespace for selection only
  21. Vim and PEP 8 — Style Guide for Python Code
  22. vim插件管理器:Vundle的介绍及安装(很全)
  23. autocmd(包括各种 autocmd 的激活事件)
  24. How to set two autocmd BufWritePre in .vimrc
  25. 编写 Vim 脚本(vimscript 语法)
  26. vim script: strftime
  27. 设置GVIM的默认初试界面大小、启动位置
  28. Opening files by default to the right split? #327(NERDtree 用 s侧打开,o方打开)
  29. How to Use the Vim <leader> Key
  30. How can I swap positions of two open files (in splits) in vim?
  31. Vim Vundle installation on windows: unknown function vundle#begin
  32. vim脚本判断操作系统
  33. How can I create a folder if it doesn’t exist, from .vimrc?
  34. VIM学习笔记 折行(Wrap)
  35. Multiple autocommands in vim
  36. How do I get the name and extension of the current file?
  37. 神级编辑器 Vim 使用-正则替换篇
  38. vim-scripts/dosbatch-indent
  39. How to auto highlight the current word in vim?
  40. How can I convert leading spaces to tabs in Vim or Linux?
  41. vimscript: how to repeat a string N times?
  42. Omit ‘Pattern not found’ error message in Vim script
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值