Of course! Here is a comprehensive guide to creating a powerful and feature-rich .vimrc file for Python development on Ubuntu. This guide covers everything from the basic setup to advanced features like linting, autocompletion, and debugging.

We'll build the configuration progressively, from a simple starter to a full-featured professional setup.
Part 1: The Goal - What We Want in a Python .vimrc
A great Python development environment in Vim should provide:
- Syntax Highlighting & Indentation: Correct Python syntax and consistent indentation.
- Code Navigation: Quickly jump to definitions of functions and classes.
- Autocompletion: Intelligent code completion based on context.
- Linting & Static Analysis: Catch errors and style issues (PEP8) in real-time.
- Code Formatting: Automatically format code to be clean and consistent.
- Virtual Environment Support: Work seamlessly with
venvorconda. - Run Code: Easily run Python scripts and see output.
- Visual Enhancements: A clean, modern look with a status line.
Part 2: Prerequisites - Installing Dependencies
Before we configure Vim, we need to install the command-line tools it will rely on. Open your terminal and run the following commands.
Install Python Tools
These are essential for linting, formatting, and language server support.

# Install linters and formatters sudo apt update sudo apt install python3-pip python3-venv # Install linters and formatters via pip pip3 install --user pycodestyle # For PEP8 style checking pip3 install --user autopep8 # For auto-formatting pip3 install --user yapf # Another excellent formatter pip3 install --user flake8 # A popular linter pip3 install --user black # An opinionated code formatter
Install a Language Server (The Modern Way)
For the best autocompletion and code intelligence, we'll use Language Server Protocol (LSP). pylsp is a great, lightweight choice.
pip3 install --user python-lsp-server
Install Required Vim Plugins
We will use vim-plug to manage our plugins. If you don't have it, install it first.
# Download vim-plug
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
Part 3: The .vimrc File - From Basic to Advanced
Now, let's create the .vimrc file. Open it in Vim:
vim ~/.vimrc
You can delete any existing content and paste the sections below. We'll build it step-by-step.
Section A: Basic Settings & UI
This section improves the general look and feel of Vim.
" === Basic Settings === " Set encoding to UTF-8 set encoding=utf-8 " Use the system clipboard set clipboard=unnamedplus " Show line numbers set number " Highlight the current line set cursorline " Highlight searches set hlsearch " Case-insensitive search set ignorecase " But be case-sensitive if search term contains uppercase set smartcase " Don't wrap lines set nowrap " Better command-line completion set wildmenu " Enable mouse support set mouse=a " Don't create swap files or backup files set noswapfile set nobackup set undofile " Store undo history in a file set undodir=~/.vim/undodir " Keep a command line history set history=1000 " === UI Enhancements === " Use a dark theme (you can change this to your liking) colorscheme desert " Show a status line at the bottom set laststatus=2 " Show a column at 80 characters for PEP8 compliance set colorcolumn=80
Section B: Plugin Management (vim-plug)
This section tells vim-plug where to find and manage our plugins.
" === Plugin Management ===
" Specify a directory for plugins
call plug#begin('~/.vim/plugged')
" List of plugins will go here
" ... (plugins from Section C will be added here)
" Initialize plugin system
call plug#end()
Section C: Essential Plugins for Python
Add these plugin definitions inside the call plug#begin(...) and call plug#end() block.
" === Core Plugins ===
" A modern auto-pairs for brackets and quotes
Plug 'jiangmiao/auto-pairs'
" A file explorer
Plug 'preservim/nerdtree', { 'on': 'NERDTreeToggle' }
" A fuzzy finder for files, buffers, etc.
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
" === Language Server & Autocompletion ===
" LSP client for Vim
Plug 'neoclide/coc.nvim', {'branch': 'release'}
" === Python-Specific Plugins ===
" Python syntax highlighting and indentation
Plug 'vim-python/python-syntax'
" Run Python code in a REPL
Plug 'tpope/vim-dispatch'
Section D: Plugin-Specific Configuration
This section configures the behavior of the plugins we just added.
" === Plugin Configuration ===
" --- NERDTree ---
" Open NERDTree automatically when no file is specified
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 0 && !exists('s:std_in') | NERDTree | endif
" Close NERDTree if it's the only window left
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif
" Map <leader>n to toggle NERDTree
nnoremap <leader>n :NERDTreeToggle<CR>
" --- FZF ---
" Use ripgrep (rg) for searching, which is much faster
" Install it with: sudo apt install ripgrep
set grepprg=rg\ --vimgrep\ --smart-case\ --follow
nnoremap <leader>f :Files<CR>
nnoremap <leader>b :Buffers<CR>
" --- coc.nvim (LSP & Autocompletion) ---
" Use tab for trigger completion with characters ahead and navigate
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugins before putting this into your config.
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
" <C-g>u breaks current undo, please don't use it.
inoremap <silent><expr> <CR> coc#pum#visible() ? coc#confirm() : "\<CR>"
" Use `[g` and `]g` to navigate diagnostics
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)
" GoTo code navigation
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" Symbol renaming
nmap <leader>rn <Plug>(coc-rename)
" Formatting selected code
xmap <leader>f <Plug>(coc-format-selected)
nmap <leader>f <Plug>(coc-format-selected)
" Add (Neo)Vim's native statusline support
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}
" --- Python Syntax ---
let g:python_highlight_all = 1
Note: The coc.nvim configuration is extensive. It provides LSP-powered features like GoTo Definition (gd), Find References (gr), and autocompletion.
Section E: Python-Specific Mappings
This section defines custom key bindings to make Python development easier.
" === Python-Specific Mappings === " Run the current Python file nnoremap <leader>r :w! | !python3 %<CR> " Open a Python REPL in a vertical split nnoremap <leader>py :vsplit term://python3<CR> " Format the current file using 'black' nnoremap <leader>bf :w !black -<CR> " Format the current file using 'autopep8' nnoremap <leader>af :w !autopep8 --in-place --aggressive --range %:2 %:2 %<CR>
Part 4: The Complete .vimrc File
Here is the final, consolidated .vimrc file. You can copy and paste this entire block into your ~/.vimrc file.
" =====================================================================
" === Basic Settings & UI =============================================
" =====================================================================
" Set encoding to UTF-8
set encoding=utf-8
" Use the system clipboard
set clipboard=unnamedplus
" Show line numbers
set number
" Highlight the current line
set cursorline
" Highlight searches
set hlsearch
" Case-insensitive search
set ignorecase
" But be case-sensitive if search term contains uppercase
set smartcase
" Don't wrap lines
set nowrap
" Better command-line completion
set wildmenu
" Enable mouse support
set mouse=a
" Don't create swap files or backup files
set noswapfile
set nobackup
set undofile
" Store undo history in a file
set undodir=~/.vim/undodir
" Keep a command line history
set history=1000
" UI Enhancements
colorscheme desert
set laststatus=2
set colorcolumn=80
" =====================================================================
" === Plugin Management (vim-plug) ====================================
" =====================================================================
" Specify a directory for plugins
call plug#begin('~/.vim/plugged')
" --- Core Plugins ---
" A modern auto-pairs for brackets and quotes
Plug 'jiangmiao/auto-pairs'
" A file explorer
Plug 'preservim/nerdtree', { 'on': 'NERDTreeToggle' }
" A fuzzy finder for files, buffers, etc.
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
" --- Language Server & Autocompletion ---
" LSP client for Vim
Plug 'neoclide/coc.nvim', {'branch': 'release'}
" --- Python-Specific Plugins ---
" Python syntax highlighting and indentation
Plug 'vim-python/python-syntax'
" Run Python code in a REPL
Plug 'tpope/vim-dispatch'
" Initialize plugin system
call plug#end()
" =====================================================================
" === Plugin Configuration ============================================
" =====================================================================
" --- NERDTree ---
" Open NERDTree automatically when no file is specified
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * if argc() == 0 && !exists('s:std_in') | NERDTree | endif
" Close NERDTree if it's the only window left
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif
" Map <leader>n to toggle NERDTree
nnoremap <leader>n :NERDTreeToggle<CR>
" --- FZF ---
" Use ripgrep (rg) for searching, which is much faster
" Install it with: sudo apt install ripgrep
set grepprg=rg\ --vimgrep\ --smart-case\ --follow
nnoremap <leader>f :Files<CR>
nnoremap <leader>b :Buffers<CR>
" --- coc.nvim (LSP & Autocompletion) ---
" 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#confirm() : "\<CR>"
" Use `[g` and `]g` to navigate diagnostics
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)
" GoTo code navigation
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" Symbol renaming
nmap <leader>rn <Plug>(coc-rename)
" Formatting selected code
xmap <leader>f <Plug>(coc-format-selected)
nmap <leader>f <Plug>(coc-format-selected)
" Add (Neo)Vim's native statusline support
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}
" --- Python Syntax ---
let g:python_highlight_all = 1
" =====================================================================
" === Python-Specific Mappings ========================================
" =====================================================================
" Run the current Python file
nnoremap <leader>r :w! | !python3 %<CR>
" Open a Python REPL in a vertical split
nnoremap <leader>py :vsplit term://python3<CR>
" Format the current file using 'black'
nnoremap <leader>bf :w !black -<CR>
" Format the current file using 'autopep8'
nnoremap <leader>af :w !autopep8 --in-place --aggressive --range %:2 %:2 %<CR>
Part 5: Installation and First Use
-
Save and Quit: In Vim, press
Escand then typewqto save and quit the.vimrcfile. -
Install Plugins: Open Vim and run the command:
:PlugInstall
This will read your
.vimrc, find all thePlugcommands, and download the plugins into~/.vim/plugged. -
Install Language Server Extensions: coc.nvim needs extensions to provide language features for Python. Run this command in Vim:
:CocInstall coc-pylsp
You can also install other extensions like
coc-flake8for more linting, butcoc-pylspis a great starting point as it includes many features. -
Activate a Virtual Environment (Crucial Step!) coc.nvim and the LSP run in a separate Python environment. To make sure they use the right packages (like
pylsp), you must tell it which Python interpreter to use.- Activate your venv in your terminal as you normally would:
source /path/to/your/venv/bin/activate
- Tell coc.nvim to use the interpreter from this venv:
:CocCommand python.setInterpreter
This will open a list of available Python interpreters. Select the one inside your virtual environment (e.g.,
/path/to/your/venv/bin/python3).
- Activate your venv in your terminal as you normally would:
Part 6: How to Use Your New Setup
| Feature | How to Use It |
|---|---|
| File Navigation | Files (or <leader>f) to fuzzy find files. Buffers (or <leader>b) to find open buffers. |
| Code Autocompletion | Start typing a function or class name and press Tab to see suggestions. Enter to select one. |
| Go to Definition | Place your cursor on a function/class and press gd. |
| Find References | Place your cursor on a name and press gr. |
| See Errors | coc.nvim will show squiggly lines under errors. Press ]g to go to the next error. |
| Run Python Script | Press <leader>r in normal mode. This will save the file and run it in your terminal. |
| Open a Python REPL | Press <leader>py to open a Python interpreter in a vertical split. |
| Format Code | Press <leader>bf to format the current file with black, or <leader>af for autopep8. |
| Toggle File Explorer | Press <leader>n to open/close NERDTree. |
You now have a highly capable, modern Python development environment right inside Vim on Ubuntu! You can customize it further by changing the colorscheme, adding more plugins, or tweaking the mappings to fit your workflow.
