Top 20 Linux Vim Commands that Boost Productivity

Filed Under: UNIX/Linux
Linux Vim Commands

VIM or the Vi Improved text editor is one of the most advanced text editors available. Let’s learn the top 20 best Linux Vim commands that you must know to gain amazing levels of productivity.

Remember, the VIM text editor has a pretty steep learning curve. But once you put in the time to get used to the commands, you will attain unmatched productivity in your day-to-day tasks that require working with text (perfect text-editor for programmers!)

Linux Vim Commands
Linux Vim Commands – Color schemes

Very geeky isn’t it? Let’s understand the editor and the commands in it.

Linux Vim Commands for Basic Navigation

Before we begin, let’s go over how we can navigate within the VIM editor. VIM is a keyboard focused editor so you have to start getting used to not touching the mouse for basic navigation tasks.

KeysAction
Arrow Keys
h j k l
Basic cursor movement as normal
B b
W w
Move backward and forward by one word at a time – cursor at the start of the word
<Line Number>GJump to a specified line number
Ctrl+u
Ctrl+d
Similar to page up/down key while the cursor stays on-screen.
eMove forward by one word – cursor at the end of the word
#
*
Find the word within the document that your cursor is currently at.
n
N
Repeats the last find command

Geek Out with the Top Linux Vim Commands and Features

The VIM editor is not only flexible and comprehensive but also very intuitive and “smart” when it comes to understanding the code that’s written.

But if you don’t mind spending your time moving the mouse cursor around pointing and clicking at things, there’s no reason for you to consider VIM. This text editor is for programmers and geeks who really love to go all out, ignore the mouse for good, and do everything using the keyboard.

The thing with VIM is, if it can be done with a mouse in other text editors, it can be done with just the keyboard in VIM.

1. Work With Multiple Files in Vim

Most of us programmers are used to working with multiple files at the same time. Our GUI text editors give us tabs that allow switching between files while all stay open simultaneously. Even though there are a few keyboard shortcuts to play around with those tabs, it’s nowhere compared to what VIM can do.

:tabedit <tab key to scroll through files in directory>
Tabedit Vim Commands
Tabedit Vim Commands

The best part? You don’t touch the mouse whatsoever. How do you move around the files? With gt or gT to switch tabs forward or backward respectively. Also :tabfirst and :tablast will let you jump back and forth from the first to the last tabs that are currently open.

But if you want to open all the files directly at the start, just type:

vim -p source_file1.py source_file2.py source_file3.py 

2. Save and Open Tab Sessions in VIM

Alright, so now you have opened a ton of files in tabs and also moved across made changes to the files. But did you notice that you have to always open the files every time you want to have them in the tabs?

What if there was a way to save the open files as they are and just move with it?

That’s exactly what VIM sessions are for. When you work with multiple files in VIM, it’s better to save a VIM session so the next time you open the session file, everything will come back up exactly as you left it.

How do you create a VIM session? You first move out of the insert mode by pressing the Esc key. Then enter the below command.

:mksession <Session Name>.vim

Now the next time when you want to open the session, you can directly open it from the terminal by typing:

vim -S <Session Name>.vim

Or if you want to open a session file while inside VIM, just type:

:source <Session Name>.vim

3. AutoComplete Text in VIM

Feel that VIM cannot compare with the autocomplete features of other IDEs or text editors? Well, give it a shot. Even though it doesn’t use Artificial Intelligence or any sort of machine learning algorithms to back this feature, it’s robust enough.

When you’re in your VIM editor trying to edit some code, press the below key combination to check it’s superb auto-completion.

Ctrl+n
Vim Ctrl N
Vim Ctrl N

Based on the letters typed, the editor finds the closest match for the word you might type. Though it doesn’t understand anything of what you type, it does the job really well.

4. Linux VIM Commands to Perform Brace Matching

As we previously mentioned that the VIM editor searches for patterns within the text, it brings with it brace matching while you’re coding. It makes things very easy for us when we’re working with long codes.

This one is pretty straight forward. Take your cursor to the opening/closing brace and press the % sign on the keyboard.

And just like that, your cursor will jump to the matching brace.

5. Mark and Fold Code Blocks in VIM

This isn’t as straightforward as you’d want it to be because the code editor does not understand what we are typing but only works on pattern matching. 

So how do we go about folding code inside vim editor? We start with bringing the cursor to where we want to begin the folding and from there we use the letter V to begin marking the code until where we want it to fold.

Highlight Code Vim
Highlight Code Vim

Once we have marked the code with the letter V , then press zf to fold the code. The f in the zf stands for fold. how do we open the Code we just press by highlighting the first line of the folded code

Code Folded
Code Folded

