vim tips and tricks

Vim Essentials: Tips and Tricks for Boosting Productivity

Do you spend a lot of time working in a command-line environment, editing and managing files using text editors? If so, then you know that having a good command over these tools can significantly increase your productivity and add value to your work. That’s where Vim comes in. If you’re new to Vim or just looking to brush up your skills, then come take a dive with me as we explore how Vim can benefit you and make your work more productive and enjoyable.

What is VIM

Vim is a powerful, free, and open-source text editor that is widely used by programmers, system administrators, and other professionals who work extensively in the command-line environment. Developed by Bram Moolenaar in the late 1980s, Vim is an enhanced version of the classic Unix text editor vi.. Vim offers a vast range of features and functionality, including support for multiple programming languages, extensive customization options, and a wide range of plugins and extensions. With Vim, you can edit text files quickly and easily, navigate your code with ease, and automate repetitive tasks using macros and scripting.

Vim – How it Helps

As someone who has worked in the industry and observed how professionals use text editors, I have come to realize that having a good command over VIM, even for basic file operations, can give individuals a significant advantage over their peers.

Many people use basic editors like Windows Notepad to edit files and transfer them to servers. Others use VIM as a basic editor without utilizing its various features, which defeats the purpose of using VIM altogether. The main reason behind this is that people do not invest the time required to learn the features and functionalities of VIM. However, the learning curve for basic VIM is not long. If you put in some effort in the beginning, and start utilizing the available features from the start, you will soon become accustomed to them.

Of course, there are many advanced editors available for advanced users, but in my opinion, for beginners, VIM is a must-tool to master as it offers several benefits, such as:

  • Vim is widely available and portable, meaning you can use it on almost any platform or operating system.
  • Vim offers advanced search and replace tools, easy navigation, and support for regular expressions, which can save you time and effort when working with large amounts of text.
  • Vim is highly customizable, so you can tailor it to your specific needs and preferences.

These benefits make VIM an essential tool for anyone who wants to be efficient and productive while working with text files. Lets know take a look at basic vim operations

Starting with VIM

The Modes

VIM provides different modes to work with, and the editor behaves differently depending on which mode you are in.

As per vimhelp.org there are 7 basic modes, the commonly used ones are described below you can read more about the other modes here vimhelp.org

Normal Mode

In normal mode you can enter all the normal editor commands , this mode is often called command mode also.

Insert Mode

This mode allows users to do text editing.

Command Line Mode

In command line mode the user can enter a line of text (command) at the bottom of the window. This allows us to enter Ex commands by pressing “:”, Search and Replace Commands by pressing “/” or “?”, Filter Commands by pressing “!”

Visual Mode

Visual mode allows you to select the desired test or section of the text for editing or manipulation, It is useful when you want you commands to only work on a specific section or block of the document.

You enter visual mode by pressing “v” more on this later in the document.

When we first run the command vim <filename>,  we start in the command mode. In this mode,  if you press h or j or k or l,  it will not insert those letter in the document, but you will be navigating left, down, up and to the right of you cursor, as your keyboard keys are mapped to commands.

Editing with VIM

on command line enter “vim <filename>” to open the file

vim filename
General syntax is vim [options] filename 
you can refer to vim documentation for better understating of options

press “i” to enter into insert mode

Tilde ("~") on any line means the line is empty of text.

To Save and Exit, press <ESC> followed by :wq!

save and exit vim
Here pressing escape takes you back into command mode. Pressing colon makes you enter into execute mode

Options to enter insert mode

Key .Description
icurrent cursor position
Ithe beginning of the line
insert text at
Key .Description
aafter cursor position
Aat the end of Line
Appends the text
Key .Description
obelow the cursor position
Oabove the cursor position
insert text at

Taking help from within VIM

:help

In the command mode enter :help to view the help menu, you can also enter :help <topic> to get help with any specific command. All documentation can be viewed by entering : help syntax.txt

vimtutor

vim by default installs with a tutorial system called vimtutor, it can help you learn the basic vim functionality hands-on, you can start the vimtutor by running it from your command line

[deb123@midas24 ~]$ vimtutor

Some ways to recover from error / incorrect inputs

Escaping out of trouble

When you first start with VIM, it is always possible to get confused, by typing wrong command, or entering the wrong mode. At all the time, you can press <ESC> key to get back to the normal mode, You may need to press it twice at times.

Undo the edits

In case you have made incorrect edits / changes to your file, you can press <ESC> to enter in the normal mode and then press “u” to undo the last change, you can press “u” multiple times to continue to undue previous edits. Once you are satisfied, you can save the file with :w so you are in the acceptable state.

Quit the file without changes

Similarly if you are unsure of changes done, but you dont want to risk it further, you can always exit the file without saving it, you can press <ESC> followed by :q! to quit the file forcefully without saving it. You can open it again to start editing as you may need.


