| 系統 | 命令 | 路徑 |
|---|---|---|
| RedHat/CentOS | vim /etc/vimrc | 全局配置 (需 root) |
| Ubuntu/Debian | sudo vim /etc/vim/vimrc | 全局配置 |
| 用戶級 (通用) | vim ~/.vimrc | 推薦,無需 root |
" 基礎設置
set nocompatible " 不兼容 vi 模式
set number " 顯示行號
set cursorline " 高亮當前行
set tabstop=4 " Tab 寬度 4 空格
set shiftwidth=4 " 縮進寬度
set expandtab " Tab 轉空格
set autoindent " 自動縮進
set smartindent " 智能縮進
set hlsearch " 高亮搜索
set incsearch " 增量搜索
set ignorecase " 搜索忽略大小寫
set smartcase " 含大寫則區分大小寫
set wrap " 自動換行
set fileencodings=utf-8,gbk " 文件編碼自動識別
syntax on " 語法高亮
filetype plugin indent on " 文件類型檢測與縮進
根據文件類型自動插入版權、作者、時間等信息。
" 文件頭模板
autocmd BufNewFile *.cpp,*.h,*.c,*.java exec ":call SetTitle()"
func SetTitle()
if &filetype == 'cpp' || &filetype == 'c' || &filetype == 'h'
call setline(1, "/*************************************************************************")
call append(line("."), " > File Name: ".expand("%"))
call append(line(".")+1, " > Author: YourName")
call append(line(".")+2, " > Mail: your@email.com")
call append(line(".")+3, " > Created Time: ".strftime("%Y-%m-%d %H:%M:%S"))
call append(line(".")+4, " ************************************************************************/")
call append(line(".")+5, "")
elseif &filetype == 'java'
call setline(1, "/**")
call append(line("."), " * @author YourName")
call append(line(".")+1, " * @date ".strftime("%Y-%m-%d"))
call append(line(".")+2, " */")
call append(line(".")+3, "")
endif
endfunc
效果:新建 test.cpp 時自動生成帶時間戳的文件頭。
" F4 編譯運行映射
map :call CompileRun()
func! CompileRun()
exec "w" " 先保存
if &filetype == 'c'
exec "!gcc % -o %< && ./%<"
elseif &filetype == 'cpp'
exec "!g++ % -o %< -std=c++11 && ./%<"
elseif &filetype == 'java'
exec "!javac % && java %<"
elseif &filetype == 'py'
exec "!python3 %"
elseif &filetype == 'sh'
exec "!bash %"
endif
endfunc
按 F4 即可自動保存、編譯、運行,並在 Vim 底部顯示輸出,按 Enter 返回編輯。
" 瀏覽器風格標籤頁
set showtabline=2
nnoremap :tabnew
nnoremap :tabclose
" 快速移動
nnoremap h
nnoremap j
nnoremap k
nnoremap l
" 取消高亮
nnoremap :nohlsearch
" 保存時自動格式化 (需安裝 clang-format/astyle)
" autocmd BufWritePre *.cpp,*.h,*.c,*.java :!clang-format -i %
:source % 重新加載。~/.vimrc 避免 root 權限問題。gcc/g++/javac/java 並在 PATH 中。set encoding=utf-8,終端編碼需一致。%< (不含擴展名文件名) 運行。這套配置輕量、通用、無插件依賴,適合大多數 Linux 開發場景,顯著提升編碼效率。