avatar

Andres Jaimes

Useful vim commands

By Andres Jaimes

Even though we have many sophisticated GUI text editors, there is one that has passed all time tests: vi.

vi is a text editor created originally for Unix in 1976. Are you kidding? 1976? Why should I even bother to know it exists? Because that is the only text editor you will find for sure in any Unix like command line environment, that includes any Unix flavor, Linux and Macs. Believe me, there are many times when you have no other way to edit files (like webpages, php’s, css’s) but from the command line. Also your customer will be very impressed when he looks at you doing all this stuff. Really.

vi has two working modes: insert mode for text insertion and command mode for operations like copying and pasting, saving and many others. By default vi starts in command mode. To go into insert mode you have to press i or any other insertion command (look below). To go back to command mode from insert mode you have to press Esc.

Following there is a list of some of the most used commands.

Insert commands

To use any of the following commands you have to be in insert mode (press i or any other insertion commands to do it)

i           Begins insert mode
o           Inserts a new line below the cursor
O           Inserts a new line above the cursor
Ctrl - t    Adds a level of indentation - works on insert mode
Ctrl - d    Removes a level of indentation - on insert mode
arrows      Move the cursor around the file.

Text commands

To use any of the following commands you have to be in command mode (press Esc to do it).

x       Deletes one character from cursor
10x     Deletes ten characters from cursor
dd      Deletes a line
yy      Yanks (copies) a line into the buffer (the clipboard)
p       Puts the buffer contents at the current location (paste)
u       Undo the last modification

Colon commands

To use any of the following commands you have to be in command mode (press Esc to do it).

:set sm              Shows matching braces
:syntax on           Syntax highlighing
:set number          Show line numbers
:set ruler           Show the cursor position all the time
:set ignore case     Ignore case when searching
:set hlsearch        Highlight searches
:set tabstop=4       Number of spaces of tab character
:set shiftwidth=4    Number of spaces to (auto)indent
:set auto indent     Set auto indenting on
:set smartindent     Smart indent
:set cindent         cindent
:!ls                 Executes ls or any other operating system command without leaving the editor
:q                   Quits the editor
:q!                  Quits the editor without saving any changes, useful when accidents happen
:w                   Writes the file changes to the disk