Learning coding means GreatToCode Be more than a Coder ! Greattocode , Join GreatToCode Community,1000+ Students Trusted On Us .If You want to learn coding, Then GreatToCode Help You.No matter what It Takes !


CODE YOUR WAY TO A MORE FULFILLING And HIGHER PAYING CAREER IN TECH, START CODING FOR FREE Camp With GreatToCode - Join the Thousands learning to code with GreatToCode
Interactive online coding classes for at-home learning with GreatToCode . Try ₹Free Per Month Coding Classes With The Top Teachers . Vim Tutorial: Basics to Advanced Concepts

Vim Tutorial: Basics to Advanced Concepts

 Vim (Vi IMproved) is an open-source text editor for Unix-based Operating Systems. It is a clone of the Vi editor and was created by Bram Moolenaar. It was first released in 1991. After the first release, cross-platform development enabled Vim to be available in many other Operating Systems. Vim traditionally doesn't have GUI and uses the terminal as its GUI but now there is a separate installed called gVim which provides GUI. Vim also has a built-in tutorial for beginners called vimtutor which is usually installed along with Vim although it exists as a separate executable.

Vim is a command-centric text editor and hence we can do everything we can do with modern text editors like VS Code, Sublime Text, etc with Vim just using the keyboard commands. Vim is a quite popular text editor because of its many features which save a lot of time for its users. The memory footprint is also very low. It also supports multiple tabs and windows which allows working on multiple files at the same time. Vim is highly configurable and extensible, making it an attractive tool for users who demand a large amount of control and flexibility over their text editing environment. Vim should be available by default on Linux based machines, if not we can download vim here.

1. Modes

Vim splits its functionality into different modes with each mode having a specific purpose. There are 7 different modes in Vim.

1. Normal Mode: By default, Vim starts in Normal mode. This mode can be thought of as an edit mode. Programmers spend most of their time editing than writing. Hence a text editor should be optimized for editing than writing. Hence this is the default mode. Mostly this mode is used for navigating and editing. To get to normal mode from any other mode, we press Esc.

2. Insert Mode: This mode is where the inserting of text happens. This mode can be thought of as a write mode. You can write content to the file using this mode. To enter into insert mode, we press i. When we enter this mode, we can see the status change at bottom of the screen as shown below.

~
~
--INSERT--

3. Command Mode: This mode is used for doing complex operations on a file like a search, replace, etc. To enter into command mode from normal mode, we press : .

4. Visual Mode: This mode is used to make selections of text, similar to how clicking and dragging with a mouse behaves. Any commands used in visual mode apply to only selected text.
There are 3 different variants in Visual Mode.

  • Visual Mode: To enter this mode, we press v. In this mode, any text selection happens from the start cursor to the end cursor. When we enter this mode, we can see the status change at bottom of the screen as shown below.
~
~
--VISUAL--
  • Visual Line Mode: To enter this mode, we press Shift + v. In this mode, any text selection happens from starting line to the end line. When we enter this mode, we can see the status change at bottom of the screen as shown below.
~
~
--VISUAL LINE--
  • Visual Block Mode: To enter this mode, we press Ctrl + v. In this mode, any text selection happens from the start cursor to the end cursor in rectangular blocks. When we enter this mode, we can see the status change at bottom of the screen as shown below.
~
~
--VISUAL BLOCK--

5. Select Mode: This is very similar to Visual Mode but it more looks like the MS-Windows selection mode. To enter this mode, we press gh. This also has 3 different sub-modes like select line mode, select block mode and select mode. When we enter this mode, we can see the status change at bottom of the screen as shown below.

~
~
--SELECT--

6. Ex Mode: This mode is more like a command mode, but after entering a command you remain in Ex mode. Very limited editing of the command line.

7. Terminal Job Mode: Interacting with a job in a terminal window. Typed keys go to the job and the job output is displayed in the terminal window.

Out of these 7 modes, only 4 modes are used mostly. Normal mode, Insert mode, Visual mode and Command mode.

From ModeTo ModeCommandExplanation
Any ModeNormal ModeEscMove from any mode to normal mode.
Normal ModeInsert ModeiPlace the cursor at the current position.
Normal ModeVisual ModevPlace the cursor at the current position.
Shift + vMove from normal mode to visual line mode.
Ctrl + vMove from normal mode to visual block mode.
Normal ModeCommand Mode:Move from normal mode to command mode.

2. Open, Save, Exit Files

