杰瑞科技汇

vim python plugin

Of course! Vim's support for Python is incredibly powerful, ranging from basic syntax highlighting to full-fledged IDE-like functionality with plugins. Here’s a comprehensive guide covering everything from the built-in features to the most popular and essential plugins.


The Built-in Stuff (No Plugins Needed)

Before you install anything, make sure you're leveraging Vim's native capabilities.

  • Syntax Highlighting: This is automatic. Just open a .py file, and Vim will highlight keywords, strings, comments, etc.
  • Indentation: Python is sensitive to whitespace. Vim's default Python indenting is pretty good, but you can improve it.
    " In your .vimrc or init.vim
    filetype plugin indent on
    set autoindent
    set smartindent
    set expandtab " Use spaces instead of tabs
    set shiftwidth=4 " Set indentation width to 4 spaces
    set tabstop=4   " Visualize tabs as 4 spaces
  • Code Folding: Vim can fold code based on indentation, which is perfect for Python.
    • za: Toggle a fold at the cursor.
    • zM: Close all folds.
    • zR: Open all folds.
  • py and py3 Commands: You can execute Python code directly from Vim.
    • py print("Hello from Python 2") (if Vim is compiled with Python 2)
    • py3 print("Hello from Python 3") (if Vim is compiled with Python 3)
    • py3 import vim gives you access to the Vim API, allowing you to script Vim's behavior with Python.

The Essential Plugin Ecosystem (LSP + Completion)

The modern standard for powerful language support in Vim is the Language Server Protocol (LSP). An LSP server provides features like:

  • Intelligent Code Completion
  • Go to Definition
  • Find References
  • Hover for Documentation
  • Diagnostics (linting/warnings)

The most popular LSP client for Vim is coc.nvim. It's a powerhouse that integrates with a vast ecosystem of language servers.

The Recommended Workflow: coc.nvim + pylsp

Step 1: Install a Plugin Manager If you don't have one, install one. vim-plug is very popular.

" In your .vimrc
call plug#begin('~/.vim/plugged')
Plug 'neoclide/coc.nvim', {'branch': 'release'}
call plug#end()

Then run PlugInstall in Vim.

Step 2: Install the Python Language Server The best all-around Python LSP server is Python Language Server (pylsp). It's fast, actively maintained, and has many great plugins.

Install it in your system's Python environment (the one you use for development):

# Using pip (recommended)
pip install 'python-lsp-server[all]'
# Or using conda
conda install -c conda-forge python-lsp-server

Step 3: Configure coc.nvim for Python coc.nvim will automatically detect pylsp. You just need to enable it.

" In your .vimrc
" Use tab for trigger completion with characters ahead and navigate
inoremap <silent><expr> <TAB>
      \ coc#pum#visible() ? coc#pum#next(1) :
      \ CheckBackspace() ? "\<TAB>" :
      \ coc#refresh()
inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"
" Make <CR> to accept selected completion item or notify coc.nvim to format
inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm() : "\<CR>"
" Go to definition
nmap <silent> gd <Plug>(coc-definition)
" Find references
nmap <silent> gr <Plug>(coc-references)
" Hover documentation
nmap <silent> K <Plug>(coc-hover)
" Symbol renaming
nmap <silent> <leader>rn <Plug>(coc-rename)

Now, when you open a Python file, you get full IDE-like functionality. coc.nvim handles the UI, and pylsp does the heavy lifting.


Other Excellent Plugins

While coc.nvim is the core, these plugins add significant value.

A. Code Formatting

Prettier is the de-facto standard for code formatting, but for Python, a better choice is Black. It's an opinionated, no-config formatter.

  • Plugin: sbdchd/neoformat (older, simple) or integrate it directly into coc.nvim.
  • coc.nvim Method (Recommended): Install the coc-prettier extension and configure it to use Black.
    " Install the extension from coc menu
    :CocInstall coc-prettier

    Then add to your .vimrc:

    " Use Black for Python formatting
    let g:coc_global_extensions = ['coc-prettier']
    autocmd FileType python let b:coc_user_config = {
        \ 'prettier': {
        \   'parser': 'babel',
        \   'printWidth': 88,
        \   'singleQuote': v:false,
        \   'trailingComma': 'es5',
        \   'tabWidth': 4,
        \   'useTabs': v:false,
        \   'semi': v:false,
        \ }
        \ }
    " Note: Black's config might conflict with Prettier's. A simpler approach is
    " to run `black` manually on save with an autocmd.

    A more robust solution is to run black on save with a simple autocmd:

    autocmd BufWritePost *.py silent !black %

