Vim 编写 Python 优化指南

1. 缩进优化

Python 依赖缩进定义代码块,Vim 可通过以下配置提升体验:

" 基础设置
autocmd FileType python setlocal expandtab     " 将 Tab 转为空格
autocmd FileType python setlocal tabstop=4      " Tab 显示宽度
autocmd FileType python setlocal shiftwidth=4   " 自动缩进宽度
autocmd FileType python setlocal softtabstop=4  " 退格删除缩进

" 增强插件(需安装)
Plug 'vim-scripts/indentpython.vim'  " PEP8 智能缩进
Plug 'hynek/vim-python-pep8-indent' " 函数参数对齐

操作技巧

  • >> / <<:单行缩进调整
  • =i{:快速缩进当前代码块
  • gg=G:全局重缩进整个文件

2. 函数跳转
原生方案
" 使用标签系统
:!ctags -R .  " 生成标签
Ctrl+]         " 跳转到定义
Ctrl+t         " 返回跳转前位置

插件方案(推荐)
" LSP 支持(需安装)
Plug 'prabirshrestha/vim-lsp'
Plug 'mattn/vim-lsp-settings'

" 配置 Python LSP
let g:lsp_settings = {
\  'pylsp': {
\    'cmd': ['pylsp']
\  }
\}

" 快捷键映射
nnoremap gd :LspDefinition<CR>    " 跳转定义
nnoremap gr :LspReferences<CR>     " 查看引用


3. 代码注释
原生方法
" 行注释
:3,5s/^/#/g    " 注释 3-5 行
:3,5s/^#//g    " 取消注释

" 块注释(可视化模式)
Ctrl+v → 选中行 → I# → Esc

高效插件
" NERD Commenter(需安装)
Plug 'preservim/nerdcommenter'

" 快捷键
<leader>cc   " 注释当前行/选区
<leader>cu   " 取消注释
<leader>c<space> " 切换注释状态


完整配置示例(.vimrc)
" === Python 专用设置 ===
augroup python_config
  autocmd!
  autocmd FileType python setlocal expandtab tabstop=4 shiftwidth=4
  autocmd FileType python nnoremap <buffer> <leader>r :!python %<CR>
augroup END

" === 插件初始化 ===
call plug#begin()
Plug 'preservim/nerdcommenter'
Plug 'prabirshrestha/vim-lsp'
Plug 'mattn/vim-lsp-settings'
call plug#end()

" === LSP 配置 ===
let g:lsp_settings = {'pylsp': {'cmd': ['pylsp']}}

最佳实践

  1. 使用 :set list 显示空白字符避免缩进错误
  2. 结合 :set number 显示行号快速定位
  3. 定期运行 :py3compile % 检查语法
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