To work on a file, we should know how to open a file, save the changes to the file and how to exit from vim.

CommandExplanation
vim <file name>Opens the file in the vim editor.
:e <file name>Open a file when the vim editor is already open.
:wSave content to the current file.
:w <file name>Save content by creating a new file <file name> if the file is not present. If present fails to write.
:qExit current vim editor if no changes are present.
:q!Exit current vim editor ignoring changes.
:wqSave vim content and then exit vim editor. :wq always writes the buffer to the file and updates the file modification time.
:xSame as :wq but :x only writes the buffer to the file only if there are unsaved changes. 

3. Editing

We do editing in normal mode and most of the time editing needs adding/replacing/deleting characters/words/lines, we need to be in insert mode for this. So most of the below command also implicitly move from normal mode to insert mode. 

Note: The yellow highlighter is the cursor. Text in italic implies, vim in insert mode else vim in normal mode. The statement before => is statement before applying command and statement after => is statement after applying command. 

Below is the Vim Editing Cheat Sheet:

CommandExplanationExample
aMove the cursor to the next character.The quick brown fox jumps over the lazy dog
=>
The quick brown fox jumps over the lazy dog
AMove the cursor to the end of the line. The quick brown fox jumps over the lazy dog
=>
The quick brown fox jumps over the lazy dog  
oInserts a new line below the current line and place the cursor at the start of a new line.

The quick brown fox jumps over the lazy dog
=>
The quick brown fox jumps over the lazy dog

OInserts a new line above the current line and place the cursor at the start of a new line.

The quick brown fox jumps over the lazy dog
=>

The quick brown fox jumps over the lazy dog

IMove the cursor to the start of the line.The quick brown fox jumps over the lazy dog
=>
The quick brown fox jumps over the lazy dog
sDeletes the current character and moves the cursor to the next character.The quick brown fox jumps over the lazy dog
=>
The quick brwn fox jumps over the lazy dog
SDeletes the current line and moves the cursor to the start of the line.

The quick brown fox jumps over the lazy dog
=>

CDeletes content from the cursor position to the end of the line.

The quick brown fox jumps over the lazy dog
=>

The quick br

r<char>Replace a single character with a new character.The quick brown fox jumps over the lazy dog
=>
The quick br<char>wn fox jumps over the lazy dog
JJoin the line below to the current one with one space in between (gJ for no space).The quick brown fox jumps over the lazy dog.
This statement is a pangram.
=>
The quick brown fox jumps over the lazy dog.   This statement is a pangram.
uUndo the action.NA
Cntrl+rRedo the action.NA

4. Navigating

Navigating through a file can be considered one of the most important features a text editor can provide. Vim provides a lot of commands to not only navigate the file but to do the navigation efficiently. While navigating, the commands do not make vim enter insert mode, unlike editing. 

Below is the vim navigation cheat sheet:

CommandExplanationExample
h (or) left arrowMove cursor left.The quick brown fox jumps over the lazy dog.
=>
The quick brown fox jumps over the lazy dog.
l (or) right arrowMove cursor right.The quick brown fox jumps over the lazy dog.
=>
The quick brown fox jumps over the lazy dog.
j (or) down arrowMove cursor down.The quick brown fox jumps over the lazy dog.
This statement is a pangram.
=>
The quick brown fox jumps over the lazy dog.
This statement is a pangram.
k (or) up arrowMove cursor up.The quick brown fox jumps over the lazy dog.
This statement is a pangram.
=>
The quick brown fox jumps over the lazy dog.
This statement is a pangram.
0Move the cursor to the start of the line.The quick brown fox jumps over the lazy dog.
=>
The quick brown fox jumps over the lazy dog.
$Move the cursor to the end of the line.The quick brown fox jumps over the lazy dog.
=>
The quick brown fox jumps over the lazy dog.
ggMove the cursor to the first line of the file.NA
GMove the cursor to the last line of the file.NA
<line no>G (or) :<line no>Move the cursor to line number <line no>.50G makes the cursor move to line number 50
%Move cursor to matching character of () or {} or [].(The quick brown fox jumps over the lazy dog.)
=>
(The quick brown fox jumps over the lazy dog.)
zzMake the current line the centre line of the screen.NA
ztMake the current line the top line of the screen.NA
zbMake the current line the bottom line of the screen.NA
HMove the cursor to the top of the screen.NA
MMove the cursor to the middle of the screen.NA
LMove the cursor to the bottom of the screen.NA

