Skip to main content

Vim Editor - Complete Guide

A comprehensive guide to Vim, the powerful modal text editor that's available on virtually every Unix-like system and is beloved by developers for its efficiency and extensibility.

What is Vim?​

Vim (Vi IMproved) is a highly configurable text editor built to enable efficient text editing. It's an improved version of the vi editor distributed with most UNIX systems.

Key Characteristics:

  • Modal Editor: Different modes for different operations (Normal, Insert, Visual, Command)
  • Keyboard-Driven: Designed for touch-typing efficiency
  • Extensible: Rich plugin ecosystem and customization options
  • Ubiquitous: Available on virtually every system
  • Lightweight: Fast and resource-efficient

Vim Modes​

Vim operates in different modes, each serving a specific purpose:

1. Normal Mode (Default)​

  • Purpose: Navigation, commands, and text manipulation
  • Enter: Default mode when Vim starts
  • Exit: Press i, a, o, v, V, Ctrl+v, or : to enter other modes

2. Insert Mode​

  • Purpose: Typing and editing text
  • Enter: Press i, a, o, O, s, S, c, C
  • Exit: Press Esc to return to Normal mode

3. Visual Mode​

  • Purpose: Selecting text for operations
  • Enter: Press v (character-wise), V (line-wise), or Ctrl+v (block-wise)
  • Exit: Press Esc to return to Normal mode

4. Command Mode​

  • Purpose: Executing commands, saving, quitting, etc.
  • Enter: Press : in Normal mode
  • Exit: Press Esc or Enter to execute command

Basic Navigation​

Cursor Movement (Normal Mode)​

# Basic movement
h, j, k, l # Left, Down, Up, Right
w, b # Next/Previous word
W, B # Next/Previous WORD (ignores punctuation)
e, ge # End of word, End of previous word
0, $ # Beginning/End of line
^, g_ # First/Last non-blank character of line
gg, G # Beginning/End of file
:n # Go to line number n

Screen Movement​

# Screen navigation
Ctrl+f, Ctrl+b # Page down/up
Ctrl+d, Ctrl+u # Half page down/up
Ctrl+e, Ctrl+y # Scroll down/up one line
H, M, L # Top/Middle/Bottom of screen
zt, zz, zb # Current line to top/center/bottom of screen

Search and Jump​

# Search
/pattern # Search forward for pattern
?pattern # Search backward for pattern
n, N # Next/Previous search result
* # Search for word under cursor
# # Search backward for word under cursor

# Jump to marks
m[a-z] # Set mark [a-z] at current position
'a, 'b # Jump to mark a, b
:marks # List all marks

Text Editing Commands​

Inserting Text​

# Insert commands
i # Insert before cursor
a # Insert after cursor
I # Insert at beginning of line
A # Insert at end of line
o # Open new line below
O # Open new line above
s # Substitute character under cursor
S # Substitute entire line

Deleting Text​

# Delete commands
x # Delete character under cursor
X # Delete character before cursor
dd # Delete entire line
dw # Delete word
d$ # Delete to end of line
d0 # Delete to beginning of line
dgg # Delete to beginning of file
dG # Delete to end of file

Copying and Pasting​

# Yank (copy) commands
yy # Yank entire line
yw # Yank word
y$ # Yank to end of line
y0 # Yank to beginning of line
ygg # Yank to beginning of file
yG # Yank to end of file

# Paste commands
p # Paste after cursor
P # Paste before cursor

Changing Text​

# Change commands
cw # Change word
c$ # Change to end of line
c0 # Change to beginning of line
cc # Change entire line
C # Change to end of line (same as c$)

Visual Mode Operations​

Selecting Text​

# Visual mode selection
v # Character-wise visual mode
V # Line-wise visual mode
Ctrl+v # Block-wise visual mode

# Selection commands
aw # Select a word
aW # Select a WORD
ap # Select a paragraph
ab # Select a block (parentheses)
aB # Select a block (braces)

