Overwiew
Vim is a highly configurable text editor renowned for its efficiency and power. It’s built to enable efficient text editing, making it a popular choice for developers and system administrators.
In this post, I put the commands that I use the most, but I also recommend this interactive Vim tutorial
Open Vim
To open vim, simply type the following in the command-line
vim <path/to/file>
where <path/to/file>
can be the path of any text-based file. If file
doesn’t exist, then it will be created.
You will see something similar to
At this point vim is in navigation mode which means you can move around in the document but not make changes.
To switch to insert mode type i
. Then you can add text.
To exit insert mode just type ESC
. To exit vim, simply type :x
, if you want to save the changes, or :q!
to discard them.
Popular Commands
Here are some of the most commonly used Vim commands:
Navigation
-
h
,j
,k
,l
: Move cursor left, down, up, right respectively. -
w
: Jump forward to the start of a word. -
b
: Jump backward to the start of a word. -
G
: Go to the end of the file. -
gg
: Go to the beginning of the file.
Search
*
: Highlight all occurrences of the word that is under the cursor. To stop highlighting:noh
or:nohlsearch
.- To search for a word, type
/
followed by the word, thenEnter
. Typen
to jump to the next ocurrence.
Editing
-
i
: Enter insert mode at the current cursor location. -
a
: Enter insert mode after the current cursor location. -
o
: Open a new line below the current line and enter insert mode. -
dd
: Delete the current line. -
u
: Undo the last operation. -
Ctrl + r
: Redo the last undo.
Replacements
Vim uses regular expressions to replace patterns inside the text. The syntax is very similar to the sed
bash command. Suppose we want to substitute all occurences of pattern
to replacement
in the text. Then we simply:
- type
ESC
to exit the insert mode - type
s/pattern/replacement/g
+ENTER
NOTE: For more details on this, check “Text Processing with RegEx”
Visual Mode
- Start visual mode typing
v
- To comment a block of code:
- scroll or move with arrows to select block
- Type
: s/^/#
+Enter
- To uncomment a block of code:
- Put cursor on first
#
character and typeCTRL
+v
- Scroll until last line of block
- Type
x
- Put cursor on first
- Copy a block with
y
- Cut a block with
d
- Paste a block with
p
- Indent a block with
>
or<
Saving and Exiting
-
:w + Enter
: Save the changes. -
:q + Enter
: Quit Vim (will not work if there are unsaved changes). -
:wq + Enter
or:x + Enter
: Save the changes and quit Vim. -
:q! + Enter
: Quit Vim without saving the changes.
Remember, Vim
has a steep learning curve, but once you get the hang of it, it can significantly enhance your text-editing efficiency.