Vim 基础配置文件指南
我的 .vimrc 配置
"===
"===编写脚本自动插入
"===
function AddTitleForShell()
call append(0,"#!/bin/bash")
call append(1,"# **********************************************************")
call append(2,"# * Author : Burgess Leo")
call append(3,"# * Email : liuxp731@qq.com")
call append(4,"# * Create time : ".strftime("%Y-%m-%d %H:%M"))
call append(5,"# * Filename : ".expand("%:t"))
call append(6,"# * Description : ")
call append(7,"# **********************************************************")
endfunction
autocmd BufNewFile *.sh call AddTitleForShell()
"===
"===Sync my plugins setting
"===
if empty(glob('~/.vim/autoload/plug.vim'))
silent !curl -fLo ~/.vim/autoload/plug.vim --create-dirs
\ https://raw.githubusercontent.com/lxp731/topazleaves/refs/heads/main/src/mdbook-files/plug.vim
autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif
"===
"===System Setting
"===
let mapleader=" "
set nocompatible
set showcmd
set mouse=a
set clipboard=unnamed
vnoremap Y :w !xclip -i -sel c<CR>
filetype on
filetype indent on
filetype plugin on
filetype plugin indent on
"set laststatus=2
set autochdir
set dictionary+=/usr/share/dict/words
"autocmd InsertLeave * write
"autocmd FocusLost * if &modified | write | endif
"===
"===Open the vimrc anytime
"===
noremap <LEADER>rc :e ~/.vimrc<CR>
map <LEADER>fd /\(\<\w\+\>\)\_s*\1
"===
"===Show command autocomplete
"===
set wildignore=log/**,node_modules/**,target/**,tmp/**,*.rbc
set wildmenu
set wildmode=longest,list,full
"===
"===Search Setting
"===
set hlsearch
exec "nohlsearch"
set incsearch
set ignorecase
set smartcase
"===
"===Code Display
"===
set encoding=UTF-8
syntax on
set number
set relativenumber
set cursorline
let &t_ut=''
"===
"===Tab behavior
"===
set expandtab
set tabstop=2
set shiftwidth=2
set softtabstop=2
set list
set listchars=tab:▸\ ,trail:▫
set scrolloff=5
"===
"===Prevent auto line split
"===
set tw=0
set wrap
set indentexpr=
set backspace=indent,eol,start
set foldmethod=indent
set foldlevel=99
"===
"===快捷键映射
"===
nnoremap <LEADER><CR> :nohlsearch<CR>
nnoremap s <nop>
nnoremap S :w<CR>
nnoremap R :source $MYVIMRC<CR>
nnoremap XX :q!<CR>
nnoremap j k
nnoremap k j
nnoremap = nzz
nnoremap - Nzz
nnoremap W 5w
nnoremap B 5b
nnoremap <C-j> :belowright term<CR>
"===
"===Edit mode shortkey
"===
inoremap <C-z> <C-o>u
inoremap <C-l> <C-o>o
inoremap <C-S-k> <Esc>ddi
inoremap <C-y> <Esc>:normal! yyp<CR>a
inoremap <C-s> <Esc>:w<CR>i
"===
"===Line Moving
"===
nnoremap <A-Down> ddp
nnoremap <A-Up> dd2kp
inoremap <A-Up> <Esc>ddkPgi
inoremap <A-Down> <Esc>ddjPgi
"===
"===Words spell Checking
"===
map <LEADER>pl :set spell!<CR>
nnoremap <C-x> ea<C-x>s
inoremap <C-x> <Esc>ea<C-x>s
"===
"===分割窗口
"===
nnoremap sl :set splitright<CR>:vsplit<CR>
nnoremap snl :set nosplitright<CR>:vsplit<CR>
nnoremap sk :set splitbelow<CR>:split<CR>
nnoremap snk :set nosplitbelow<CR>:split<CR>
nnoremap <LEADER>l <C-w>l
nnoremap <LEADER>h <C-w>h
nnoremap <LEADER>j <C-w>k
nnoremap <LEADER>k <C-w>j
nnoremap <C-Up> :res +2<CR>
nnoremap <C-Down> :res -2<CR>
nnoremap <C-Left> :vertical resize-2<CR>
nnoremap <C-Right> :vertical resize+2<CR>
map <LEADER>sv <C-w>t<C-w>H
map <LEADER>sh <C-w>t<C-w>K
"===
"===Tab Management
"===
nnoremap th :tabprevious<CR>
nnoremap tl :tabnext<CR>
nnoremap to :tabclose<CR>
nnoremap tq :tabfirst<CR>
nnoremap tp :tablast<CR>
" Insert mode mappings
"inoremap tl <C-O>:tabnext<CR>
"inoremap th <C-O>:tabprevious<CR>
"inoremap tq <C-O>:tabfirst<CR>
"inoremap tp <C-O>:tablast<CR>
"===
"===保存VIM光标位置
"===
augroup remember_last_cursor_position
autocmd!
autocmd BufWritePost * mkview
autocmd BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g`\"" | endif
augroup END
"===
"===VIM 插件管理器
"===
call plug#begin('~/.vim/plugged')
Plug 'sheerun/vim-polyglot'
Plug 'connorholyday/vim-snazzy'
" File navigation
Plug 'preservim/nerdtree'
Plug 'Xuyuanp/nerdtree-git-plugin'
" Taglist
Plug 'preservim/tagbar'
" Error checking
Plug 'dense-analysis/ale'
" Auto Complete
Plug 'Valloric/YouCompleteMe'
" Undo Tree
Plug 'mbbill/undotree'
" Other visual enhancement
Plug 'nathanaelkane/vim-indent-guides'
Plug 'itchyny/vim-cursorword'
" Git
Plug 'rhysd/conflict-marker.vim'
Plug 'tpope/vim-fugitive'
Plug 'mhinz/vim-signify'
Plug 'gisphm/vim-gitignore', { 'for': ['gitignore', 'vim-plug'] }
" HTML, CSS, JavaScript, PHP, JSON, etc.
Plug 'elzr/vim-json'
Plug 'hail2u/vim-css3-syntax'
Plug 'spf13/PIV', { 'for' :['php', 'vim-plug'] }
Plug 'gko/vim-coloresque', { 'for': ['vim-plug', 'php', 'html', 'javascript', 'css', 'less'] }
Plug 'pangloss/vim-javascript', { 'for' :['javascript', 'vim-plug'] }
Plug 'mattn/emmet-vim'
" Python
Plug 'vim-scripts/indentpython.vim'
Plug 'linux-cultist/venv-selector.nvim'
" Markdown
Plug 'iamcco/markdown-preview.nvim', { 'do': { -> mkdp#util#install_sync() }, 'for' :['markdown', 'vim-plug'] }
Plug 'dhruvasagar/vim-table-mode', { 'on': 'TableModeToggle' }
Plug 'vimwiki/vimwiki'
" Bookmarks
Plug 'kshenoy/vim-signature'
" Other useful utilities
Plug 'terryma/vim-multiple-cursors'
Plug 'junegunn/goyo.vim' " distraction free writing mode
Plug 'tpope/vim-surround' " type ysks' to wrap the word with '' or type cs'` to change 'word' to `word`
Plug 'godlygeek/tabular' " type ;Tabularize /= to align the =
Plug 'gcmt/wildfire.vim' " in Visual mode, type i' to select all text in '', or type i) i] i} ip
Plug 'scrooloose/nerdcommenter' " in <space>cc to comment a line
" Dependencies
Plug 'MarcWeber/vim-addon-mw-utils'
Plug 'kana/vim-textobj-user'
Plug 'fadein/vim-FIGlet'
" commenter
Plug 'preservim/nerdcommenter'
call plug#end()
"===
"===Snazzy Setting
"===
map <LEADER>c1 :set background=dark<CR>:colorscheme snazzy<CR>:AirlineTheme drak<CR>
map <LEADER>c2 :set background=light<CR>:colorscheme sorbet<CR>:AirlineTheme dark<CR>
let g:SnazzyTransparent = 1
color sorbet
"color snazzy
"color slate
"color desert
"color industry
"color evening
"color habamax
"color peachpuff
"color elflord
"color pablo
"color murphy
"color lunaperche
"color koehler
"===
"===NERDTree Setting
"===
"Start NERDTree when Vim starts with a directory argument.
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists('s:std_in') |
\ execute 'NERDTree' argv()[0] | wincmd p | enew | execute 'cd '.argv()[0] | endif
"Close the tab if NERDTree is the only window remaining in it.
autocmd BufEnter * if winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() | quit | endif
nnoremap <C-t> :NERDTreeToggle<CR>
"nnoremap <C-n> :NERDTree<CR>
"nnoremap <C-f> :NERDTreeFind<CR>
"nnoremap <leader>n :NERDTreeFocus<CR>
" ===
" === NERDTree-git
" ===
"let g:NERDTreeGitStatusUseNerdFonts = 1
let g:NERDTreeGitStatusIndicatorMapCustom = {
\ 'Modified' :'✹',
\ 'Staged' :'✚',
\ 'Untracked' :'✭',
\ 'Renamed' :'➜',
\ 'Unmerged' :'═',
\ 'Deleted' :'✖',
\ 'Dirty' :'✗',
\ 'Ignored' :'☒',
\ 'Clean' :'✔︎',
\ 'Unknown' :'?',
\ }
" ===
" === Tagbar
" ===
" nmap <F8> :TagbarToggle<CR>
"===
"===ALE
"===
" let g:ale_fixers = {
" \ '*': ['remove_trailing_lines', 'trim_whitespace'],
" \ 'javascript': ['eslint'],
" \}
" let g:ale_fix_on_save = 1
" call deoplete#custom#option('sources', {
" \ '_': ['ale', 'foobar'],
" \})
" let g:ale_completion_enabled = 1
"===
"===Markdown Preview
"===
let g:mkdp_auto_start = 0
let g:mkdp_auto_close = 1
let g:mkdp_refresh_slow = 0
let g:mkdp_command_for_global = 0
let g:mkdp_open_to_the_world = 0
let g:mkdp_open_ip = ''
let g:mkdp_browser = ''
let g:mkdp_echo_preview_url = 0
let g:mkdp_browserfunc = ''
let g:mkdp_preview_options = {
\ 'mkit': {},
\ 'katex': {},
\ 'uml': {},
\ 'maid': {},
\ 'disable_sync_scroll': 0,
\ 'sync_scroll_type': 'middle',
\ 'hide_yaml_meta': 1
\ }
let g:mkdp_markdown_css = ''
let g:mkdp_highlight_css = ''
let g:mkdp_page_title = '「${name}」'
let g:mkdp_port = '3001'
let g:mkdp_theme = 'light' "dark OR light
" combine preview window
" ensure to set let g:mkdp_auto_close = 0 if you have enable this option
let g:mkdp_combine_preview = 0
" auto refetch combine preview contents when change markdown buffer
" only when g:mkdp_combine_preview is 1
let g:mkdp_combine_preview_auto_refresh = 1
noremap mp :MarkdownPreview<CR>
noremap ms :MarkdownPreviewStop<CR>
"===
"===MarkdownEdit
"===
autocmd Filetype markdown inoremap ,1 #<Space><Enter><++><Esc>kA
autocmd Filetype markdown inoremap ,2 ##<Space><Enter><++><Esc>kA
autocmd Filetype markdown inoremap ,3 ###<Space><Enter><++><Esc>kA
autocmd Filetype markdown inoremap ,4 ####<Space><Enter><++><Esc>kA
autocmd Filetype markdown inoremap ,5 #####<Space><Enter><++><Esc>kA
autocmd Filetype markdown inoremap ,6 ######<Space><Enter><++><Esc>kA
autocmd Filetype markdown inoremap ,f <Esc>/<++><CR>:nohlsearch<CR>c4l
autocmd Filetype markdown inoremap ,b **** <++><Esc>F*hi
autocmd Filetype markdown inoremap ,i ** <++><Esc>F*i
autocmd Filetype markdown inoremap ,s ~~~~ <++><Esc>F~hi
autocmd Filetype markdown inoremap ,d `` <++><Esc>F`i
autocmd Filetype markdown inoremap ,c ```<Enter><++><Enter>```<Enter><Enter><++><Esc>4kA
autocmd Filetype markdown inoremap ,a [](<++>) <++><Esc>F[a
autocmd Filetype markdown inoremap ,p  <++><Esc>F[a
function! CreateTable(num_cols)
let col_str = repeat('|<++>', a:num_cols) . '|'
let separator = repeat('|:----:', a:num_cols) . '|'
let result = col_str . "\n" . separator . "\n" . col_str
return result
endfunction
autocmd Filetype markdown inoremap ,t2 <Esc>i<C-R>=CreateTable(2)<CR><Esc>^3klc5l
autocmd Filetype markdown inoremap ,t3 <Esc>i<C-R>=CreateTable(3)<CR><Esc>^3klc5l
autocmd Filetype markdown inoremap ,t4 <Esc>i<C-R>=CreateTable(4)<CR><Esc>^3klc5l
autocmd Filetype markdown inoremap ,t5 <Esc>i<C-R>=CreateTable(5)<CR><Esc>^3klc5l
autocmd Filetype markdown inoremap ,t6 <Esc>i<C-R>=CreateTable(6)<CR><Esc>^3klc5l
" autocmd Filetype markdown inoremap ,t3 \|<++>\|<++>\|<++>\|<Enter>\|:----:\|:----:\|:----:\|<Enter>\|<++>\|<++>\|<++>\|<Enter><Esc>3klc4l
" autocmd Filetype markdown inoremap ,t2 \|<++>\|<++>\|<Enter>\|:----:\|:----:\|<Enter>\|<++>\|<++>\|<Enter><Esc>3klc4l
function! CreateMarkdownRow(num_cols)
let col_str = repeat('|<++>', a:num_cols) . '|'
return col_str
endfunction
autocmd Filetype markdown inoremap ,l2 <Esc>o<C-R>=CreateMarkdownRow(2)<CR><Esc>^lc5l
autocmd Filetype markdown inoremap ,l3 <Esc>o<C-R>=CreateMarkdownRow(3)<CR><Esc>^lc5l
autocmd Filetype markdown inoremap ,l4 <Esc>o<C-R>=CreateMarkdownRow(4)<CR><Esc>^lc5l
autocmd Filetype markdown inoremap ,l5 <Esc>o<C-R>=CreateMarkdownRow(5)<CR><Esc>^lc5l
autocmd Filetype markdown inoremap ,l6 <Esc>o<C-R>=CreateMarkdownRow(6)<CR><Esc>^lc5l
" autocmd Filetype markdown inoremap ,l2 \|<++>\|<++>\|
" autocmd Filetype markdown inoremap ,l3 \|<++>\|<++>\|<++>\|
autocmd Filetype markdown inoremap <C-s> <C-o>:w<CR>
"===
"===UndoTree
"===
nnoremap <F5> :UndotreeToggle<CR>
"===
"===vim-surround
"===
" objects: word(iw), line(s), tag(t)
" opretion: add, remove, change
" add: ys[objects] [Mark]
" remove: ds [Mark]
" change: cs [src_Mark], [dst_Mark]
"===
"===nerdcommenter
"===
let g:NERDCreateDefaultMappings = 1
let g:NERDSpaceDelims = 1
let g:NERDCompactSexyComs = 1
let g:NERDDefaultAlign = 'left'
let g:NERDAltDelims_java = 1
let g:NERDCustomDelimiters = { 'c': { 'left': '/**','right': '*/' } }
let g:NERDCommentEmptyLines = 1
let g:NERDTrimTrailingWhitespace = 1
let g:NERDToggleCheckAllLines = 1
配置文件详解
1. 基础设置
" 设置不兼容 vi
set nocompatible
" 启用文件类型检测
filetype on
filetype plugin on
filetype indent on
" 设置编码
set encoding=utf-8
set fileencodings=utf-8,gbk,big5,latin1
2. 界面设置
" 语法高亮
syntax on
" 显示行号
set number
" 显示相对行号
set relativenumber
" 高亮当前行
set cursorline
" 显示状态栏
set laststatus=2
" 显示命令
set showcmd
" 显示匹配的括号
set showmatch
3. 编辑设置
" 启用鼠标
set mouse=a
" 设置缩进
set autoindent
set smartindent
set tabstop=4
set shiftwidth=4
set expandtab
" 启用回退删除
set backspace=indent,eol,start
" 启用持久性撤销
set undofile
set undodir=~/.vim/undodir
4. 搜索设置
" 搜索时忽略大小写
set ignorecase
set smartcase
" 高亮搜索结果
set hlsearch
" 输入时实时搜索
set incsearch
" 搜索时循环
set wrapscan
5. 性能优化
" 禁用交换文件
set noswapfile
" 禁用备份文件
set nobackup
set nowritebackup
" 减少更新延迟
set updatetime=300
" 禁用错误铃声
set noerrorbells
set novisualbell
常用配置选项
1. 主题和颜色
" 设置配色方案
colorscheme desert
" 真彩色支持
set termguicolors
" 设置背景
set background=dark
2. 快捷键映射
" 设置 Leader 键
let mapleader = ","
" 快速保存
nnoremap <leader>w :w<CR>
" 快速退出
nnoremap <leader>q :q<CR>
" 切换行号显示
nnoremap <leader>n :set number!<CR>
" 清除搜索高亮
nnoremap <leader>h :nohlsearch<CR>
3. 插件相关
" 插件管理器初始化
call plug#begin('~/.vim/plugged')
" 插件列表
Plug 'tpope/vim-sensible'
Plug 'scrooloose/nerdtree'
Plug 'vim-airline/vim-airline'
call plug#end()
4. 文件类型特定设置
" Python 文件设置
autocmd FileType python setlocal
\ tabstop=4
\ softtabstop=4
\ shiftwidth=4
\ textwidth=79
\ expandtab
\ autoindent
\ fileformat=unix
" Markdown 文件设置
autocmd FileType markdown setlocal
\ wrap
\ linebreak
\ spell
\ spelllang=en_us
配置技巧
1. 条件配置
" 根据操作系统配置
if has('win32')
set shell=cmd.exe
else
set shell=/bin/bash
endif
" 根据终端类型配置
if &term =~ '^screen'
" tmux 特定配置
endif
2. 函数定义
" 自定义函数:删除尾部空格
function! StripTrailingWhitespace()
let l = line(".")
let c = col(".")
%s/\s\+$//e
call cursor(l, c)
endfunction
" 映射到快捷键
nnoremap <leader>sw :call StripTrailingWhitespace()<CR>
3. 自动命令
" 保存时自动格式化
autocmd BufWritePre *.py,*.js,*.json,*.md,*.txt :call StripTrailingWhitespace()
" 打开文件时自动定位到上次位置
autocmd BufReadPost *
\ if line("'\"") >= 1 && line("'\"") <= line("$") && &ft !~# 'commit'
\ | exe "normal! g`\""
\ | endif
配置文件管理
1. 模块化配置
# 创建配置目录结构
~/.vim/
├── vimrc # 主配置文件
├── config/
│ ├── basic.vim # 基础设置
│ ├── keymaps.vim # 快捷键映射
│ ├── plugins.vim # 插件配置
│ └── filetypes.vim # 文件类型设置
└── after/ # 后加载配置
2. 在 vimrc 中引入模块
" 加载模块化配置
source ~/.vim/config/basic.vim
source ~/.vim/config/keymaps.vim
source ~/.vim/config/plugins.vim
source ~/.vim/config/filetypes.vim
3. 版本控制
# 初始化 Git 仓库
cd ~
git init
git add .vimrc .vim/
git commit -m "Initial vim configuration"
调试和测试
1. 检查配置
" 查看当前设置
:set all
" 查看特定选项
:set tabstop?
" 检查语法
:syntax
2. 性能分析
" 启动性能分析
:profile start profile.log
:profile func *
:profile file *
" 执行操作
" ...
" 停止分析
:profile pause
:q
3. 错误排查
" 查看错误信息
:messages
" 查看加载的脚本
:scriptnames
" 检查运行时路径
:set runtimepath?
推荐配置
1. 开发环境配置
" 代码开发专用配置
set number
set relativenumber
set cursorline
set colorcolumn=80
set signcolumn=yes
set scrolloff=5
2. 写作环境配置
" 写作专用配置
set wrap
set linebreak
set spell
set spelllang=en_us,zh_cn
set conceallevel=2
set concealcursor=nc
3. 演示环境配置
" 演示专用配置
set nonumber
set norelativenumber
set nocursorline
set laststatus=0
set showmode
set showcmd
常见问题
问题 1:配置不生效
# 检查配置文件位置
ls -la ~/.vimrc
# 检查文件权限
chmod 644 ~/.vimrc
# 重新加载配置
vim -u ~/.vimrc
问题 2:插件冲突
" 暂时禁用插件测试
" 在配置文件中注释掉插件行
" Plug 'some/plugin'
" 重新加载配置
:source ~/.vimrc
问题 3:性能问题
" 检查启动时间
vim --startuptime startup.log
" 查看日志分析
cat startup.log | sort -k2 -nr | head -20
最佳实践
1. 渐进式配置
- 从基础配置开始
- 逐步添加需要的功能
- 定期清理不需要的配置
2. 文档化
- 为重要配置添加注释
- 记录配置变更原因
- 分享配置经验
3. 备份和同步
- 定期备份配置文件
- 使用版本控制系统
- 在多台机器间同步配置
一个好的 Vim 配置可以显著提高编辑效率。建议从基础配置开始,根据实际需求逐步添加功能,形成适合自己的个性化配置。