Lets explore further

Navigation – Moving around your file

In command mode your keyboard keys are mapped to various navigation commands which enable you to move around your document with ease and efficiency.

The list is not exhaustive you can refer to vim help or documentation, there are several cheatsheets also available.

KeyDescription
hmove to the left of cursor
jmove down one line
kmove up one line
lmove to the right of the cursor
^move to the beginning of the line
$move to the end of the line
ggmove to the first line of the document
Gmove to the end of the document
55ggmove to line number 55
0 (zero)Start of line

Manipulating your text in normal mode

Deleting

KeyDescription
x / Xdelete char under the cursor / delete to the left of the cursor
s / Schange one character / change whole line
dwdelete word
Ddelete to end of line
d<motion> deletes in the direction of the motion
JDeleting a line break
cwdelete word and insert (change word)
Cdeletes line and insert
To delete a character move the cursor over it and press x,
To delete 7 characters from the beginning of the line, scroll to the line, you can press 0 to go to the beginning, Press x 7 times

Cut / Copy and Paste Operations

Key Description
dddelete the current cursor line.
yyCopy line from current cursor position.
xDelete single character / works like delete button
XWorks like Backspace button
pPaste copied line below the cursor.
PPaste copied line above the cursor.
To copy and paste or cut and paste, lines or words,

Moving your text

Take your cursor to the word or line you want copy and paste or cut and paste

This is first line

This is line 3 enter <dd>

This is line 2

Enter dd to delete the line, navigate to the new position and enter p

This is first line

This is line 2 enter <p>

End State

.This is first line

This is line 2

This is line 3

Repeating Commands

Repeating a command using a count

For all the commands executed in normal mode vim supports command repetition, where instead of entering the same command multiple times to repeat the desired action we can prefix the same with the number of repetitions, so to delete 5 lines – 5dd : open the file –> enter 4gg to go to line 4 –> enter 5dd to delete lines from 4 to 8

to move up 9 lines – 9k
to copy 5 lines – 5yy

Repeating a change or set of changes

The “.” is a very powerful command in vim, it repeats the change (or all the changes since last edit), it is super useful when you have to the same changes in different sections of the document,

For example you want to

Note : The “.” command will not work for the “u” (undo), Ctrl-R (redo) and commands that start with a colon (:).


Visual Mode

As mentioned visual mode helps to identify the area of text that needs to be modified visually, it is helpful when it is not easy to decide the area of text by say line numbers

Start Visual Mode

You start visual mode by pressing v in the normal mode and then use navigation to select the text h, j, k, l or arrow keys

vlllllllll

Selecting lines : If you want to select who lines you should start visual mode with V and can then select more lines with j or k

Vjjjjj

vim visual selection

Selecting blocks

When you are working with text arranged on rows and columns and you want to an operation on columns or group of columns you can do so by starting visual mode using <Ctrl + v>

Take your cursor to the column you want to select enter <Ctrl + v>ll

vim visual block selection

Moving to the other end of the Selection

Once you have select the a block or section of the text you may need to make changes to the other side for the selection pressing “o” or “O” can help you move from one side to the other side

Operations

Once you have made you selection you can make any changes to the selected text using commands,

In block selection mode you can remove / copy paste / cut paste data column wise

You can also do search and replace operations on the selected text as described in the following section

ChangeAction
for deletingpress d
for cut pastetake your cursor to the new position and press p
for copyingy
for copy and pastetake your cursor to the new position and press p

Search and Replace Operations

Vim provides highly effective ways to search as well as search and replace. With the use of regular expressions, and the control of where and which places to search and replace, these commands can make you a power user

Vim Simple Search

To search for a string in Vim, use the forward slash command followed by the string.

/file

Press Enter to jump to the first occurrence of the string.

To jump to the next occurrence of a string in Vim, simply press the “n” key. You can repeat this command to continue searching for the next occurrence of the same string.

If you want to search for occurrences backwards in Vim, you can use the “N” key. Pressing “N” will take you to the previous occurrence of the string you are searching for.

To search for a string from the bottom to the top of a file in Vim, you can use the question mark command followed by the string you want to search for.

?file

Once you press Enter, Vim will jump your cursor to the next occurrence of the string above your current cursor position. In this case “n” will jump to the occurrence above and “N” will reverse search for next occurrence below the current cursor position.

And Replace

To search and replace once we are at the occurrence which we want to change we can simply press “cgn” followed by the new string

Here cgn changes the next match of the search pattern,

As shown, we have first used n to move the second occurrence of the string “file”, and then entered cgn, vim automatically deletes the string file and enters insert mode,

Here we enter FILES

You can repeat the same for following occurrence by pressing <ESC> followed by n and “.” dot (refer to section : Repeating a change or set of changes above)

