Complete Vim Editor Tutorial with Usage Examples
1. What is Vim?
Vim (Vi IMproved) is a highly configurable, powerful, and efficient text editor that runs in the command-line interface (CLI) and as a standalone graphical user interface (GUI). It's a modal editor, meaning it operates in different "modes," each with specific functionalities. Vim is widely used by programmers, system administrators, and anyone who needs to edit text files quickly and efficiently, especially on Linux/Unix-like systems.
Why Learn Vim?
- Efficiency: Once mastered, Vim allows for incredibly fast text editing with minimal keystrokes, as you spend less time reaching for the mouse.
- Ubiquity: Vim (or its predecessor Vi) is available on virtually every Unix-like system by default.
- Power & Customization: Extremely flexible with extensive configuration options and a rich plugin ecosystem.
- Keyboard-Centric: Encourages staying on the keyboard, leading to improved workflow and reduced wrist strain.
2. Installing Vim
Vim is often pre-installed on Linux and macOS. If not, you can easily install it.
To start Vim and open a file:
vim my_file.txt
If the file doesn't exist, Vim will create it when you save.
3. Vim Modes
Vim's core concept is its modal nature. You're always in one of several modes. Switching between them is key to efficiency.
- Normal Mode (Command Mode):
- This is the default mode when you open Vim.
- Used for navigation (moving cursor), deleting text, copying (yanking), pasting (putting), and executing commands.
- You cannot type text directly in this mode.
- Press Esc to return to Normal Mode from any other mode.
- Insert Mode:
- Used for typing and editing text, similar to a standard text editor.
- Enter Insert Mode from Normal Mode by pressing `i`, `a`, `o`, `I`, `A`, `O`, etc.
- Press Esc to exit Insert Mode and return to Normal Mode.
- Visual Mode:
- Used for selecting text blocks. Once selected, you can perform operations like copying, cutting, or deleting on the selected block.
- Enter Visual Mode from Normal Mode by pressing `v` (character-wise), `V` (line-wise), or Ctrl + v (block-wise).
- Press Esc to exit Visual Mode.
- Command-Line Mode (Ex Mode):
- Used for executing commands that affect the entire file or interact with Vim's settings.
- Enter Command-Line Mode from Normal Mode by pressing `:` (colon).
- After typing a command, press Enter to execute it.
- Commands like saving, quitting, search/replace are done here.
4. Basic Navigation (Normal Mode)
Moving around in Vim without the arrow keys is fundamental.
5. Insert Mode
This is where you type actual text. You enter Insert Mode from Normal Mode using specific commands:
- i: Insert text before the cursor.
- a: Insert text after the cursor.
- o: Insert a new line below the current line and enter Insert Mode.
- I: Insert text at the beginning of the current line.
- A: Insert text at the end of the current line.
- O: Insert a new line above the current line and enter Insert Mode.
- s: Delete character under cursor and enter Insert Mode.
- S: Delete current line and enter Insert Mode.
To exit Insert Mode and return to Normal Mode: Press Esc.
6. Saving and Exiting (Command-Line Mode)
You need to be in Command-Line Mode (press `:` from Normal Mode) to perform these actions.
- :w: Save the current file.
- :w filename: Save the file as `filename`.
- :q: Quit Vim (only if there are no unsaved changes).
- :wq: Save and quit. (Also ZZ in Normal Mode for current file only).
- :x: Save and quit (only writes if changes were made).
- :q!: Quit without saving changes (force quit).
- :wq!: Save and quit, even if the file is read-only (if you have permission).
7. Basic Editing Commands (Normal Mode)
These commands perform actions on text.
- Delete:
- x: Delete character under the cursor.
- dw: Delete from cursor to the end of the word.
- d$: Delete from cursor to the end of the line.
- dd: Delete the entire current line.
- dG: Delete from current line to the end of the file.
- dgg: Delete from current line to the beginning of the file.
- Change (Delete & Insert):
- cw: Change word (delete to end of word, then enter Insert Mode).
- c$: Change to end of line (delete to end of line, then enter Insert Mode).
- cc: Change line (delete current line, then enter Insert Mode).
- C: Same as `c$`.
- Replace (single character):
- r: Replace single character under cursor. (e.g., `ra` replaces char with 'a'). Does not enter Insert Mode.
- R: Enter Replace Mode (overwrites characters until Esc is pressed).
Combining Commands: Vim commands often follow a `[number][command][motion]` pattern.
5dd # Delete 5 lines
3dw # Delete 3 words
d2w # Delete 2 words (same as 2dw)
c3w # Change 3 words
dG # Delete from current line to the end of the file
8. Copy, Paste, Delete (Yank, Put, Delete)
Vim uses different terms for these operations, often interacting with registers.
9. Searching and Replacing (Command-Line Mode)
Powerful features for navigating and modifying text.
- Searching:
- /pattern: Search forward for `pattern`. Press n for next match, N for previous.
- ?pattern: Search backward for `pattern`. Press n for next (backward) match, N for previous (forward).
- *: Search for the word under the cursor, forward.
- #: Search for the word under the cursor, backward.
- Replacing: (Uses `:s` for substitute command)
- :%s/old/new/: Replace first occurrence of `old` with `new` on each line.
- :%s/old/new/g: Replace ALL occurrences of `old` with `new` on each line (`g` for global).
- :%s/old/new/gc: Replace ALL occurrences, with confirmation for each (`c` for confirm).
- :start_line,end_line s/old/new/g: Replace in a specific range of lines. (e.g., `1,10s/error/bug/g` replaces in lines 1 to 10).
10. Undo and Redo (Normal Mode)
- u: Undo the last change.
- Ctrl + r: Redo the last undone change.
- . (dot): Repeat the last change/command. Extremely powerful for repetitive tasks.
11. Advanced Navigation (Normal Mode)
- Jumping between lines/paragraphs:
- {: Move to the previous paragraph.
- }: Move to the next paragraph.
- Jumping between matching brackets/parentheses:
- %: Jump between matching `()`, `[]`, `{}`.
- Marks: Set custom markers in your file.
- ma: Set mark `a` at current cursor position.
- `a: Jump to the exact position of mark `a`.
- 'a: Jump to the beginning of the line containing mark `a`.
- Jumplists: Vim keeps a history of cursor positions.
- Ctrl + o: Jump to older position in jumplist.
- Ctrl + i: Jump to newer position in jumplist.
12. Multiple Files & Windows
Vim can efficiently manage multiple files and split its view.
- Buffers (Open Files):
- :e filename: Open `filename` in the current window.
- :bn: Go to next buffer.
- :bp: Go to previous buffer.
- :ls: List all open buffers.
- :b number: Go to buffer by its number (from `:ls`).
- :bd: Close current buffer.
- Splitting Windows: Divide the Vim window into multiple panes.
- :sp: Split horizontally, opening a new buffer (or current buffer if no filename).
- :vsp: Split vertically.
- :sp filename: Split horizontally and open `filename`.
- :vsp filename: Split vertically and open `filename`.
- Ctrl + w w: Move cursor to the next window.
- Ctrl + w h/j/k/l: Move cursor to left/down/up/right window.
- Ctrl + w q: Close current window.
- Tabs: Manage multiple layouts of windows.
- :tabnew: Create a new tab.
- :tabnew filename: Create a new tab and open `filename`.
- gt: Go to next tab.
- gT: Go to previous tab.
- :tabc: Close current tab.
- :tabo: Close all other tabs.
13. Visual Mode
Used for selecting text, then performing an operation on the selection.
- v: Character-wise visual mode. Select characters using navigation keys.
- V: Line-wise visual mode. Select whole lines.
- Ctrl + v: Block-wise visual mode. Select a rectangular block of text.
- Once selected:
- y: Yank (copy) the selection.
- d: Delete the selection.
- c: Change (delete) the selection and enter Insert Mode.
- ~: Change case of selected characters.
- Example:
# Go to start of text
vwwyw # Select two words character-wise and yank them
:s/pattern/replacement/g # Select lines with V, then replace
Ctrl-v 3j I # Select a block, then insert text at the beginning of each selected line.
# (Ctrl-v to enter block mode, 3j to extend selection 3 lines down, I (capital I) to insert at beginning of block, type text, then Esc)
14. Macros
Record a sequence of keystrokes and play them back, automating repetitive tasks.
- qregister: Start recording a macro into a specific register (e.g., `qa` for register 'a').
- Perform your sequence of commands.
- q: Stop recording.
- @register: Play back the macro once (e.g., `@a`).
- number@register: Play back the macro `number` of times (e.g., `5@a`).
- @@: Play back the last executed macro again.
# Example: Add a semicolon and then a comment "// END" to the end of 5 lines
qa # Start recording into register 'a'
$ # Go to end of line
a # Enter Insert mode after cursor
; // END # Type the text
<Esc> # Exit Insert mode
j # Go to next line
q # Stop recording
# Now, execute 4 more times (total 5 lines modified)
4@a
15. .vimrc Configuration
The `.vimrc` file (located in your home directory `~/.vimrc` on Linux/macOS, or `_vimrc` in Vim installation directory on Windows) is where you customize Vim's behavior, appearance, and key bindings.
- Open/Create `.vimrc`:
vim ~/.vimrc
- Common Settings:
" Basic settings
set nocompatible " Behave like Vim, not Vi
set autoindent " Auto indent new lines
set smartindent " Smart auto-indent for programming
set tabstop=4 " Number of spaces a <Tab> in the file counts for
set shiftwidth=4 " Number of spaces to use for autoindenting
set expandtab " Use spaces instead of tabs
" User Interface
set number " Show line numbers
set relativenumber " Show relative line numbers (useful for motions)
set wrap " Wrap long lines
set incsearch " Incremental search
set hlsearch " Highlight all matches for search pattern
set ignorecase " Ignore case in search patterns
set smartcase " Overrides ignorecase if pattern contains uppercase
" Status line
set showcmd " Show incomplete commands
set showmode " Show current mode
set laststatus=2 " Always show the status line
" Visual customization
syntax on " Enable syntax highlighting
colorscheme default " Set a color scheme (e.g., dracula, gruvbox)
set mouse=a " Enable mouse support in all modes
- Reload `.vimrc`: After making changes, save the file and then source it in Vim:
:source ~/.vimrc
16. Plugins
Vim's functionality can be greatly extended with plugins, adding features like file explorers, fuzzy finders, auto-completion, and advanced syntax highlighting.
Popular Plugin Managers:
- Vim-plug: Lightweight and easy to use.
" In your ~/.vimrc
call plug#begin('~/.vim/plugged') " Directory where plugins will be installed
" Plugins
Plug 'VundleVim/Vundle.vim' " Example: A different plugin manager
Plug 'tpope/vim-fugitive' " Git wrapper
Plug 'vim-airline/vim-airline' " Lean & mean status/tabline
Plug 'scrooloose/nerdtree' " File explorer
call plug#end()
Installation: Follow Vim-plug's instructions to install `plug.vim`. Then, in Vim, run `:PlugInstall` to download and install plugins.
- Vundle: Another popular option.
Examples of Popular Plugins:
- NerdTree: A file system explorer. (Use `:NERDTree` to open).
- Vim-Airline: A customizable status line for Vim.
- Fugitive: A Git wrapper, allowing Git commands directly from Vim.
- CtrlP: A fuzzy file finder.
- YouCompleteMe (YCM): A fast, as-you-type code completion engine.
17. The vimtutor
Vim comes with an excellent built-in interactive tutorial called `vimtutor`. It's highly recommended for beginners as it teaches the basic commands interactively.
vimtutor
Usage: Simply type `vimtutor` in your terminal and follow the instructions. It takes about 25-30 minutes to complete and covers many of the fundamental concepts discussed here.
The Learning Curve:
Vim has a steep learning curve initially because its modal nature and keyboard-centric commands are very different from traditional editors. However, with consistent practice, these commands become muscle memory, and you'll find yourself editing text with unparalleled speed and precision. Start with the basics, practice daily, and gradually explore more advanced features and plugins. Happy Vimming!