Vim Tutorial
Introduction
Vim is a highly configurable text editor that has been around for decades. It’s known for its steep learning curve, but once mastered, it can greatly improve your productivity and efficiency when working with text.
Vim Mode
1. Normal Mode
In Normal mode you can enter all the normal editor commands. If you start the editor you are in this mode (unless you have set the ‘insertmode’ option).
Here are some basic commands you can use in normal mode:
- Movement:
- Arrow keys (up, down, left, right)
- h (left)
- l (right)
- j (down)
- k (up)
- Insertion:
- i (insert text at the cursor)
- a (insert text after the cursor)
- A (start inserting text at the end of a line)
- I (insert text at the beginning of a line)
- o (insert a new row after the current row)
- O (insert a new row before the current row)
- Deletion:
- x (delete text at the cursor)
- X (delete text at the cursor and move left)
- Modification:
- r (replace text at the cursor)
- R (replace text at the cursor with a register)
- Copy and Paste:
- y (yank text to the clipboard)
- p (paste text from the clipboard after the current line)
- P (paste text from the clipboard before the current line)
- Other:
- . (repeat last command)
- $ (move to end of line)
- ^ (move to beginning of line)
These are just a few examples of the many commands you can use in normal mode. It’s important to practice and experiment with different commands to become proficient in using Vim.
2. Visual Mode
Pressing the ‘v’ key will take you into visual mode, where you can select text visually. You can also use the ‘V’ key to select text in a line, or the ‘<’ and ‘>’ keys to select text in a block.
Here are some basic commands you can use in visual mode:
- Selection:
- Use the arrow keys (up, down, left, right) to select text.
- Use ‘h’ (left), ’l’ (right), ‘j’ (down), and ‘k’ (up) to select text.
- Use ‘V’ (select line) or ‘v’ (select character) to select text.
- Deletion:
- Use ‘x’ (delete selected text) or ‘X’ (delete selected text and move left).
- Copy and Paste:
- Use ‘y’ (yank selected text to clipboard) or ‘Y’ (yank line to clipboard).
- Use ‘p’ (paste text from clipboard after current line) or ‘P’ (paste text from clipboard before current line).
- Other:
- Use ‘.’ (repeat last command).
- Use ‘G’ (move to end of file) or ‘gg’ (move to beginning of file).
- Use ‘^’ (move to beginning of line) or ‘%’ (move to ending of line).
It’s important to note that in visual mode, you can only select text that is visible on the screen. If you want to select text that is not visible on the screen, you need to move the cursor to that position first using the arrow keys or ‘h’, ’l’, ‘j’, and ‘k’ keys.
3. Select Mode
Select mode looks like Visual mode, but the commands accepted are quite different. This resembles the selection mode in Microsoft Windows. When the ‘showmode’ option is set, “– SELECT –” is shown in the last line.
Entering Select mode:
- Using the mouse to select an area, and ‘selectmode’ contains “mouse”. ‘mouse’ must also contain a flag for the current mode.
- Using a non-printable movement command, with the Shift key pressed, and
‘selectmode’ contains “key”. For example:
and . ‘keymodel’ must also contain “startsel”. - Using “v”, “V” or CTRL-V command, and ‘selectmode’ contains “cmd”.
- Using “gh”, “gH” or “g_CTRL-H” command in Normal mode.
- From Visual mode, press CTRL-G.
Here are some basic commands you can use in select mode:
-
Printable characters,
and cause the selection to be deleted, and Vim enters Insert mode. The typed character is inserted. -
Non-printable movement commands, with the Shift key pressed, extend the selection. ‘keymodel’ must include “startsel”.
-
Non-printable movement commands, with the Shift key NOT pressed, stop Select mode. ‘keymodel’ must include “stopsel”.
-
ESC stops Select mode.
-
CTRL-O switches to Visual mode for the duration of one command. v_CTRL-O
-
CTRL-G switches to Visual mode.
Otherwise, typed characters are handled as in Visual mode.
When using an operator in Select mode, and the selection is linewise, the selected lines are operated upon, but like in characterwise selection. For example, when a whole line is deleted, it can later be pasted halfway a line.
- Selection:
- Use the ‘/’ key followed by a search pattern to select text.
- Use the ‘?’ key to toggle whether the search pattern should be interpreted as a regular expression or not.
- Use the ‘!’ key to negate the search pattern (i.e., select all occurrences of the pattern that do not match the search pattern).
- Deletion:
- Use ‘x’ (delete selected text) or ‘X’ (delete selected text and move left).
- Insertion:
- Use ‘i’ (insert text at cursor) or ‘I’ (insert text at beginning of line).
- Use ‘a’ (append text at end of line) or ‘A’ (append text at beginning of line).
- Modification:
- Use ‘r’ (replace selected text with new character) or ‘R’ (replace selected text with new character and move right).
- Copy and Paste:
- Use ‘y’ (yank selected text to clipboard) or ‘Y’ (yank line to clipboard).
- Use ‘p’ (paste text from clipboard after current line) or ‘P’ (paste text from clipboard before current line).
- Other:
- Use ‘.’ (repeat last command) or ‘,’’ (start of line).
- Use ‘!’ (execute command) or ‘#’ (toggle comment).
- Use ‘$’ (move to end of file) or ‘%’ (move to beginning of file).
- Use ‘^’ (move to beginning of line) or ‘&’ (repeat last command with change).
It’s important to note that in select mode, you can only select text that matches the search pattern. If you want to select text that does not match the search pattern, you need to use the ‘!’ key to negate the search pattern.
Also, keep in mind that some commands in select mode may have different behavior depending on the context. For example, the ‘x’ command will delete the selected text, but if you use it with a count (e.g., ‘3x’), it will delete the next three occurrences of the search pattern.
Finally, it’s important to practice and experiment with different commands in select mode to become proficient in using Vim. With time and practice, you can become more efficient and productive in editing text with Vim.
4. Insert Mode
Press the ‘i’ key to enter insert mode, where you can add new text or modify text.
Here are some basic commands you can use in insert mode:
- Insertion:
- Type any character to insert new text.
- Use the arrow keys (up, down, left, right) to move the cursor and insert text at a specific position.
- Use the ‘a’ key to start inserting text after the cursor.
- Use the ‘A’ key to start inserting text at the end of a line.
- Use the ‘I’ key to insert text at the beginning of a line.
- Use the ‘o’ key to insert a new row after the current row.
- Use the ‘O’ key to insert a new row before the current row.
- Other:
- Use the ‘Esc’ key to exit insert mode and return to normal mode.
It’s important to note that in insert mode, you can only insert text at the cursor position. If you want to insert text at a different position, you need to move the cursor to that position first using the arrow keys or ‘h’, ’l’, ‘j’, and ‘k’ keys.
Also, keep in mind that when you are in insert mode, Vim will not allow you to type any command that would modify the text. If you want to perform a command that modifies the text, such as deleting a character or replacing a word, you need to exit insert mode first by pressing the ‘Esc’ key.
5. Replace Mode
Replace mode replaces existing text with new text. To enter replacement mode, press the ‘r’ key. In this mode, you can type new text to replace existing text at the cursor position.
It’s important to note that in replace mode, you can only replace text at the cursor position. If you want to replace text at a different position, you need to move the cursor to that position first using the arrow keys or ‘h’, ’l’, ‘j’, and ‘k’ keys.
Also, keep in mind that when you are in replace mode, Vim will not allow you to type any command that would modify the text. If you want to perform a command that modifies the text, such as deleting a character or replacing a word, you need to exit replace mode first by pressing the ‘Esc’ key.
6. Command Mode
Pressing the ‘:’ key will take you into command mode, where you can enter Vim commands. In this mode, you can use commands like :w, :q, :e, and others.
Here are some basic commands you can use in command mode:
:w
- Write or save the file without exiting Vim.:q
- Quit Vim. If there are unsaved changes, you’ll be prompted to discard them.:q!
: Quit Vim without saving changes:qa!
- Quit all windows and discard any unsaved changes.:e filename
- Open a new file for editing.:r filename
- Read or insert the contents of a file at the cursor position./pattern
- Search for a pattern in the file. Press n to move to the next occurrence of the pattern, and N to move to the previous one.:set paste
- Enter paste mode to prevent auto-indentation when pasting text from outside Vim.:set number
or:set nu
- Show line numbers in the left margin.:set spell
- Enable spell checking for the current file.:set nospell
- Disable spell checking.:s/old/new/g
- Replace all occurrences of “old” with “new” in the current line. Use a count, like “:s/old/new/g 3”, to apply the substitution three times.:g/pattern/d
- Delete all lines that match a pattern.
7. Ex Mode
Pressing the ‘Q’ key will take you into ex mode, where you can execute Vim commands without leaving command mode. This mode is useful for executing complex commands that require multiple keys to be pressed.
These are the most common modes in Vim, but there are several others that you can use depending on your needs. It’s important to understand the different modes and when to use them to become proficient in using Vim.
Mode Switching
Normal | Visual | Select | Insert | Replace | Cmd-line | Ex | |
---|---|---|---|---|---|---|---|
Normal | v V ^V | *4 |
*1 |
R gR | : / ? ~ | Q | |
Visual | *2 |
^G | c C | : | |||
Select | *5 |
^O ^G | *6 |
||||
Insert | <Esc> | <Insert> | |||||
Replace | <Esc> | <Insert> | |||||
Command-line | *3 |
:start | |||||
Ex | :vi |
-
*1
Go from Normal mode to Insert mode by giving the command “i”, “I”, “a”, “A”, “o”, “O”, “c”, “C”, “s” or S". -
*2
Go from Visual mode to Normal mode by giving a non-movement command, which causes the command to be executed, or by hitting <Esc>, “v”, “V” or “CTRL-V”, which just stops Visual mode without side effects. -
*3
Go from Command-line mode to Normal mode by:- Hitting <CR> or <NL>, which causes the entered command to be executed.
- Deleting the complete line (e.g., with CTRL-U) and giving a final <BS>.
- Hitting CTRL-C or <Esc>, which quits the command-line without executing the command. In the last case <Esc> may be the character defined with the ‘wildchar’ option, in which case it will start command-line completion. You can ignore that and type <Esc> again. {Vi: when hitting <Esc> the command-line is executed. This is unexpected for most people; therefore it was changed in Vim. But when the <Esc> is part of a mapping, the command-line is executed. If you want the Vi behaviour also when typing <Esc>, use “:cmap ^V<Esc> ^V^M”}
-
*4
Go from Normal to Select mode by:- use the mouse to select text while ‘selectmode’ contains “mouse”
- use a non-printable command to move the cursor while keeping the Shift key pressed, and the ‘selectmode’ option contains “key”
- use “v”, “V” or “CTRL-V” while ‘selectmode’ contains “cmd”
- use “gh”, “gH” or “g CTRL-H” |g_CTRL-H|
-
*5
Go from Select mode to Normal mode by using a non-printable command to move the cursor, without keeping the Shift key pressed. -
*6
Go from Select mode to Insert mode by typing a printable character. The selection is deleted and the character is inserted.
Navigation
Moving through a file
h
: Move the cursor leftl
: Move the cursor rightj
: Move the cursor downk
: Move the cursor up0
(zero): Move the cursor to the beginning of the line^
: Move the cursor to the first non-blank character of the line$
: Move the cursor to the end of the lineg_
: Move the cursor to the last non-blank character of the lineG
: Move the cursor to the last line of the filegg
: Move the cursor to the first line of the file<C-d>
(Control+D): Scroll down half a screen<C-u>
(Control+U): Scroll up half a screen<C-f>
(Control+F): Move forward one full screen<C-b>
(Control+B): Move back one full screenH
: Move the cursor to the top of the screenM
: Move the cursor to the middle of the screenL
: Move the cursor to the bottom of the screen
Jumping to specific lines or words
10G
|10gg
|:10
: Jump to line 10*
: Search for the word under the cursor#
: Search backwards for the word under the cursor
Moving through search results
/foo
: Search “foo”n
: Move the cursor to the next match (forward)N
: Move the cursor to the previous match (backward)
Text Editing
Inserting and appending text
i
: Insert text before the cursorI
: Insert text at the beginning of the linea
: Append text after the cursorA
: Append text at the end of the line
Editing lines
J
: Join the current line with the next linecc
|S
: Change the entire current line (delete and enter insert mode)cw
: Change the word under the cursor (delete and enter insert mode)C
: Change the rest of the line from the cursor position (delete and enter insert mode)r
: Replace a single character under the cursor with another characterR
: Enter replace mode; replace multiple characters until you pressEsc
g~
: Invert the case of the character under the cursor
Deleting text
x
: Delete the character under the cursorX
: Delete the character before the cursordd
: Delete the entire current lineD
: Delete the rest of the line from the cursor position (cut)cw
: Change the word under the cursor (delete and enter insert mode)
Copying and pasting text
yy
: Yank (copy) the entire current line into the default registeryw
: Yank (copy) the word under the cursor into the default registerp
: Put (paste) the contents of the default register after the cursor positionP
: Put (paste) the contents of the default register before the cursor position
Undoing and redoing changes
u
: Undo the last change made to the fileCtrl+R
(Control+R): Redo the last undone change
Searching and Replacing Text
Basic search commands
/foo
: Search forward for the word “foo”?bar
: Search backward for the word “bar”n
: Move the cursor to the next match (forward) after searchingN
: Move the cursor to the previous match (backward) after searching
Advanced search commands
:%s/foo/bar/g
: Find and replace all occurrences of “foo” with “bar” in the entire file:%s/foo/\=strtr(submatch(0), 'abc', 'xyz')/g
: Replace each character in the word “foo” with its corresponding character in the string “xyz”
Indentation and Formatting
Adjusting indentation
>>
: Indent the current line or selected lines by one tab stop (or shift width)<<
: Unindent the current line or selected lines by one tab stop (or shift width)==
: Reindent the current line or selected lines to the correct indentation level
Formatting paragraphs and code blocks
gqip
: Format the current paragraph (text between two blank lines)=ap
: Format the selected block of codegwap
: Swap the selected block of code with its mirror image (for example, to flip a function body)
Code Folding and Toggling
Folding and unfolding regions
zf
: Fold the current line or selected lines into a regionza
: Toggle the fold status of the current line (open if folded, close if not folded)zM
: Close all folds in the current bufferzR
: Open all folds in the current buffer
Setting fold levels
zm
: Decrease the fold level by one (close a fold or open a more nested fold)zr
: Increase the fold level by one (open a fold or create a new fold)
Buffer Management
Listing and switching buffers
:ls
: List all buffers in the current Vim session:b foo
: Switch to the buffer named “foo”<C-^>
(Control+Shift+6): Switch between the last two used buffers
Splitting and closing windows
:split
or:sp
: Open a new window with the same file in the current tab page:vsplit
or:vsp
: Open a new vertical window with the same file in the current tab page<C-w>_
: Close the current window (but not the buffer)
Resizing windows
<C-w>+
: Increase the height of the current window by one line<C-w>-
: Decrease the height of the current window by one line<C-w>>
: Increase the width of the current window by one column<C-w><
: Decrease the width of the current window by one column
Moving windows
<C-w>h
: Move the current window to the left<C-w>j
: Move the current window downward<C-w>k
: Move the current window upward<C-w>l
: Move the current window to the right
Window navigation
<C-w>p
: Move the cursor to the previous window (left or above)<C-w>n
: Move the cursor to the next window (right or below)
Tab Management
Opening, closing, and listing tabs
:tabnew
or:tabedit
: Open a new tab with an empty buffer:tabedit foo.txt
: Open a new tab with the file “foo.txt”:qa
: Close all windows and tabs in the current Vim session:lt
: List all tabs in the current Vim session
Moving between tabs
<C-w>T
: Move the current window to its own tab pagegT
: Move the cursor to the previous tab page (left or above)gt
: Move the cursor to the next tab page (right or below)
File Operations
Opening and saving files
:edit foo.txt
: Open a new buffer with the file “foo.txt”:write
or:w
: Save the current buffer’s contents to its associated file:qa
: Quit all windows and tabs in the current Vim session (or use:wq
to save changes before quitting)
Splitting windows with different files
:split foo.txt
: Open a new window with the file “foo.txt”:vsplit bar.txt
: Open a new vertical window with the file “bar.txt”
Tips and Tricks
Here are some tips and tricks to help you become more proficient in using Vim:
- Learn the basics: Before you can start using Vim effectively, you need to learn the basic commands and keybindings. The good news is that once you learn the basics, you’ll be able to do a lot with just a few keys.
- Use registers: Registers are a key feature in Vim that allow you to store and recall text, which can save you a lot of time when working with repetitive tasks.
- Use macros: Macros are a way to record a sequence of commands and play them back at a later time. This can be very useful when you need to perform a series of actions repeatedly.
- Customize your workflow: Vim is highly customizable, which means you can tailor it to fit your specific needs and workflow. This can include things like custom keybindings, plugins, and configuration files.
- Use the right syntax: Vim has a steep learning curve, but once you master the syntax, you’ll be able to perform complex tasks quickly and efficiently.
- Use plugins: Plugins are a great way to extend the functionality of Vim and make it even more powerful. There are many plugins available that can add new features and enhance your workflow.
- Learn the advanced commands: Once you’ve mastered the basics, it’s time to start learning the advanced commands. These commands can help you perform complex tasks even faster and more efficiently.
- Practice, practice, practice: The more you use Vim, the better you’ll become at it. Practice as much as possible and try to use Vim for all your text editing needs.
- Use the built-in help: Vim has a built-in help system that can provide you with information on all the commands and features available in the editor. This can be very useful when you’re trying to learn new commands or troubleshoot issues.
- Join the community: There is a large and active community of Vim users who share tips, tricks, and best practices. Joining this community can help you learn new techniques and improve your skills.
Popular Plugins
- Nerdtree: A plugin that adds a file tree to the left side of the screen, making it easier to navigate your files.
- Syntastic: A plugin that provides syntax highlighting for a wide range of programming languages.
- Vim-Airline: A highly configurable status line for Vim that’s easy to customize and improves your overall editing efficiency.
- Nerd Commenter: This plugin helps you easily comment and uncomment lines of code in various programming languages.
- FZF: A command-line fuzzy finder with syntax highlighting, keyboard navigation, and file filtering capabilities.
- YouCompleteMe: A fast, as-you-type code completion engine for Vim.
- Coc.nvim: A Language Server Protocol (LSP) plugin that provides IntelliSense features, like autocomplete and go-to-definition, for many popular programming languages.
- Vim-Fugitive: This plugin allows you to easily manage Git repositories within Vim.
- Ale: A syntax and style checker that works with many popular programming languages, providing real-time error checking while you type.
- Vim-surround: This plugin makes it easy to work with pairs of characters (like quotes or parentheses) surrounding text in your files.
- Lightline: A light and configurable statusline/tabline plugin for Vim.
- Vim-easymotion: EasyMotion provides a much simpler way to use some motions in vim. It takes the
out of w or f{char} by highlighting all possible choices and allowing you to press one key to jump directly to the target. - Vim-lsp: A plugin that provides language server protocol support, allowing you to use advanced language features like code completion and syntax highlighting.
These are some popular plugins for Vim that can greatly enhance your productivity as a programmer. You can easily install them using Vim’s package manager, such as Vundle, Pathogen, or Vim-Plug.
Conclusion
Vim may take some time to get used to, but with practice and patience, it can become an indispensable tool for anyone working with text. Remember to keep practicing and experimenting with new commands and keybindings to become more proficient in using Vim. Happy editing!