Once done you can save and exit the file.

Using the substitute Command

Vim Substitute command makes search and replace operations very easy, the basic syntax in normal mode is

:s/<oldstring>/<newstring>

this will replace the first occurrence of the oldstring on the line where your cursor is present.

Variations

Options syntaxDescripition
replacing all the occurrence in a single line:s/<search_term>/<replace_term>/greplace all the occurrences of the oldstring on the line
replacing all the occurrences in the entire file:%s/<search_term>/<replace_term>/g replace all the occurrences across the entire document
replacing all the occurrences in the specific lines:1,5s/<search_term>/<replace_term>/g replace all the occurrences between the lines 1 and 5, the sysntax is :start_line_number, end_line_number s/<search_term>/<replace_term>/g
search case insensitive:s/<search_term>/<replace_term>/giadding “i” make the search case insensitive
search and replace with confirmation:%<search_term>/<replace_term>/gc adding “c” will prompt you for confirmation before replacing for every occurrence
search for the whole word:%\<search_term\>/<replace_term>/gc adding <> around the word only matches the whole word and not when the string is a part of larger word, here backslash is used as n escape character
Comment lines (add # before the line) from 5 to 10::5,10s/^/#/Here ^ (caret symbol, <SHIFT>+6) represents the beginning of the line, so this replaces the beginning of the line with #,
Uncomment lines (remove # before the line) from 10 to 15::10,15s/^#//Here we search for # at the beginning of the line (^) and replace it with blank, uncommenting the line

Using regular expression

Regular expressions, also known as regex or regexp, are a pattern-matching system used to search for and manipulate text based on certain rules or patterns. Regular expressions can be used in Vim’s substitute command to replace all occurrences of a pattern in a file, By using regular expressions, you can perform complex search and replace operations that are difficult or impossible to achieve with simple string matching. Here we look at some common regex examples, refer here for detailed regex usage

remove all blank line:%s/^$//gHere ^ matches the beginning and $ matches the end of the line, so it will match any line were there is nothing between beginning and end = blank line and replace it with nothing, hence removing it
Replace all digits with “x”::%s/\d/x/gHere \d matches all the digits
Replace all words starting with “a” and ending with “e” with “replacement”::%s/a\w*e/replacement/ghere \w matches any word character (alphabets, digits, underscore) 
If we only had to match words with text we could have used \a
Insert a new line after every occurrence of a semicolon::%s/;/;\r/gHere we are replacing ; with ; followed by \r
\r is the new line
Eg. you have a list of statements separated by semicolons and you want to split them into individual lines
remove trailing whitespace characters across all lines in the file:%s/\s\+$//gHere \s matches match space and tab characters, \+ match one or more times,
replace digits in a pattern with X (hide them for security purposes):%s/\d{3}-\d{2}-\d{4}/XXX-XX-XXXX/gHere \d matches digits {3} matches three occurrences for digit and so on for each block, so only those patterns will be impacted where we have 3digits-2digits-4digits
To match multiple words and replace them with a single word::%s/\(word1\|word2\|word3\)/replacement_word/gHere \ is the escape character, so substitute command consider ( and | as a special character, and | provides OR functionality
To find and fix formatting errors in a list of email addresses::%s/\(\w\+\) *@ *\(.\+\)/\1@\2/gHere
\(\w\+\) matches one or more word characters (letters, digits, or underscores) and saves the match as a “capture group” for later use. The parentheses around \w\+ create the capture group.
*@ * matches zero or more spaces (including none) around the “@” symbol and any number of spaces after it.
\1 backreference to the first capture group
\2 backreference to the second capture group

Working with Multiple Files

Vim allows you to work with multiple files in several ways

Opening multiple files

To open multiple files in Vim, simply append all filenames as command line arguments like this:

vim /path/to/file1 /path/to/file2 /path/to/file3

Once Vim is opened, the first file will be displayed. You can navigate between the files using these Vim commands:

:n(ext) # jumps to the next file

:prev # jumps to the previous file

However, it might be difficult to keep track of which files are open, VIM provides another way to open the files in different tabs

Opening multiple files in tabs

Vim has tabs support since version 7.0, making it easy to work with multiple files.

To open multiple files in separate tabs, use the -p CLI flag followed by the filenames:

vim -p /path/to/file1 /path/to/file2 /path/to/file3

This opens Vim with all files opened in tabs, and the tab bar is displayed on top of the editor window.

To open a new tab while already in Vim’s normal mode, use the command

:tabe [/path/to/file]

You can then switch between tabs using

  • :gt OR :tabn[ext] to jump to the next tab,
  • :gT or :tabp[revious] to jump to the previous tab,

or n followed by gt to jump to a specific tab (where n is the tab index starting at 1).

To close the current tab, use :tabc[lose] command-line command.

Tabs make it easier to manage multiple files in Vim, but you may want to compare the files and edit them in the same window, vim provides several options for that as well

Comparing and editing files side by side

To view multiple files in a single Vim workspace, you can use the built-in split feature. In Vim, you can split the window either horizontally or vertically by using the following command-line commands:

  • :sp[lit] [/path/to/file] # splits the window horizontally [and opens the file]
  • :vs[plit] [/path/to/file] # splits the window vertically [and opens the file]

After splitting the window, you’ll have multiple windows open in Vim. You can navigate between the windows and perform various actions by using the following commands or keystrokes while in normal mode:

  • Jumping between windows is Ctrl-w <cursor keys>, Ctrl-w [hjkl], or Ctrl-w Ctrl-[hjkl]
  • Jumping to the next window is Ctrl-w w or Ctrl-w Ctrl-w
  • Jumping to the previous window is Ctrl-w W
  • Jumping to the last accessed window is Ctrl-w p or Ctrl-w Ctrl-p
  • Closing the current window is Ctrl-w c or :clo[se] Making the current window the only one and closing all other windows is Ctrl-w o or :on[ly]

Command Line Mode – Summary

Esc: Press key to change the mode to Execute mode.
:q : Quit file.
:w : Write changes to file.
:wq : Save & Quit.
:x : Save & Quit.
:q! : Quit forcefully
:wq! : Save & Exit forcefully.
:| : Go to first line of the file.
:set nu: Set the numbers to line.
:set nonu: Remove numbers from lines.
:<Specific Line Number>: Specified Line Number.
:r /root/test : Copy the content of test file in cursor current position.
:r !date : The command output will paste in current cursor position.
:!ls - Execute shell command "ls"

Lets look Deeper

Configuring your VIM

VIM can be configured using .vimrc file which for Centos / RHEL the system wide configuration file for Vim is  /etc/vimrc., where it is at  /etc/vim/vimrc.local file on Ubuntu/Debian based operating system

You can directly edit the above files to make necessary configuration changes for vim, but then those will be applicable at system level, for user level you can create a .vimrc file for your login user with the following command:

touch ~/.vimrc

Then, open .vimrc file with vim with the following command:

vim ~/.vimrc

Here you can define your keybindings, set themes, install plugins etc.

Showing Line Numbers

if you want to show the line number by default every time you open the file using vim you can simply add the entry “set nu” in the file, now every time you will open any file using vim, the line numbers will be there by default

You can explore more such option here

Configure Simple Mapping

A mapping maps a key stroke to a set of vim commands, if you use a set of key commands often, then it is a good idea to create a mapping for the same, this will help you complete you task faster

Map x to dd

Normally x deletes a single chracter if we make the following entry in ~/.vimrc file, when you press x it will delete the line instead

:map x dd

Map a key to set of commands

If you want to add curly brackets around a word say “customername”. You can make the following entry

:map <F3> i{<Esc>ea}<Esc>

here map maps “<F3>” with a set of commands – “i” enter into insert mode, enter { , <ESC> to enter normal mode, “e” to reach end of the word, “a” to append (insert mode), and enter }.

Once set the entire operation of changing customername to {customername} can be achieved with single key click on F3

Configuring Plugins

Vim offers a way to enhance its functionality by utilizing “plugins”. There are primarily two methods to install Vim plugins.

  • The first and easiest method is by using a plugin manager. This can be likened to a package manager, but for Vim.
  • The second method is by manually cloning repositories in specific directories.

Manually installing plugins is not recommended as it can become confusing and complicated when dealing with a large number of plugins. Additionally, there is a risk of mistakenly cloning the plugin in the wrong directory, which can potentially cause issues with your Vim plugins.

You can refer to How to Extend Vim’s Functionality by Adding Plugins to understand more about adding plugins.

Conclusion

In conclusion, Vim is a powerful and versatile text editor that can significantly enhance your productivity once you become familiar with its features and capabilities. It offers several advantages over other text editors, such as its speed, efficiency, and extensibility through the use of plugins. Vim’s modal editing and command-line interface may require some time to get used to, but once you do, you can work with unprecedented speed and accuracy. With this guide, you should be equipped with the knowledge necessary to start using Vim effectively and efficiently for all your text editing needs.

.

.

Nikhil Kumar Ahluwalia
Founder Upspir

Nikhil has more than 16 years of industry experience. Prior to founding Upspir, he served as the Vice President of Support, Services, and Delivery at Ameyo/Exotel, where he gained extensive experience in managing and leading technical support and delivery teams. With Upspir, Nikhil aims to take his passion for developing and mentoring people to the next level by sharing his experiences and knowledge with those who want to build their careers in the tech support domain.

Add a Comment

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