Visual Mode Operations​

# After selecting text in visual mode
d # Delete selection
y # Yank (copy) selection
c # Change selection
> # Indent selection
< # Unindent selection
~ # Toggle case
u # Convert to lowercase
U # Convert to uppercase

Advanced Editing​

Find and Replace​

# Substitute command
:s/old/new/ # Replace first occurrence on current line
:s/old/new/g # Replace all occurrences on current line
:%s/old/new/g # Replace all occurrences in entire file
:%s/old/new/gc # Replace with confirmation
:%s/old/new/gi # Replace case-insensitive

# Examples
:%s/foo/bar/g # Replace all 'foo' with 'bar'
:%s/\s\+$// # Remove trailing whitespace
:%s/^/\t/ # Add tab to beginning of each line

Multiple Files​

# Buffer commands
:ls # List all buffers
:bnext, :bn # Next buffer
:bprev, :bp # Previous buffer
:bdelete, :bd # Delete buffer
:b [number] # Switch to buffer by number
:b [name] # Switch to buffer by name

# Window commands
:split # Split window horizontally
:vsplit # Split window vertically
Ctrl+w h/j/k/l # Navigate between windows
Ctrl+w +/- # Increase/decrease window height
Ctrl+w </> # Increase/decrease window width

Macros​

# Recording macros
q[a-z] # Start recording macro to register [a-z]
q # Stop recording

# Playing macros
@[a-z] # Play macro from register [a-z]
@@ # Repeat last played macro

File Operations​

Opening and Saving​

# File operations
:e filename # Edit file
:new filename # Create new file
:w # Save current file
:w filename # Save as filename
:wq, :x # Save and quit
:q # Quit (if no changes)
:q! # Quit without saving
:qa # Quit all windows
:qa! # Quit all windows without saving

File Navigation​

# File explorer
:Ex # Open file explorer
:Vex # Open file explorer in vertical split
:Sex # Open file explorer in horizontal split

# Netrw commands (in file explorer)
<Enter> # Open file/directory
- # Go to parent directory
d # Create directory
% # Create new file
D # Delete file/directory
R # Rename file/directory

Configuration and Customization​

Vim Configuration File​

Create or edit ~/.vimrc (Unix/Linux) or _vimrc (Windows):

" Basic settings
set number " Show line numbers
set relativenumber " Show relative line numbers
set autoindent " Auto-indent new lines
set smartindent " Smart auto-indent
set expandtab " Use spaces instead of tabs
set tabstop=4 " Number of spaces per tab
set shiftwidth=4 " Number of spaces for auto-indent
set softtabstop=4 " Number of spaces for tab in insert mode

" Search settings
set ignorecase " Ignore case in search
set smartcase " Case-sensitive if uppercase in search
set hlsearch " Highlight search results
set incsearch " Incremental search

" Visual settings
set syntax=on " Enable syntax highlighting
set background=dark " Dark background
set cursorline " Highlight current line
set showmatch " Show matching brackets

" File settings
set fileencoding=utf-8
set encoding=utf-8
set fileformat=unix

" Key mappings
map <C-n> :bnext<CR>
map <C-p> :bprev<CR>
map <C-s> :w<CR>

Plugin Management​

# Install vim-plug
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

Add to your .vimrc:

" Plugin management
call plug#begin('~/.vim/plugged')

" Popular plugins
Plug 'scrooloose/nerdtree' " File explorer
Plug 'ctrlpvim/ctrlp.vim' " Fuzzy file finder
Plug 'vim-airline/vim-airline' " Status line
Plug 'vim-airline/vim-airline-themes'
Plug 'scrooloose/syntastic' " Syntax checking
Plug 'tpope/vim-fugitive' " Git integration
Plug 'airblade/vim-gitgutter' " Git diff in gutter
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim' " Fuzzy finder

call plug#end()

Then run :PlugInstall in Vim.


Advanced Features​

Registers​

# Using registers
"ayy " Yank line to register 'a'
"ap " Paste from register 'a'
:registers " Show all registers
"*yy " Yank to system clipboard
"*p " Paste from system clipboard

Marks​

# Setting marks
ma " Set mark 'a' at current position
mA " Set mark 'A' (global mark)
'a " Jump to mark 'a'
'A " Jump to global mark 'A'
:marks " List all marks

Folding​

# Folding commands
zf " Create fold
zo " Open fold
zc " Close fold
za " Toggle fold
zR " Open all folds
zM " Close all folds

Spell Checking​

# Spell checking
:set spell " Enable spell checking
:set nospell " Disable spell checking
]s " Next misspelled word
[s " Previous misspelled word
zg " Add word to dictionary
zw " Remove word from dictionary
z= " Show spelling suggestions

Vim vs Neovim​

Neovim is a modern fork of Vim that aims to improve extensibility and maintainability:

Key Differences​

FeatureVimNeovim
Lua SupportLimitedFull Lua scripting
LSP SupportPlugin requiredBuilt-in
TerminalPlugin requiredBuilt-in
AsyncLimitedFull async support
Plugin APIVimscriptLua + Vimscript
PerformanceGoodBetter

Migration​

# Install Neovim
# Ubuntu/Debian
sudo apt install neovim

# macOS
brew install neovim

# Windows
choco install neovim

Create ~/.config/nvim/init.vim:

" Neovim configuration
set runtimepath^=~/.vim runtimepath+=~/.vim/after
let &packpath = &runtimepath
source ~/.vimrc

Productivity Tips​

1. Learn the Language​

Think of Vim commands as a language:

  • Verbs: d (delete), y (yank), c (change)
  • Nouns: w (word), s (sentence), p (paragraph)
  • Modifiers: i (inside), a (around), t (till)

2. Use Text Objects​

# Text objects
diw " Delete inside word
daw " Delete around word
ci" " Change inside quotes
da( " Delete around parentheses

3. Leverage the Dot Command​

The . command repeats the last change, making it incredibly powerful for repetitive edits.

4. Use Marks for Navigation​

Set marks at important locations to quickly jump between them.

5. Master Visual Mode​

Visual mode is powerful for selecting and operating on text blocks.


Common Workflows​

1. Code Editing​

# Navigate and edit
gg " Go to top
/function " Search for function
ciw " Change inside word
:w " Save

2. Multiple Files​

# Work with multiple files
:e file1.js " Edit file1.js
:split file2.js " Split and edit file2.js
Ctrl+w h/j/k/l " Navigate between windows

3. Search and Replace​

# Find and replace
:%s/old/new/gc " Replace with confirmation
:%s/\s\+$// " Remove trailing whitespace
:%s/^/\t/ " Add indentation

Troubleshooting​

Common Issues​

  1. Stuck in Insert Mode

    • Press Esc multiple times
    • Press Ctrl+[
  2. Can't Exit Vim

    • Press Esc then :q! to quit without saving
    • Press Esc then :wq to save and quit
  3. Undo/Redo Issues

    • Use u to undo
    • Use Ctrl+r to redo
  4. Search Not Working

    • Check if you're in the right mode
    • Use / to search forward, ? to search backward

Getting Help​

# Help commands
:help " General help
:help [topic] " Help on specific topic
:help user-manual " User manual
:help quickref " Quick reference

Conclusion​

Vim is a powerful editor that rewards investment in learning. Start with the basics (modes, navigation, basic editing) and gradually incorporate more advanced features. The key to Vim mastery is practice and understanding that it's designed for efficiency through keyboard-driven operations.

Remember: Vim has a steep learning curve, but the productivity gains are substantial once you become proficient. Focus on learning the language of Vim commands rather than memorizing individual keystrokes.


This guide covers the fundamentals of Vim. For more advanced topics, explore plugins, scripting, and Neovim-specific features.