To open the code now, we can bring our cursor to the line where the folded code is (as you can see in the above screenshot, the grey colored line which says 6 lines: function1(). Once your cursor is on that line, press zo where o stands for open.

But the above method is good in cases where the code is small. What if you want to jump through a few hundred lines of code? Let me show you another marking technique that will cut your time in half.

  • Go to the line where you want to start the folding of the code
  • Press the letter m followed by any other letter to name the marking. For example mk
  • Highlight any of the braces within the code and press % to jump directly to the matching close brace.
  • Press zf'k

The 'k signals the fold command to look for the “k” mark which we pointed out by typing out mk at the start.

6. Explore Files in Your System, Without Leaving VIM

A regular GUI text/code editor person would feel that they miss the “Project folder” column that usually is provided on the left sidebar of the code editor window. Can VIM replicate that?

Of course!

With the two commands :Vexplore and :Sexplore, you can split the window into two sections and browse through the entire file system. Have a look at both the commands.

V Explore VIM linux vim commands
V Explore VIM
S Explore Vim linux vim commands
S Explore Vim

As you can see, in both cases, the file manager is opened and you can navigate through the files without losing your focus from the code file that you were working on.

Since we’ve already seen the split-screen capabilities of VIM, how do we split the screen in two and edit two codes?

7. Split VIM Code Window

You can either Vertically or Horizontally split the VIM window and edit multiple code files without moving away from the other. How? Let’s have a look.

The Vexplore and Sexplore commands allow us to browse through files and open any file in the split section of the terminal. But if you just want to open the file, you can use the vsplit or split command.

VERTICAL SPLIT
:vsplit <filename>

OR 

:vsp <filename>

HORIZONTAL SPLIT
:split <filename>

OR 

:sp <filename>

The above command will split the terminal vertically and open the other file for you.

Vim Split Windows
Vim Split Windows
CommandAction
Ctrl-w ←
OR
Ctrl-w h
Focus on the left adjacent split
Ctrl-w →
OR
Ctrl-w l
Focus on the right adjacent split
Ctrl-w ↓
OR
Ctrl-w j
Focus on the bottom adjacent split
Ctrl-w ↑
OR
Ctrl-w k
Focus on the top adjacent split
Ctrl-w n+
OR
Ctrl-w n
Increase or decrease the size of the split by n lines

If you’re working through an SSH client software like Terminus to connect to your Linux server, using the default VIM commands to switch splits will simply close the connection.

Because Ctrl-W is the default shortcut to close tabs on Terminus and on many other Windows software. So how do we go about this?

VIM allows us to remap keys to save keystrokes and also to avoid conflicts.

8. Remap and Change Linux VIM Commands

Some shortcuts in VIM are quite cumbersome and can make us wonder if all the effort is even worth it!

The remap, noremap, nnoremap, inoremap, vnoremap commands allow us to remap existing VIM commands to any other key that we’d like to set up.

The difference between the mapping commands is the map modes they work in. Covering the map modes is out of scope for this topic so I’ll leave it to you to read. Go ahead and type in :help map-modes.

Map Modes Vim
Map Modes Vim

This is the overview of the map-modes but the help topic has a ton of details if you’re interested in understanding these modes.

How to map the existing vim command shortcuts? We’ll work with the “map” command.

Syntax:

:map <new key-combo> <existing key-combo>

For example: 
:map <C-J> <C-W><C-J>
:map <C-K> <C-W><C-K>
:map <C-L> <C-W><C-L>
:map <C-H> <C-W><C-H>
:map l gg

The above mappings will change the default split-window switching commands to Ctrl-J, Ctrl-K and so on instead of the added Ctrl-W.

The last command will change the gg command to l. So whenever you press l, you’ll be taken to the first line.

Do this for as many commands as you need. But these mappings are session-based. Once you quit vim, the mappings are reset.

To set persistent key mapping, we need to add the commands to the VIMrc file. Simply copy-paste the commands without the : in the ~/.vimrc file. If the file does not exist, just create one with only the commands that you need to run on startup of VIM.

To set up these key mappings in addition to the existing default vim configuration, just make a copy or symlink the original file as below:

root@ubuntu:~# ln -s ~/code/dotfiles/vim/vimrc ~/.vimrc

9. Linux VIM commands to enable Syntax Highlighting

Continuing from our previous section, we can add the command syntax on in the ~/.vimrc file to enable the syntax highlight. Have a look at the difference that it would make.

Syntax Off Vim
Syntax Off Vim
Syntax On Vim
Syntax On Vim

You can obviously turn the syntax highlighting on and off while in session too as we did for all other commands before.

10. Linux VIM commands to Cut, Copy, and Paste

Copying and pasting are not as straightforward as Ctrl-c Ctrl-v but it’s pretty easy!

In VIM, Copy action is called Yank, and Cut action is called Delete. The paste action continues to be called Paste.

So the shortcuts are named according to these names. For example, if I have to “Yank” something, I can type y and the selected text gets yanked.

To cut a text, the command is the same as delete, the letter d. So you can understand that even when you delete a piece of text, the VIM editor is actually preparing the text to be pasted somewhere else.

Whatever section the cursor is at, will get copied or deleted. To paste the copied text, just type p to paste after the cursor, and P to paste before the cursor.

11. Spell Checking in VIM

Didn’t expect to see this point, did you? Well, VIm does have a spell checking option that works based on a dictionary file that is already available. All we have to do is set up the language.

Spell Check Off
Spell Check Off

In the ~/.vimrc file, add the following line:

set spell spelllang=en_us
Spell Check On Linux vim commands
Spell Check On

As you can see, the Lorem Ipsum text gets instantly highlighted when I enabled the spell check.

12. Substitution – Find and Replace in VIM

The find and replace functionality that all the GUI text editors offer is also found on VIM. How? Because of pattern matching.

:%s /Lorem/JournalDev/g

The above line will instantly replace every occurrence of Lorem on each line (g) with the word JournalDev.

13. Execute Linux Commands In VIM

So you’re editing some code and need to quickly run a command. Do you need to save and exit VIm just to run the code? Not really!

Vim allows you to run the code from within the editor without having to lose track of the code. You can do this by the use of an exclamation mark after the colon. Here’s an example:

:!ping www.journaldev.com

That’s it! Now if it’s a command that ends after output, you can hit the ENTER key and get back to programming. But in case of this ping command, you can hit the keyboard interrupt Ctrl-C and then hit the ENTER key without losing your VIM editor from the background.

Alternatively, you can just type :shell to directly get a shell opened up for you. Once you’re done with what you need to do, you just type exit to exit the shell and get back to VIM which stays as it was left before.

14. Deleting Multiple Words

You know that the words to the right of your cursor need to be deleted. But not the entire sentence. How do you do it? With the same command and some additional parameters.

The d command will simply make use of the number specified after it to delete those many words. Have a look at the command below. Both commands work based on where the cursor is at.

d3w #This will delete 3 words to the right 
d3b #This will delete 3 words to the left

15. Linux VIM command to Undo Changes

While you’re getting used to VIM, there will be times when you end up deleting something that you didn’t want to. The Ctrl-Z approach doesn’t work on VIM so how do you undo your work?

u

The letter u will automatically undo the changes just like ctrl-z would.

16. Insert Text From Different File

This is a pretty useful productivity hack. Saves time copy-pasting things from multiple files to merge between them.

So what exactly is this? It simply reads text from another file that is specified and inserts the entire text right after the cursor.

Before Retrieving Other File Linux vim commands
Before Retrieving Other File
:r <file name>
After Retrieving File Contents
After Retrieving File Contents

17. Macros in VIM

We know VIM can do a lot, but did you imagine a command-line editor to be able to record macros? Well, you better start imagining as this editor is called powerful because of the great potential this simple-looking editor has.

How do you record a macro? It’s very easy! You enter the command mode (If you’re in insert mode, just press Esc).

qb #The letter after q is just to identify the macro. Can be anything
q #Stop recording macro
@b #Replay the macro. The letter runs that specific macro

What’s the use of this macro? Anything that you can do within the VIm editor can be done with a macro. So for example you:

  • Go to the first word
  • Delete the first word
  • Replace it with something else

If you have to do this for multiple lines, all you need to do is record a macro and replay it.

18. Using Count For Commands

Almost every command that “might” need to enter multiple times, accepts a number as an argument. For example, the delete command d, the line jump command k, etc.

So if I want to delete 6 lines, I can do the d command 6 times or just say 6d.

That’s for delete, you can also do it when moving around the text. If I want to move by 3 words, all I type is 3w or 3e depending on where I want the cursor to be placed, at the start or at the end.

19. Knowing Progress Within File

If you’re scrolling through a long file and you simply need to know where you are at present, go for this command. It will give you a percentage figure of where you stand at the present moment within the file.

Ctrl G Linux vim commands
Ctrl G in VIM

As you can see in the above image, it tells me that my cursor’s current position is at the 40% mark from the end of the file. The command to do this is by typing Ctrl-G when you’re in command mode.

20. Help Modules For Linux VIM commands

I’m going to end this post by talking about the handy tool, the help command. Similar to man pages in Linux, the help command allows users to understand all the vim commands in detail. Here’s an example of what the help command shows for our delete command.

:help d
Vim Help Command
Vim Help Command

Conclusion

This is just going to be the start of your journey in vim-land. There are loads of commands and features that you’ll explore as you go along with learning VIm.

But there’s one thing that you can be assured of. If you learn VIM well enough once, it will just become second nature to you to expect those features when you start using any other editor!

References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages