Vim is a powerful and flexible text editor, widely used by developers for its speed and efficiency. Although its command-line interface can be intimidating for beginners, mastering its commands can greatly improve your productivity. Here’s a complete rundown of Vim’s essential commands.
Vim modes
Vim has several operating modes. The main ones are :
- Normal mode: The default mode for navigating and executing commands.
- Insert mode: To insert text.
- Visual mode: To select text.
- Command mode: To execute specific commands.
Switching between modes
- Esc: Return to Normal mode.
- i: Switch to Insert mode to the left of the cursor.
- a: Switch to Insert mode to the right of the cursor.
- v: Switch to Visual mode.
- (colon): Switch to Command mode from Normal mode.
Navigation
Navigating efficiently is crucial in Vim. Here are some basic commands:
- h: Move the cursor to the left.
- j: Move the cursor down.
- k: Move the cursor upwards.
- l: Move the cursor to the right.
- w: Go to the beginning of the next word.
- b: Go to the beginning of the previous word.
- 0: Go to the beginning of the line.
- $ : Go to the end of the line.
- gg: Go to the beginning of the file.
- G: Go to the end of the file.
Text Editing
Vim offers a host of commands for editing text efficiently.
Insert text
- i: Insert before the cursor.
- I: Insert at the beginning of the line.
- a: Insert after the cursor.
- A: Insert at the end of the line.
- o: Insert a new line underneath.
- O: Insert a new line above.
Delete from text
- x: Delete the character below the cursor.
- dd: Delete the entire line.
- dw: Delete to the beginning of the next word.
- D: Delete to the end of the line.
Copy and Paste
- yy: Copy (yank) the entire line.
- yw: Copy the next word.
- p: Paste after the cursor.
- P: Paste before the cursor.
Undo and Redo
- u: Cancel the last order.
- Ctrl + r: Restore a cancelled command.
Search and replacement
Searching for and replacing text are common operations in file editing.
Search
- /: Search forwards in the file.
- ?: Search backwards in the file.
- n: Go to the next occurrence.
- N: Go to the previous occurrence.
Replacement
- :s/old/new: Replace the first occurrence on the current line.
- :s/old/new/g: Replace all occurrences on the current line.
- :%s/old/new/g: Replace all occurrences in the entire file.
File Management
File management commands are essential for opening, saving and closing files.
- :e file_name: Open a file.
- :w: Save the current file.
- :w filename: Save under another name.
- :q: Exit Vim.
- :q! Quit without saving.
- :wq: Save and exit.
Conclusion
Vim is a powerful tool that can dramatically improve your workflow. Start with these basic commands and explore the many advanced features Vim has to offer. With practice, you’ll find that Vim becomes an indispensable tool in your development arsenal.