B. Running Code

  • Plugin: tpope/vim-dispatch
    • This is the gold standard for running tasks. It's a powerful asynchronous dispatcher.
    • Dispatch python % will run your current Python file in a background terminal.
    • It integrates beautifully with other tools like make and git.

C. Debugging

  • Plugin: sakhnik/nvim-gdb
    • This plugin provides an incredible debugging experience, similar to modern IDEs.
    • It splits your screen to show the GDB TUI (Terminal User Interface) alongside your code.
    • You can set breakpoints, inspect variables, and step through code directly from Vim.

D. Snippets

  • Plugin: SirVer/ultisnips + honza/vim-snippets
    • ultisnips is a powerful snippet engine. vim-snippets provides a huge collection of pre-written snippets for many languages, including Python.
    • Type a snippet trigger (e.g., def for a function definition) and press <Tab> to expand it.

A Complete .vimrc / init.vim Example

Here is a sample configuration putting it all together using coc.nvim as the foundation.

" === Plugin Manager (vim-plug) ===
call plug#begin('~/.vim/plugged')
" LSP Client for IDE features
Plug 'neoclide/coc.nvim', {'branch': 'release'}
" Asynchronous task runner
Plug 'tpope/vim-dispatch'
" Python debugger integration
Plug 'sakhnik/nvim-gdb'
" Snippet engine and collection
Plug 'SirVer/ultisnips'
Plug 'honza/vim-snippets'
" Optional: A better statusline
Plug 'itchyny/lightline.vim'
call plug#end()
" === General Settings ===
set number
set relativenumber
set hidden " Allow buffer switching without saving
set nowrap
set encoding=utf-8
set fileencoding=utf-8" Set the terminal title
set scrolloff=5 " Keep 5 lines of context when scrolling
" === Python-Specific Settings ===
autocmd FileType python setlocal expandtab shiftwidth=4 tabstop=4
" === coc.nvim Configuration ===
" Use tab for trigger completion with characters ahead and navigate
inoremap <silent><expr> <TAB>
      \ coc#pum#visible() ? coc#pum#next(1) :
      \ CheckBackspace() ? "\<TAB>" :
      \ coc#refresh()
inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"
" Make <CR> to accept selected completion item
inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm() : "\<CR>"
" Go to definition, etc.
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gr <Plug>(coc-references)
nmap <silent> K <Plug>(coc-hover)
nmap <silent> <leader>rn <Plug>(coc-rename)
" Format code on save with Black (requires black to be installed)
autocmd BufWritePost *.py silent !black %
" === Key Mappings ===
" Leader key
let mapleader = " "
" Quick-save
nnoremap <leader>w :w<CR>
" Open terminal
nnoremap <leader>t :vsplit term://bash<CR>
tnoremap <leader>t <C-\><C-n>:q<CR>
" Run Python file with Dispatch
nnoremap <leader>r :Dispatch python %<CR>

Summary of Choices

Goal Recommended Solution Why?
Modern IDE Features coc.nvim + pylsp Provides the best all-in-one experience: completion, go-to-def, hover, linting, etc.
Code Formatting Black (run via coc or on-save) Opinionated, consistent, and requires zero configuration. The community standard.
Running Code vim-dispatch Asynchronous, powerful, and integrates with other tools. The standard for running tasks in Vim.
Debugging nvim-gdb Provides a full-featured graphical debugger interface within Vim, rivaling standalone IDEs.
Snippets ultisnips + vim-snippets Powerful, flexible, and comes with a massive library of pre-built snippets for Python.

Start with coc.nvim and pylsp. This single combination will dramatically improve your Python development workflow in Vim. Then, add the other plugins as you find you need them.

分享:
扫描分享到社交APP
上一篇
下一篇