5. Search and Replace

Vim provides commands for searching content in a file and also can help in replacing content. Here are some of the most used commands for search and replace in vim. vim used sed Unix command like syntax to replace content in a file.

CommandExplanation
/patternSearch for the pattern in the file from the cursor position to the end of the file (forward search).
?patternSearch for the pattern in the file from the cursor position to the start of the file (backward search).
nIf multiple patterns are matched, n is used to move the cursor to the next pattern match.
NIf multiple patterns are matched, N is used to move the cursor to the previous pattern match.
:%s/old/new/gReplaces all the old content with new content throughout the file.
:%s/old/new/gcReplaces all the old content with new content throughout the file but with confirmation for each replacement.
*Search forwards for a word the same as a current word under the cursor.
#Search backwards for a word the same as a current word under the cursor.

6. Cut, Copy, Paste

Cut, Copy, and Paste can be considered one of the most commonly performed tasks when working with text files. Keep this in mind, Vim provides several vim commands to do these tasks efficiently.

In the Vim world, Copy is called Yank, Cut is called Cut, and Paste is called Put. All the operations that we do have the effect only in Vim. For example, copying a line in vim copies the content to its internal buffer and hence can only be pasted in vim editor only. We can't paste the content somewhere else.

OperationCommandExplanationExample
Yank (Copy)yCopy a single character.The quick brown fox jumps over the lazy dog. 
(copies the character w to vim buffer).
yyCopy the current line.The quick brown fox jumps over the lazy dog. 
(copies the whole line to vim buffer).
3yyCopy three lines starting from the current line.The quick
brown
fox jumps
over the lazy dog.
(copies lines The quick, brown, and fox jumps)
y$Copy everything from the cursor to the end of the line.The quick brown fox jumps over the lazy dog.
(Copies n fox jumps over the lazy dog.
y0Copy everything from the start of the line up to the cursor (not including the cursor character).The quick brown fox jumps over the lazy dog.
(Copies The quick bro).
ywCopy from the cursor to the start of the next word.The quick brown fox jumps over the lazy dog.
(Copies rown  (note the space after n))
yiwCopies the whole current word no matter where the cursor is.The quick brown fox jumps over the lazy dog.
(Copies brown).
Cutd{motion}If the motion is left, it cuts the character before the cursor.
If the motion is right, it cuts the character at the cursor.
The quick brown fox jumps over the lazy dog.
=> (d + h, Note: h is the motion to left)
The quick brwn fox jumps over the lazy dog.
—-----------------
The quick brown fox jumps over the lazy dog.
=> (d + l, Note: l is the motion to right)
The quick bron fox jumps over the lazy dog.
ddCut the current line.NA
3ddCut 3 lines starting from the current line.NA
d$Cut everything from the cursor to the end of the line.The quick brown fox jumps over the lazy dog.
=>
The quick bro
(copies the wn fox jumps over the lazy dog. to internal buffer)
d0Cut everything from the start of the line up to the cursor (not including the cursor character).The quick brown fox jumps over the lazy dog.
=>
wn fox jumps over the lazy dog.
(copies the The quick bro to internal buffer)
dwCut from the cursor to the start of the next word.The quick brown fox jumps over the lazy dog.
=>
The quick brofox jumps over the lazy dog.
(copies wn  to internal buffer)
diwCut the whole current word no matter where the cursor is.The quick brown fox jumps over the lazy dog.
=>
The quick   fox jumps over the lazy dog.
Put (Paste)pPut the internal buffer content (yanked or cut) after the cursor position.The quick brown fox jumps over the lazy dog.
=> (let's say vim is present in buffer)
The quick browvimn fox jumps over the lazy dog.
PPut the internal buffer content (yanked or cut) before the cursor position.The quick brown fox jumps over the lazy dog.
=> (let's say vim is present in buffer)
The quick brovimwn fox jumps over the lazy dog.
DeletexActs like a delete.NA
XActs like backspace.NA

It would be much easier to cut, and copy in visual mode than in the normal mode. We can select the exact text we want to copy/cut in visual mode and use y (for copy), d (for cut). 
To know more about copy, cut, and paste, visit here.

7. Working with Multiple Files

Vim also provides functionality to work with more than 1 file at the same time. To do this, Vim has 3 concepts.

  1. Buffer
  2. Window
  3. Tab

A buffer is the in-memory text of a file. Vim creates a new buffer when we open a new file. Windows and Tabs are introduced in the subsequent section.

CommandExplanationExample
vim <file1> <file2> <file3>Opens vim editing session with 3 files with an initial focus on file1. Each opened file is considered a buffer.vim test1.txt test2.txt test3.txt
:ls (or) :buffersShows a list of opened files.1. test1.txt
2. test2.txt
3. test3.txt
:n (or) :bn

Switch to the next file.

Note: :bn means next buffer

If we are at test1.txt currently, then :n moves focus to test2.txt.
:N (or) :bp

Switch to the previous file.

Note: :bp means the previous buffer

If we are at test2.txt currently, then :N moves focus to test1.txt.
:e <file>Adds <file> to the current editing session.

:e test4.txt adds the test4.txt to the current editing session.

:ls should give
1. test1.txt
2. test2.txt
3. test3.txt
4. test4.txt

:bfSwitch to the first buffer i.e., the first file.:bf here would mean switching to test1.txt
:blSwitch to the last buffer i.e., the last file.:bl here would mean switching to test4.txt
:b <number>Switch to the <number> buffer.The numbers are the numbers seen in :ls output. 
:b 3 here means a switch to test3.txt as this file has corresponding number 3 in :ls
:wallSave the content of all files in the editing session.NA
:bwQuits the current file from the editing session.If we are at test3.txt and issues :bw then that file is removed from current editing session leaving only 3 files present (test1.txt, test2.txt, and test4.txt).
:qallQuit all files from editing session.Removes all the files from the session and closes the vim session.
:qall!Quits all files from the editing session without saving the changes.NA

8. Windows

The other feature that Vim provides for working with multiple files in Windows. A window is a viewport on a buffer. We can have multiple windows opened each for a different buffer. Windows make it possible to see more than 1 file on the same screen.

CommandExplanationExample
vim -o <file 1> <file 2>Opens 2 new buffers in 2 horizontally separated windows.

vim -o test1.txt test2.txt

test1.txt is in the top window and test2.txt is in the bottom window.

vim -O <file 1> <file 2>Opens 2 new buffers in 2 vertically separated windows.

vim -O test1.txt test2.txt

test1.txt is in the left window and test2.txt is in the right window.

:sp <file>If <file> is specified, opens the <file> is new horizontal window. If not, open the current buffer in a new horizontal window.

:sp test3.txt

Opens another horizontal window for test3.txt buffer.

:vsp <file>If <file> is specified, opens the <file> is new vertical window. If not, open the current buffer in a new vertical window.

:sp test4.txt

Opens another vertical window for the test4.txt buffer.

Ctrl + w ,  jMove to the horizontal window that is below the current window.NA
Ctrl + w, kMove to the horizontal window that is above the current window.NA
Ctrl + w, lMove to the vertical window that is right to the current window.NA
Ctrl + w, hMove to the vertical window that is left to the current window.NA
Ctrl + w, wCycle through all the windows.NA
:close (or) Ctrl + w, cClose the current window.NA
:only (or) Ctrl + w, oClose all windows except current window.NA

9. Tabs

The last feature that is provided by vim for making working with multiple files effectively is tabs.

A tab page is a page with one or more windows in it with a label at the top.

CommandExplanationExample
vim -p <file 1> <file 2>Opens 2 new buffers in 2 tabs.vim -p test1.txt test2.txt opens 2 buffers such that test1.txt is in the first tab and test2.txt in the second tab.
vim -O <file 1> <file 2>Open specified file in a new tab.:tabe test3.txt opens a new tab for a new file test3.txt.
:sp <file>Lists all the tabs opened in the current editing session.:tabs gives 3 tabs as we opened test1.txt, test2.txt and test3.txt.
:vsp <file>Closes the current tab.If we are currently in tab that has file test3.txt, :tabc closes this tab.
Ctrl + w ,  jClose the specified tab number.:tabc 1 closes the first tab.
Ctrl + w, kGo to next tab.NA
Ctrl + w, lGo to previous tab.NA
Ctrl + w, hGo to the tab at position <number>.2gt moves to the 2nd tab
Ctrl + w, wGo to the first tab.NA
:close (or) Ctrl + w, cGo to the last tab.NA
:only (or) Ctrl + w, oMoves the tab to the position specified.:tabm 3 moves the current tab to position 3.
:tabm +<position>Moves the tab to right by position times.:tabm +3 moves the current tab to its right by 3 times.
:tabm -<position>Moves the tab to left by position times.:tabm -2 moves the current tab to its left by 2 times.

10. Miscellaneous

Vim also offers a lot of other features that can also be used for effectively doing various miscellaneous stuff.

CommandExplanationExample
:! <cmd>Execute <cmd> in the shell and press Enter to get back to where you are in vim.:! ls will execute the command ls and show the list of files and then when we press enter, we get back to where we are in vim. This greatly helps in quickly getting back out of vim and executing some commands.
Ctrl + nAutocomplete the word matching the current prefix.If a file has the content "A quick brown fox jumps over the lazy dog" and we try to write the word brown again, instead of typing the whole brown, we can type b and then use Ctrl + N to auto-complete the word. If there is more than one-word matching prefix, then vim shows the list of possibilities to choose from.
Ctrl + x + lAutocomplete the whole line matching the current prefix.Same as above but auto-complete the current prefix with existing lines.
:set spell spelllang=<lang>Enables the check for spelling mistakes in the file. Marks all misspelt words in red.

:set spell spelllang=en_us

<lang> are en_us for USA, en_gb for Great Britain, en_au for Australia etc.

:set nospell To disable spell check.NA
m<character>Marks the current position with a character so that we can move back to this position.ma marks the current position (row, col) with the character a. 
`<character>Moves the cursor to the position marked by the character.`a moves the cursor to the position captured by the mark a.
:marksShow the list of markers.NA
Ctrl + r=<math exp>Calculates the given math expression and put it at the cursor position in insert mode.Ctrl + r=250*12/3 makes the result 1000 inserted at the current position of the cursor.
:set foldmethod=<fold_type>Set the fold method to the type specified.

Different types of <fold_type> are:
1. manual : select the lines manually that we want to fold
2. indent: based on the indentation levels of lines, vim automatically does the folding
3. marker: based on the corresponding match of markers like {, (, [ used for folding

These are the majorly used folding methods.

zfCreate a fold based on the fold method.This helps in folding long methods into a single line for a better view.
zaToggle the fold. If folded, then opens. If opened, then folds.NA
zMCloses all the opened folds.NA
zROpens all the closed folds.NA

Conclusion

With all the features that Vim has, It can easily help its users to do work efficiently and quickly without having to remove their hands from the keyboard. Vim uses different modes to do different operations. We can quickly open files, save changes, navigate around the file, do the editing, do basic operations like a copy (yank), and cut and paste (put) easily with all the vim commands that vim provides. With the introduction of features like buffers, windows, and tabs, vim makes the users work on multiple files at the same time. Although it takes a bit of time to learn vim and get used to vim editor, once we get used to it, we can before very efficient and quick in writing code/ content.

Often in a developer's life, we get the need to ssh to other machines to do some tasks. With ssh, we will not have the ability to use modern text editors to edit/insert the code. Mastering Vim becomes very handy in that case to not only make the changes but do it quickly and efficiently with the help of all these vim shortcuts.

1.

Which of the following statement(s) is/are true?

2.

How many modes are present in vim?

3.

How to open a new file (test.txt) when we are already in vim?

4.

How to copy from the start of the line to the cursor position in a line?

5.

What command to use to close the file after saving the changes?

6.

How to run the ls shell command when we are already in vim?

7.

How to fold a python method in a file?

8.

How to search the word “vim” in a file and then move the cursor to the next match?

9.

What are the commands for moving to the last line of the document and moving to the first line of the document?

10.

How to access the built-in tutorial for Vim?


Post a Comment

0 Comments

•Give The opportunity to your child with GreatToCode Kid's • Online Coding Classes for Your Kid • Introduce Your kid To the world's of coding
•Fuel You Career with our 100+ Hiring Partners, Advance Your Career in Tech with GreatToCode. •Join The Largest Tech and coding Community and Fast Forward Your career with GreatToCode. •10000+ Learner's+ 90 % placement Guarantee. • Learning Coding is Better with the GreatToCode community .
•Greattocode Kid's •GreatToCode Career •GreatToCode Interview •GreatToCode Professional •GreatToCode for schools •GreatToCode For colleges •GreatToCods For Businesses.
Are you ready to join the millions of people learning to code? GreatToCode Pass is your one-stop-shop to get access to 1000+ courses, top-notch support, and successful job placement. What are you waiting for? Sign up now and get your future in motion with GreatToCode Pass.