vim – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Fri, 19 Feb 2021 02:14:20 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 How to delete lines in Vi/Vim? https://linuxhint.com/delete-lines-in-vi-vim/ Wed, 17 Feb 2021 11:08:29 +0000 https://linuxhint.com/?p=90094 Vim previously known as Vi, stands for “Vi IMproved”, is a multi-purpose text editor that is compatible with all UNIX based operating systems like Linux and macOS. Vim can be used for various purposes such as creating, editing text, and/or computer program files.

You often need to delete one or more lines while editing text files in Vim editor, and unlike any other text editor, it allows you to edit your files quite efficiently. This guide will focus on how to edit and delete lines from your files in the Vim editor.

If you don’t have Vim editor, then try installing it using:

$ sudo apt install vim

line/1%20copy.png

Vim lets you delete lines in various ways, for instance, you can delete all lines at once, multiple lines, and even lines by custom pattern/word. Let’s check all of these methods:

Deleting a single line in Vim editor:

The process of deleting only one line in Vim is simple. To delete a line, follow the steps below:

  1. First, bring your cursor to the line you want to delete.
  2. Press the “Esc” key to change the mode.
  3. Now type, “:d”, and press “Enter” to delete the line or quickly press “dd”.

I am removing line number 3 for demonstration. See the images below:

line/multi%201.png

How to delete all lines in Vim editor:

To delete all the lines at once, follow the process below:

  1. First, hit the “Esc” button to switch mode from insert to edit.
  2. Now type, “:%d”, and hit “Enter” to remove all the lines.

line/multi%202.png

How to delete a range of lines in Vim editor:

Vim also allows to select a range of lines and then delete them. The syntax is given below:

:[Starting Line Number],[Ending Line Number]d

For instance, if you want to delete lines from line number 5 to line number 7, then simply follow the below-mentioned process:

  1. Change the mode using the “Esc” key if it is in insert mode.
  2. Type “:5,7d” and hit “Enter”, line number 5,6, and 7 will be removed.

line/multi%203.png

If you want to delete all the lines before the current line, then use “:1,-1d“. For example, if you want to delete lines from line number 5 to all lines before this lines, then use the following method:

  1. Bring your cursor to line number 5.
  2. Press the “Esc” key and type “:1,-1d”, and then press “Enter”.

line/multi%204.png

To delete all line after line number 5, follow the below-mentioned process:

  1. Bring the cursor to line number 5.
  2. Press the “Esc” key and type “:+1,$d”, then press “Enter”, the lines that are below line number 5 will be removed.

line/multi%205.png

How to delete multiple lines in Vim editor:

In this method, we will learn the process of removing multiple consecutive lines. Simply follow the process:

  1. Bring the cursor to a line from where you want to start deleting.
  2. If you want to remove 4 consecutive lines, then simply type “4dd”.

line/multi%2010.png

In the above image, the cursor is on line 2, therefore lines 3,4,5, and 6 have been removed.

How to delete the line with a custom pattern in Vim editor:

Another feature of Vim editor is that it allows you to delete the line with a given condition, the syntax is given below:

:g /<WORD>/d

Replace “<WORD>” with the word of the line you want to delete. For example, if you want to delete lines with the word “Linux”, then use the following approach:

  1. Press the “Esc” key to change mode.
  2. Type “:g /linux/d”, then hit “Enter”.

The lines containing the “Linux” word will be deleted.

line/multi%206.png

Similarly, if you want to delete all lines, except lines containing the “Linux” word, then use

“:g! /linux/d”:

line/multi%207.png

To delete lines that begin with a specific letter, use

“:g /^T/d” ;

line/multi%208.png

To remove all blank lines in your text file or code, use

“:g /^$/d”:

line/multi%209.png

Conclusion:

Vim is one of the well-liked text editors among Linux users and developers. It is a free, well documented, and customizable text editor. In this guide, we learned how to edit text and code in Vim. We thoroughly discussed various methods and approaches to delete a line, multiple lines, and even lines with a specified word. Vim is a versatile editor that has a lot more features to uncover.

]]>
How to Search in Vim https://linuxhint.com/search-in-vim/ Sat, 13 Feb 2021 05:42:04 +0000 https://linuxhint.com/?p=89808

Vim is a widely used, light-weight, free, multi-platform text and code editor. It is very popular among developers because of its efficiency and ease of use. Though Vim is a simple text editor, it still needs some time to learn for advanced usage.

Learning the basics of Vim is very handy, therefore in this guide, we are going to focus on Vim editor’s search feature. Searching for some specific text (word/string) is one of the very common tasks when working with large files.

Let’s understand the search feature of Vim from basic searching to advance search techniques. Make sure you are in command mode before searching for something.

How to Do a Basic Search in Vim/Vi?

There are a couple of methods to search for a specific pattern in Vim:

  1. Forward searching
  2. Backward searching

Any pattern word can be searched in a backward or forward direction from the cursor position. In Vim editor, the search is case sensitive, for example, the “LINUX” and “Linux” will be searched differently. Therefore, there are various approaches to ignore case sensitivity. You can use “:set ignorecase” or “:set ic”. Another way to ignore case sensitivity is by simply adding “\c” with the search pattern: “/linux\c” and for capital words use “\C”.

1: Forward Searching

To begin a basic search, switch the mode if it is still in insert mode by pressing the “Esc” button. Then use the forward-slash “/” to quickly search text. For example, if you are looking for “Linux” in a file, then use “/Linux”, as shown in the images below:


The editor will highlight the first word that comes after the current cursor position. The search command will search the pattern, not the word. For instance, if you type “famous” after forward-slash, the editor will search all the words with the letters “famous” even if it is “infamous”, as demonstrated in the following image:

  • Use “n” to jump to the next similar word
  • Use “N” to go back to the previous word

2: Backward Searching

For backward searching, the process is the same, simply use “?” with the search string in place of forward-slash. The search will begin from the current position of the cursor, as shown in the following image:


Similarly, to jump to the next occurrence, use “n” and “N” in opposite direction.

How to search for a specific word in Vim?

To search a specific word in Vim, firstly, move the cursor to the word you want to search, now press the “Esc” button to switch mode, and then “*” for the next instance of the same word and “#” for the previous instance of the word.

How to search the entire word in Vim?

The procedure of searching the entire word in Vim is a bit different, the syntax is given below:

/\<WORD\>

Vim will highlight the first word in the file.

How to Highlight Search Results in Vim?

Another important feature of Vim is highlighting the search results. To enable this feature, use “:set hlsearch”, and to disable it, use “:set !hlsearch”.

Conclusion

Vim is a lightweight text editor with numerous features that is very popular among developers. In this guide, we learned another key feature of the Vim editor. We also learned its basic forward and backward search, methods of finding a specific word, and running commands to highlight the search results and ignoring case–sensitivity while searching a pattern.

]]>
Vim Tutorial https://linuxhint.com/vim-tutorial/ Sun, 13 Dec 2020 00:06:18 +0000 https://linuxhint.com/?p=81083 Vim means Vi Improved. It is an efficient text editor especially developed for Linux users. This editor is mainly used to edit or create different types of files, e.g., python/perl/.html/ .php. In this article, you will learn about how to install Vim on your Linux system, as well as different operations and functions that can be performed by Vim. Follow the cited below steps to get hands-on Vim.

Install Vim

Remove Preferences

First of all, you have to remove the preferences for the smooth installation of Vim using the rm command:

$ sudo rm /etc/apt/preferences.d/nosnap.pref

Update Linux System

Update your Linux system using the apt command:

$ sudo apt update

Install Vim

You can install Vim on your Linux system using two methods. The first one is the direct installation using the apt-get command, and the other is using the Snap store utility. If you want to install Vim using the Snap store, you have to install the Snap utility first using the apt command:

$ sudo apt install snapd


After that, install Vim editor beta using the snap command:

$ sudo snap install vim-editor --beta


If you want to install Vim editor using the direct command, you can also do that using the apt-get command, as follows:

$ sudo apt-get install vim


You will be asked to confirm this action to install Vim on your Linux system. To complete the installation, tap y or Y to continue.


After some time, your Vim editor will be installed and ready to use. You can check the Vim version and other information regarding Vim by using the version command:

$ vim --version

Launch Vim

To start Vim on Linux, try the following command:

$ vim


You will see a screen that will be popped up, similar to the screen shown in the below image.

Vim Modes

Vim comprises two modes: Normal mode and Insert mode. Eventually, it has another three different modes as well. Every mode has a lot of supported commands, which we will discuss later. Now, have a look at all modes of Vim, as listed below:

Normal Mode
Your very first Vim screen is your normal mode when you first launch Vim. You cannot do any insertion but can move around using some cursor keys from alphabets. You can switch to normal mode by hitting the Esc key while you are in another mode.

Insert Mode
You can add any text, same as any text editor in insert mode. You can switch to insert mode by tapping the “I” alphabet from the keyboard while you are in normal mode.

Visual Mode
Visual mode is a little appealing and attractive as compared to other modes of Vim. Any action performed in this mode is a little highlighted. You can move to Visual mode by pressing the v alphabet when you are currently in normal mode.

Command Mode
This mode of Vim is more functional than other modes. To take yourself to command mode press “:” when you are in normal mode. You can add any command after “:” sign.

Replace Mode
The Replace mode enables you to replace or overwrite the original text by typing over it. To move in Replace mode, press capital R while you are in normal mode.

Editing a File

Create a new file with the name Test.html in your home directory and open it using the following command via Vim:

$ vim Test.html


You will see the below screen after executing the command. This is your normal mode in Vim.


You should be in the Insert mode if you want to edit your file Test.html. Press “I” from your keyboard, and you will be in your Insert mode. Add some text to your file, as shown in the image below.

Saving your Work

Now, if you want to save your edited file, you have to be in Normal mode. So, tap Esc to jump into the Normal mode. Then, add “:w” or “:wq” in command mode, and press Enter. Your file has been saved. Single “:w” represents that the text is saved. On the other hand, “:wq” means that the text has been saved, and the editor has quitted as well.

Exiting the Editor

By simply using the “:wq” command, you can save and quit at the same time.


Use the “:x” command after saving the file with the “:w” command to exit the editor.


The command “q!” will quit the editor without saving the changes.

Page Up, Page Down

Make sure to be in the Normal mode to perform up and down operations. You can move the file page up and down using the simple keys as follows:

  • Press k to move up on the page
  • Press j to move down on the page

The image shows that the cursor is at the first line and on the first word as “1,1” by using key k.


This image shows that the cursor is at the last line and on the first word as “5,1” by using key j.

Go to the Beginning, Go to the End of the File

You can directly go to the beginning of the file, as well as the end of the file, using very simple keys. Firstly, make sure to be in Normal mode using the Esc key.

  • Press gg to go at beginning of the file
  • Press capital G to go at end of the file

In the below image, it is clear that the cursor is at top of the file at line 1 using the gg command.


You can see that the cursor is on the 10th line, which is the end of the file using the G key.

Show Line Numbers

Line numbers can make your work easy and your Vim appealing. If you want your Vim to show line numbers at the start of every line, you can do that very simply. Go to the normal mode or command mode by hitting the Esc key. Add any of the following commands there and tap Enter:

$ :set number
$ :set number!
$ :set nu!


Now, you can see we have line numbers exposed at the beginning of each line.

Word Count

You can also count the number of total words in the file. Press Esc to move into command mode. If you want to check the columns, lines, word count, and byte count, do:

Press g then Ctrl+g


You can also use another command to only show the word count of the file, as shown below:

$ :w !wcw

You have to press Enter to jump into normal mode again.

Selecting Text

There are two ways to select text in Vim, as listed below:

Character-wise selection: small v

Line-wise selection: capital V

If you want a character-wise selection of the text, you have to Press a small v from your keyboard. It will bring you to regular Visual mode. You can select the text using your mouse cursor or using h, j, k, l keys for the expansion of selection.


You can also do a line-wise selection of the text by only pressing the capital V key when you are in the normal mode. It will bring you to Visual Line mode. You can select the text by just moving line-wise up and down using k and j keys, respectively.

Delete Text

You can delete text from the file using the visual mode.

Delete Single Line
To delete a single line from the file, go to Visual Line mode by pressing capital V. Before deleting the text, you can see the text line selected.


Now, press d from the keyboard. The lines selected have been deleted from the text.

Delete Single Word
You can easily delete a word by using a simple command. Move to the normal mode by hitting the Esc key. Take your mouse cursor at the word you want to delete. Then, press dw from the keyboard. You can see I have deleted a word I from the fourth line using this command.


Delete Multiple Lines
You can delete multiple lines using a single command. Press Esc to jump on Normal mode. Then, move your cursor to the line you wish to remove.

Press [#]dd or d[#]d to remove the lines

[#] signifies the total number of lines you wish to delete from the particular line. For example, I put my cursor on the first line, as shown in the image below.

When I pressed 2dd from the keyboard, the first two lines have been deleted, as shown in the illustration.


Delete Specified Range Lines
You can also delete lines from the indicated range. For this determination, you have to put the starting line and the ending line in command mode. You can see I have chosen the first line to be deleted as line 2 and the last line to be deleted as the 4th line:

:[from],[to]d


You can see the lines 2, 3, and 4 have been deleted from the text file. Total 3 lines have been deleted and left 2 lines.


Delete all Lines
You can delete all lines by simply using one command in command mode:

:%d

You can see we have a total of five lines before the execution of the command.


When I execute the command “:%d”, all the lines have been deleted, as shown in the image.

Delete to End of Line, Delete to End of File

You can delete text from the start to the end of the line and the end of the file when you are in Normal mode. Press Esc to move into normal mode.

  • Press d$: delete to the end of the line
  • Press :.,$d : delete to end of the file

Initially, we have 10 lines in your file. The cursor is one first word of the first line.


When I tap d$ from the keyboard, you can see the first line text has been deleted to the end of the line.


Now, press:” to move into command mode while cursor on line 5. Type the “:.,$d” command in this mode, as shown in the following illustration.


Press Enter, and you will see all the text to the end of the file from line 6 has been deleted.

Undo, Redo

Undo and Redo are different operations that can act a little differently. You can use Undo and Redo in Vim using simple keys as follows:

  • u : can undo your last modification
  • Ctrl-r : Redo can undo the undo

In the previous phase, we have deleted the text to the end of the file. Now, we will use Undo and Redo commands to undo our actions. Below is the last modification we have just done.


Now, when I used the key u in the mode, all the changes have been undone. 6 lines have been added again, which were deleted, as shown in this image.


And when I pressed Ctrl+r, the entire last undo has been discarded, and you can see the old output of the text file in the image.

Searching

To perform the search operation, you must be in normal mode. So, press the Esc key from the keyboard to move into normal mode. You can search a single alphabet, word, or string in the text lines. Use the following keys to perform a search in the text files in Vim:

  • Press / : to perform a forward search
  • Press ? : to perform a backward search
  • Press n : to search next occurrence in forwarding direction
  • Press N : to search next occurrence in the backward direction

Move your cursor on the first line at the first word. Now, press / and the pattern, word, or alphabet you want to search, e.g., I have added /am, and press Enter. It will highlight the pattern I have been searching for, as shown below.


Now, press small n to search the same pattern in the forwarding direction and capital N to search in the backward direction, as shown in the corresponding image.


I have used “?” to search in the opposite direction with another pattern, as shown in the illustration.


Press small n to move in a forwarding direction, which is its opposite direction, and capital N to move in a backward direction, which is basically our forward direction.

Find and Replace (with or without confirmation)

You can search for the pattern or word and can replace with another pattern using the simple command as follows:

  • :%s/search-string/replace-string/g to search+replace in the current line without confirmation
  • :%s/search-string/replace-string/g to search+replace globally in the file without confirmation
  • :%s/search-string/replace-string/gc to search+replace globally with a confirmation

You can see the text before the change or use of the search and replace command without confirmation. Press Enter to continue.


Here, you can see, the pattern “am” is replaced by “was” without taking confirmation from the user.


The text file before using the search and replace command with the confirmation of the user.


When you press Enter, it will ask you to confirm the replacement of patterns. I have answered every question to y, as shown in the image.


You can see every word “am” is replaced by the word “are”.

Regex Substitution

You can perform regular expression substitution using the same simple command below:

:%s/word-to-be-replaced/expression/g

You can replace any word using this command with regular expressions, as shown below.


You can see the regular expression has been substituted at the end of every line.


You can also replace any word with any regular expression.


You can see a change has been made.

Setting up .vimrc file

To open the configuration file in Vim, use any one of the following commands:

$ sudo vim /etc/vim/vimrc.local incase of Ubuntu/Debian

$ sudo vim /etc/vimrc in case of Centos 8/RHEL 8


Use the appended command to create a .vimrc file:

$ touch ~/.vimrc


Open the .vimrc file using the below command:

$ vim ~/.vimrc

Syntax Highlighting

Open the .vimrc file using the vim command. Then, insert the cited text into the file.

syntax on

You can see the text highlight has been turned on in the image below.

vimdiff

To show differences between the two files, we will be using the vimdiff command:

$ vimdiff file1 file2


You can see the comparison between two files, Test.html and Text.html below.

Convert Tabs to Spaces

Open your .vimrc file, and then add the following lines to it. After that, add the retab command.

  • set expandtab
  • set tabstop=2
  • set shiftwidth=3
  • :retab

Whenever you press the tab from the keyboard, it will convert it into spaces as you have given in the commands.

Default Tab Space Configuration

Open your .vimrc file, then add the following lines to it. After that, add the retab command. This is the default tab space configuration.

  • set expandtab
  • set tabstop=4
  • set shiftwidth=4
  • :retab

Whenever you press the tab from the keyboard, it will shift the cursor to 4 spaces ahead.

Edit Multiple Files

To edit multiple files at the same, you have to open files using the vim command:

$ sudo file1 file2

Now, I have opened the two files in Vim. It will open the first file that has been added in the terminal first, e.g., Test.html. The file can be amended using any mode.


Now to switch to another file, add the command below:

  • :n to switch to the next file.
  • :N to switch to the previous document.

Conclusion

In this guide, we elaborated on the basic features of Vim. Upon following all the above tutorial, you will be able to understand the basic functionality of Vim.

]]>
Toggling Line Numbers On/Off in the vi Text Editor https://linuxhint.com/vi_toggle_line_numbers/ Thu, 22 Oct 2020 04:24:10 +0000 https://linuxhint.com/?p=72651 The line numbers shown in a text editor can greatly enhance a programmer’s experience writing and reading code. There are several text editors available for the Linux operating system, including the popular and powerful vi text editor, and these editors can be used to create and modify various file types.

The vi editor provides three different types of line numbers: absolute, relative, and a hybrid combining features of absolute and relative. In this article, we will discuss method that can be used to change the line number type shown in the vi text editor.

Note: Linux Mint 20 is used to demonstrate all the methods discussed below.

Showing Absolute Line Numbers

Absolute (or regular) line numbers are the line numbers preferred by most users. To display the absolute line numbers in vi, take the following steps:

Launch the terminal.


Open any file that can be edited with vi text editor by running the command `$ sudo vi [file name]` in the terminal, as follows:


Press the Esc key to enter Command Mode .

This step is important because, while the text editor has several modes of operation, for our present goal, we have to be in Command Mode.

Run the command `:set number`, as follows.


When you hit Enter to execute this command, the absolute line numbers will appear at the beginning of each line of your file, as shown below:

Hiding Absolute Line Numbers

You can hide the absolute line numbers in vi by taking the following steps:

  • Once you have a file opened in vi, enter Command Mode by pressing the Esc key
  • Execute the command `:set nonumber`.


After executing this command, the absolute line numbers will no longer be shown, as shown in the image below:

Showing Relative Line Numbers

For relative line numbers, the line in the file to which your cursor is currently pointing is assigned the number zero, and all other line numbers are calculated relative to that line.

You can show relative line numbers in vi by taking the following the steps:

  • Once you have a file opened in vi, press the Esc key to enter Command Mode.
  • Execute the following command `:set relativenumber`.


When you execute this command, relative line numbers will appear at the beginning of every line of your file. In our case, because the cursor was pointing to the third line of the file, the third line is assigned a value of 0, and the other line numbers are calculated accordingly, as shown below:

Hiding Relative Line Numbers

To hide the relative line numbers, you can take the following steps:

  • Once you have a file opened in vi, press the Esc key to enter Command Mode
  • Execute the command `:set norelativenumber`.


When you execute this command, the relative line numbers have be removed, as shown in the image below:

Showing Hybrid Line Numbers

For hybrid line numbers, the line to which your cursor is pointing is assigned its actual absolute line number, but all other line numbers are relative values.

We can show hybrid line numbers by taking the following the steps:

  • Once you have a file opened in vi, press the Esc key to enter Command Mode
  • Execute the command `:set number relativenumber`.


When this command is executed, hybrid line numbers will be shown at the beginning of every line of the file. In our case, because the cursor was pointing to the third line of the file, the number 3 was assigned to the third line, and all other line numbers were calculated accordingly, as shown below:

Hiding Hybrid Line Numbers

To hide hybrid line numbers, you can take the following steps:

  • Once you have a file opened in vi, press the Esc key to enter Command Mode
  • Execute the command `:set nonumber norelativenumber`.


When you execute this command, the hybrid line numbers will be removed, as shown in the image below:

Conclusion

The commands discussed in this article can be easily used to toggle absolute, relative, and hybrid line numbers on/off in the vi text editor.

]]>
Vim Games – Games You Can Play with the Vim Editor https://linuxhint.com/vim_editor_games/ Sun, 26 Jul 2020 04:58:48 +0000 https://linuxhint.com/?p=63946 Among all the text editors out there, Vim (stands for VI improved) is one of the elites. Vim is quite a popular text editor and is available on almost all platforms (Windows, Linux, macOS, BSD, and others), but is most popular on Linux. This text editor comes with tons of features and is a clear rival to paid text editors.

Despite being incredibly powerful, Vim is famous (infamous, to be exact) for having a steep learning curve, especially for novice users. There are numerous commands and shortcuts that Vim comes with by default. Keeping track of these commands can prove to be a difficult task.

This is where Vim games come in. These are fun games designed to teach Vim to anyone, especially novice users. Even if you are a Vim master, you can check these games out just for fun. Practicing the basics never hurts!

Vim Games

As mentioned earlier, Vim is known for its high learning curve. To make it easier to learn how to use this program, there are numerous guides and tutorials all over the internet to learn Vim. Vim games share the same goal. Here, I have listed some of the games I personally like and enjoy. There are lots of them out there, so feel free to explore by yourself.

Some of these games are apps that you can install on your system, while others are browser games.

Vim Snake

We all have played the classic snake game before. Control the snake with direction keys, eat food, and survive for as long as possible. Vim Snake is a browser game with this exact description. However, the main trick lies in the direction keys.

Generally, on computers, we are used to using the arrow keys to navigate through the text. Vim also supports the arrow keys. However, the primary navigation keys of Vim are h (navigate left), j (navigate downwards), k (navigate upwards), and l (navigate right).

You can use this Snake game to train yourself on Vim navigation until it becomes second nature!

PacVim

PacVim is a text-based game for learning Vim commands. As you may infer from the name, this game is inspired by the legendary Pacman game. This game is available on Linux and macOS. Check out PacVim on GitHub.

PacVim requires the GNU Curses library to run. Depending on your distro, the package name and installation method may differ. Run the appropriate command according to your distro.

For Debian/Ubuntu, run the following command.

$ sudo apt install libncurses5-dev

For Fedora, run the following command.

$ sudo dnf install ncurses-devel

For CentOS/RHEL, run the following command.

$ sudo yum install ncurses-devel

Once the dependency is installed, it is now time to download and install PacVim.

$ git clone https://github.com/jmoon018/PacVim.git

$ cd PacVim && sudo make install

Once the installation is complete, launch the game.

$ pacvim

You can also decide the level and difficulty in this game. There are two difficulty levels: n (stands for normal) and h (stands for hard).

$ pacvim <level> <difficulty>

Vim Genius

Vim Genius is a web-based Vim game that you can play in your browser of choice. Vim Genius is designed to be similar to vimtutor, the built-in Vim tutorial program that comes with Vim by default.

I recommend making an account with Vim Genius first so that your progress is saved. The levels will start with a list of commands that you must remember to clear the hurdle. Only then will you proceed to the next stage.

If you are a beginner, Vim Genius is a great place to start learning Vim.

Vim Adventures

Vim Adventures is my most favorite game on the list so far. Vim Adventures is an interesting, indie-style game where you take a journey through a mysterious land to fulfill a prophecy. In your journey, you will encounter various hurdles that you must pass through using the knowledge and applications of various Vim concepts.

You must apply various Vim commands and shortcuts to progress through the game. With this game, you can enjoy the interactive and slick gameplay, interesting story, and the delight of learning, all at the same time!

Openvim

Openvim is an online interactive tutorial where you can learn and practice various aspects of Vim. This game is a great place to start learning about the basics of Vim and the most common shortcuts used in Vim.

You can also practice your Vim knowledge in the practice section.

Vim Tutor

Vim Tutor is the built-in Vim tutorial app that comes with Vim. In this app, there are interactive on-screen instructions that you will follow. Vim Tutor will teach you enough to use Vim on a daily basis. However, if you wish to master Vim, you should check out some additional resources.

Vim Tutor is an all-in-one tool to learn and master Vim. To launch the Vim Tutor, run the following command.

$ vimtutor

Final Thoughts

In the article above, some of the best Vim games that you can play to learn and master Vim have been listed. Interested in having fun with the CLI? Check out some of the best command-line games on Linux.

Enjoy!

]]>
Best Ways to Add Color to Your Vim Editing Experience https://linuxhint.com/vim_color_scheme/ Wed, 22 Jul 2020 17:30:56 +0000 https://linuxhint.com/?p=63616 Vim is, without question, one of the finest text editors. It’s a CLI text editor that comes with numerous features. It’s free and open-source software available for all the popular platforms. Vim is notorious for its learning curve. However, once mastered, Vim can do wonders.

Vim is a CLI text editor. Most of the time, it’s the basic black and white window. How about spicing your Vim experience? Let’s check out the best ways to add color to Vim.

Vim color scheme

Color schemes are one of the simplest ways to make a text editing experience dramatically better, especially if you’re working with codes. It improves visual clarity, allowing you to focus on the important part. For some, the appropriate color scheme can reduce eye strain. It also provides good aesthetics to the editor.

That’s why almost all the text editors support some form of theme. In the case of Vim, there are tons of color schemes out there. It comes with a number of color schemes by default. If you’re not satisfied, you can add more through the Vim plugin system.

Vim color schemes

Vim comes with a handful of awesome themes by default. To change the color scheme, use the following command. For example, I’ll be using the XML code found here.

$ :colorscheme <color_scheme>

If you don’t know the exact name of the color scheme, pressing Tab will reveal all the available ones.

Let’s try out the “desert” color scheme.

$ :colorscheme desert

To check what color scheme Vim is currently using, run this command.

$ :colorscheme

Like many other Vim commands, the color command also has an acronym.

$ :color

$ :colo

Now, this change won’t be permanent. Once you exit Vim, it’ll revert back to the default color scheme. You can define the default color scheme at the vimrc file. It’s the Vim configuration file that Vim loads every time it starts.

Open up the vimrc file. If you don’t have one, the following command will create one by default. My vimrc is a sample one from Vim fandom.

$ vim ~/.vimrc

At the end of the file, add the following line.

$ colo <color_scheme_name>

To take the change into effect, restart Vim. If that’s not an option, then reload the vimrc file.

$ :source ~/.vimrc

Vim additional color schemes

Vim comes with a handful of color schemes by default. There are tons of color schemes out there to be explored. In this section, let’s check out how you can add your favourite color scheme to the editor.

All the Vim color schemes (and plugins) come in the form of a .vim (vimscript) file. The same goes for Vim color schemes. The default Vim color schemes are located at the following directory.

$ ls /usr/share/vim/vim80/colors | grep vim

As for the Vim themes we’re going to add, they’ll be located under the ~/.vim directory. It’s user-specific; one user can’t use other users’ Vim color schemes. Whenever Vim starts, it looks for the directory and its content. If it doesn’t exist, nothing is performed. If it exists and there’s file according to the structure, then Vim will follow those directives.

Generally, this directory doesn’t exist. Run the command to create the directory.

$ mkdir -v ~/.vim

To store the color schemes, we’ll be needing the colors sub-directory.

$ mkdir -v ~/.vim/colors

It’s time to grab your favourite Vim color scheme. There’s a dedicated website that hosts a ton of Vim color schemes with preview. Check out Vim Colors.

In this example, let’s install the miramare dark theme. Download the color scheme from GitHub.

$ git clone https://github.com/franbach/miramare.git

Now, move the miramare.vim file to the “~/.vim/colors” directory.

$ mv -v /<path_to_miramare_git_directory>
/colors/miramare.vim ~/.vim/colors

Voila! The color scheme is ready to use! It should now appear on the list of available color schemes.

$ :colo miramare

To make the newly-added color scheme the default, modify the vimrc file accordingly.

Final thoughts

This is just the manual way of adding Vim color schemes. It’s also possible to use a Vim plugin manager to add the Vim color scheme for you. It’s a far better approach as it’ll also keep the color scheme (and other plugins) updated. Check out how to enjoy Vim plugins. Vim macro is also a great way to improvise your editing experience. Check out Vim macro tutorial.

Enjoy!

]]>
How to Customize VIM Color Schemes and Syntax Highlighting https://linuxhint.com/vim_customize-_color_schemes_syntax_highlighting/ Mon, 20 Jul 2020 05:02:20 +0000 https://linuxhint.com/?p=63394 Vim is a well-known text editor used in the Linux operating system. You can work with most Linux utilities by making use of the command-line interface (CLI). However, at times, this interface gets quite dull and boring. Like any other text editor, Vim provides you with various customization options with which you can make this program look more attractive and eye-catching. This article will talk about some of the methods you can use to customize Vim color schemes and syntax highlighting in Ubuntu 20.04.

To customize VIM color schemes and syntax highlighting in Ubuntu 20.04, simply follow the methods explained below.

Customizing Color Schemes in Vim

To customize color schemes in Vim, follow the steps below:

1. First, launch the terminal in Ubuntu 20.04. Press Ctrl+ T or click on the Activities icon located in your desktop. Next, type ‘terminal’ in the search bar that appears, and double click on the search results to open the terminal. Alternatively, you may also right-click on your desktop to launch a pop-up menu, from which you will select the Open Terminal As soon as you do this, the terminal window will appear on your screen, as shown in the image below:

2. Type the command below in your terminal, followed by pressing the Enter key:

vim

Running this command will open the Vim text editor in your terminal. You can see the command in the image below:

3. Once you have the Vim text editor opened in front of you, type the following command:

:colorscheme CTRL+D

Next, type a colon (;), followed by ‘colorscheme,’ and then a space, and press Ctrl+D, as shown in the image below:

4. As soon as this command runs successfully, you will see a list of different color schemes that are available for your Vim text editor, as shown in the following image:

5. Now, you can decide on a color scheme from this list. After choosing a color scheme, type the following command in your terminal, followed by pressing the Enter key:

:colorscheme ChosenScheme

Here, replace the term ‘ChosenScheme’ with the name of your desired color scheme from the list. In this example, I want to change the color scheme to blue, so I will replace ‘ChosenScheme’ with ‘blue,’ as shown in the image below:

6. Upon executing this command successfully, your color scheme will immediately change to the chosen scheme, as shown in the following image:

Syntax Highlighting in Vim

To highlight syntax in Vim, perform the following steps:

1. First, you will need to create a dummy text file with the Vim text editor to try out this method. To do so, you will first need to launch the terminal, as described previously. Once you have the terminal window open in front of you, type the following command in the terminal, and then press the Enter key:

vim FileName.txt

Here, replace the term ‘FileName’ with whatever name you want to keep for your dummy text file. In this example, I have replaced ‘FileName.txt’ with ‘Testing.txt,’ as shown in the image below:

2. Once this command has executed successfully, an empty text file with the name Testing.txt will open in front of you. Press the Esc key to switch to the insert mode, and then type any random text in it, as shown in the following image:

3. To switch back to the command mode, press the Esc key again. Next, type the below command in your Vim text editor, followed by pressing the Enter key:

:wq

Running this command will save your newly created text file. The image below shows this command:

4. Next, type the following command in your terminal and press the Enter key:

:hi Normal ctermfg=Color ctermbg=Color

Here, you will replace the ctermfg color term with the color that you want to keep for the foreground and the ctermbg color term with the color that you want for the background. In this example, I have replaced the first color with Black and the second color with Red, as shown in the following image:

5. After this command has been executed successfully, the text color of the dummy text file will be changed to black and the background color will be changed to red, as shown in the image below:

Conclusion

By following the methods described in this article, you can conveniently customize Vim color schemes and also highlight text in your text files.

]]>
Integrating Vim with ctags https://linuxhint.com/integrating_vim_ctags/ Sat, 18 Jul 2020 03:41:12 +0000 https://linuxhint.com/?p=63297 Ctags is a tool used for navigating source code indexing methods, classes, identifiers, and variables. Ctags stores the index of programming code in a separate tags file. In the tags file, each line contains a single tag. You can obtain a lot of details from this index. Ctags supports 41 programming code languages and make it easier to search for methods or function blocks in large projects, especially when you do not know the working of code lines. For example, sometimes, you might not know how the particular method to be called when programming. With the ctags tool, you can immediately jump to the method definition.

This article will show you how to install ctags on your Ubuntu 20.04 Linux system and how to integrate Vim with ctags for source code navigation.

Installing ctags on Ubuntu 20.04

Ctags is not installed by default on Ubuntu 20.04. Use the following command to install ctags on Ubuntu 20.04:

$ sudo apt install ctags

Select the programming source code project folder to determine whether ctags is functioning properly. This article will use a few examples to test how ctags functions with Python projects.

Navigate to the specified folder where you want to implement ctags. Use the following command to move to the Python folder and list files.

$ cd pythoncode
$ ls

Integrating ctags with Vim

All the information related to ctags is stored in a tags file. So, you will need to set the folder path in ~/.vimrc file before using ctags.

Open the ~/.vimrc file in vim editor with root privileges by using the terminal.

$ sudo vim ~/.vimrc

Write the following set of commands in the .vimrc file and save it.

:syntax on
set tags+=$HOME/home/kbuzdar/pythoncode/

In the above image, ‘/home/kbuzdar/pythoncode/’ is the folder path where the tags file will be stored.

Working with ctags

Navigate to the specified folder through the terminal and use the following command to create ctags of the programming source code files that exist in this folder.

$ ctags -R *
$ ls

After executing the above command, you will observe that a file named ‘tags’ has been created in this folder.

Open the tags file on the vim editor. The tags file contains all the tags details of the programming code files present in the current folder.

$ vim tags

Find Tags Using Search Pattern

You can search tag by using a search pattern in Vim. To do so, open the python code file named even_odd.py in Vim. Next, search the ‘if’ tag by typing ‘:/if’ as follows:

$ vim leapyear.py
: /if

The following output will be displayed when you hit the Enter key. The ‘if’ tag will be highlighted if it exists in the Python source code file.

Search Tags Using tag Command

You can use the tag command in Vim to search for a tag in the file that exists in the tags file. Use the following command to search for a tag in a file:

:tag<tag-name>

For example, in the following output, the tag ‘num’ exists in the tags file.

:tag num

If a file contains the same tag many times in a file, the ctag command allows you to move to the next tag of the same type in the tag list. Use the following command to move the cursor to the next tag of the same type:

:tnext

The ctag command also allows you to move to the previous tag of the same type in the tag list. Use the following command to move the cursor to the previous tag of the same type:

:tprev

You can also move to the last and the first tag of the same type of tag searched in the list. To move to the last tag of the same type as the searched tag, enter the following command:

:tlast

To move to the first tag of the same type as the searched tag, enter the following command:

:tfirst

To select a particular tag from a list of tags after opening the source code file, use the following command:

:tselect

You can display the current tag information using the following command:

:tags

Ctags are useful for source code navigation within a file. Using the tags file, you can search the appropriate tag in the source code file. Keep in mind that if you change the source code file, then every time you make these changes, you will need to integrate and configure ctags with the changes. This is because the ctags file does not automatically update with the source code file.  To resolve this problem, you can use some useful auto plugins that keep your source code and tags file up to date.

]]>
How to create Macros in VIM for Repetitive Tasks? https://linuxhint.com/creating_vim_macros/ Sat, 18 Jul 2020 03:34:21 +0000 https://linuxhint.com/?p=63333 A macro is defined as a process that specifies the execution sequence of a certain operation. Macros are generally created for the tasks that are supposed to occur quite frequently. In Windows operating system, Microsoft Word also allows you to create macros for editing purposes. Similarly, in the Linux operating system, the VIM text editor provides you with the ability to create macros very easily. Therefore, in this article, we will explain to you the method of creating macros in VIM for repetitive tasks while using Ubuntu 20.04.

Method of Creating Macros in VIM for Repetitive Tasks in Ubuntu 20.04:

For creating macros in VIM for repetitive tasks while using Ubuntu 20.04, you will need to perform the following steps:

1. We need to create a dummy text file for demonstrating this process. For doing that, type the following command in your terminal and then press the Enter key:

vim DummyFile.txt

Here, replace DummyFile with the name of the file that you want to create. In this example, I have created a file named Macros.txt. This command is also shown in the following image:

2. As soon as you press the Enter key, an empty text file will appear on your screen. In this example, we are going to teach you the method of creating a macro for copying some text and pasting it multiple times in a text file. For doing that, you need to be in the Normal VIM text editor is by default in the Normal mode, so you do not need to switch to this mode. Now press “q” followed by the name of your macro. You can name your macros with small case English alphabets. In this example, the name of my macro is “m” so I will press “qm”. As soon as you press this key combination, VIM will start recording your macro, and you will be able to verify it by looking at the bottom of your screen as highlighted in the image shown below:

3. Now you need to switch to the Insert For doing that, press Esc followed by “i”. While being in the Insert mode, type anything that you later want to be copied and pasted multiple times. In this example, I want the following line to appear multiple times in my text file:

Creating VIM Macros for Repetitive Tasks

You can write anything of your choice. It is also shown in the following image:

4. Once you have typed the desired text and you have successfully recorded it, press “q” again to stop this recording. As soon as you press it, the recording status will disappear from the bottom, as shown in the image below:

5. Now your macro is all set to be played. You just need to point your cursor to the location where you want to paste the recorded text while being in the Insert mode, as shown in the image above. Then switch to the Normal mode by pressing the Esc Now type the following command:

=@q

As soon as you type it, your recorded text will automatically be played at the cursor position as shown in the following image:

6. However, if you want your macro to be played for more than once, then you need to type the following command while being in the Normal mode:

NumberOfTimesTheMacroIsToBePlayed@q

Here, replace NumberOfTimesTheMacroIsToBePlayed with an integer. In this example, I wanted my macro to be repeated 5 times, so I typed 5@q. As soon as you type this command, the recorded macro will be played at the cursor position for as many times as you have specified in your command, as shown in the image below:

Conclusion:

By following the simple method described in this article, you can create macros for repetitive tasks in VIM while using Ubuntu 20.04 very conveniently. The basics are the same for whichever type of task you want your macro to perform. However, for each different task, you will need to slightly modify the logic of your macro.

]]>
Important VIM Options and Settings https://linuxhint.com/important_vim_settings/ Sat, 18 Jul 2020 03:30:32 +0000 https://linuxhint.com/?p=63351 Vim is one of the most popular open-source command-line text editors. It is highly configurable and supports a lot of options, which is the reason for its popularity among users. In this article, we will discuss some of the Vim setting options that will help you to optimize your editing environment according to your preferences. Most of the options mentioned here are not enabled by default in Vim.

There are two ways to use the Vim setting options:

1. Enable the options for an individual file inside the Vim session using :set Open the desired file in Vim, type any option using the :set command in the Normal mode, and press Enter.

2. Enable the options permanently for all the files by specifying them in the local Vim configuration file ~/.vimrc. Whatever options you want to enable, simply add them in the ~/.vimrc file by removing the (:) before the set command, then save and close the file.

Vim configuration file can be created for the current user with the following command in the Terminal:

$ touch ~/.vimrc

To edit the Vim configuration file, use the following command in Terminal:

$ vim ~/.vimrc

Searching options

Enable search highlighting

While searching for some text, it is often helpful to highlight all the search results so that you can find at a glance where the matching pattern lies. Enabling search highlighting adds a colored background to all the search results. Search highlighting is disabled by default.

To enable search highlighting, use the following command:

:set hlsearch

To disable search highlighting, just prefix the option with the word “no”.

:set nohlsearch

Incremental searches

Usually, when you perform a normal search in Vim, you are only able to see the result after you have typed the whole search word and pressed Enter. With Vim incremental search, you can see the search results as you start typing the search word. It highlights all the text that matches what you have entered so far. For instance, you are searching for the word “count”. As you start typing letters, you will see Vim highlighting the matches.

The incremental search is disabled by default. To enable incremental search, use the following command:

:set incsearch

To disable incremental search, just prefix the option with the word “no”.

:set noincsearch

Case insensitive search

By default, the Vim performs case sensitive search, treating uppercase and lowercase letter differently. To perform case insensitive search, use the following command:

:set ignorecase

To re-enable the case sensitive search, just prefix the option with the word “no”.

:set noignorecase

Smart search

Sometimes, while performing case sensitive search for some text, you need to perform case insensitive search for some other text. Shifting between ignorecase and noignorecase can be annoying. Fortunately, Vim allows us to do smart searching by using the smartcase option with the ignorecase option. By combining these options, you will get either case sensitive or insensitive search based on the scenario:

  • If you enter a search query in lowercase, the search will be case insensitive. For example, searching for ubuntu will find ubuntu, Ubuntu, and UBUNTU.
  • If you enter a search query that contains one or more letters in uppercase, the search will be sensitive. For example, searching for Ubuntu will find only Ubuntu, not Ubuntu or UBUNTU

To perform a smart search in Vim, use the following commands:

:set ignorecase (press Enter)
:set smartcase (press Enter)

To disable smart search, just prefix the options with the word “no”:

:set nosmartcase

Automatically write files

While switching between multiple files, Vim asks you to first save the file if it has been modified. However, with the autowrite option, Vim saves the file automatically when you use the :n (or :p, :first, :last) commands to switch to another file.

To automatically write files before opening another file, use the following command:

:set autowrite

To disable this option, just prefix the option with the word “no”.

:set noautowrite

Enabling Automatic Indentation

Enabling automatic indentation in Vim allows you to indent each line the same as the previous one. For example, you indent a line with Space or Tab and press Enter. The next lines you type will automatically be intended with the same amount as the previous line.

To enable automatic indentation in Vim, use the following command:

:set autoindent

To disable automatic indentation, just prefix the option with the word “no”.

:set noautoindent

Syntax highlighting

Syntax highlighting displays the source code in different colors to enhance its readability. To enable syntax highlight in Vim, use the following command:

:syntax on

To disable the syntax highlighting, just prefix the option with the word “no”.

:syntax off

Set a color scheme for syntax highlighting

The color scheme is basically a combination of colors that is used in syntax highlighting. It comes handy, as the colors can help you identify various data types, functions, parameters, etc.

Vim contains some pre-installed color schemes which can be viewed from inside the Vim. Type :colorscheme, hit Spacebar and then use the shortcut Ctrl+d:

:colorscheme [space] [Ctrl+d]

To set a new color scheme for syntax highlighting, type the :colorscheme command followed by the name of the scheme.

:colorscheme name

Example:

:colorscheme torte

Display numbering

Line numbers in an editor can be very helpful in navigating through the file. It also tells where you are in the file. By default, Vim does not show line numbering.

To show line numbers in Vim, use the following command:

:set number

To hide line numbering, just prefix the option with the word “no”.

:set nonumber

Set windows title

Vim also allows you to change the title of the Vim editing window. With this feature, you can display the file that is currently being edited.

To specify a new title for your Vim window, use the following command by replacing the string with your preferred string name.

:set titlestring=string

To display the  original filename as a title, use  %t :

:set titlestring=%t

After specifying the title string, use the following command to set this new title:

:set title

To remove the new title and return to default one, just prefix the option with the word “no”.

:set notitle

Display cursor position

Using the ruler command in Vim, you can find out the cursor current position in the file. It shows the row and column of the cursor, which can be quite helpful when scrolling through a long text file.

To display the cursor’s current position in the Vim, use the following command:

:set ruler

To disable this option, just prefix the option with the word “no”.

:set noruler

Set confirm

When you try to perform certain operations (like :q or :e) on a modified file without saving it, the operations get failed. However, if you use the confirm option, the Vim displays the confirmation dialog asking if you want to save the file.

To use the confirmation option in Vim, use the following command:

:set confirm

To disable this option, just prefix the option with the word “no”.

:set noconfirm

Set history

By default, Vim remembers the history of 50 (:) commands and search patterns. However, you can change this default behavior by decreasing or increasing the number of commands to remember.

To change the number of commands Vim remember, use the following command by replacing the x with the number of commands to remember:

:set history=x

Enable Spell Check

Another great feature in Vim is spell-checking. When spell check is enabled, Vim finds and highlights the misspelled word.

To enable spell checking in Vim, use the following command:

:set spell

To disable this option, just prefix the option with the word “no”.

:set nospell

So that’s how you can use some of the important and useful Vim setting options to configure Vim according to your preferences. Use these options on individual files or apply them to all files by adding them in the ~/.vimrc file.

]]>
Navigating within a file in VIM https://linuxhint.com/navigating_vim_file/ Thu, 16 Jul 2020 06:45:28 +0000 https://linuxhint.com/?p=63235 Navigation in a file plays a vital role in text editing. To be more productive, you should know all possible shortcut methods or keys related to file navigation in Vim editor. Navigation within a file in other graphical editors is quite easy and simple. But, in Vim, you must remember some tips and tricks related to Vim navigation options. Vim offers great support to some advanced navigation features.

In this article, we will explain how to navigate within a file using Vim. We will suggest some navigation techniques for navigation, which will help you to improve productivity.

We have run all navigation options on Vim in this article using Ubuntu 20.04 system.

How to navigate within a file in Vim?

Vim offers some complicated ways to navigate within a file. You have to remember shortcut keys for Vim navigation. Let us start reviewing the following Vim navigation options.

First, you will open the terminal through the application launcher bar. Now, type ‘Vi’ to launch the Vim command-line editor. Type the following command to open a file in Vim for editing:

:edit <filename>

Or you can also type the following command on the terminal to open a file.

$ Vi <filename>

Navigating within file lines

Once the file is open in Vim, you will try the following file line navigation options on this file.

k – move upward
j – move downward
l – move to the right side
h – move to the left side

You can also use keyboard arrow keys for navigation in a file.

You can also repeat the operation for N times in Vim. For example, if you want to move down by 5 lines, then write ‘5j’.

Vim also allows users to navigate in a file to other positions instead of only the upward or download. Use the following options to do this action.

0 – cursor moves to the start of the current line
$ – cursor moves to the end of the current line
Ctrl + f – move to scroll down the entire page
Ctrl + b – move to scroll up the entire page

Navigating between the file words

You may use the following command for word navigation within a file −

w – cursor moves to the start of the next word
e – cursor moves to the end of the word
b – cursor moves to the start of the previous word

Special navigation

The following commands can be used to navigate to a particular line position:

:n – move to the nth line in a file
:0 – move to the start of the current file

or

(gg – this option will also move the cursor to start of the file)

:$ – move to the end of the current file

or

(G – you may also use this option to move to the end of the file)

Note: when you will use keyboards keys, then be careful about the case of keys.

H – move the cursor to the start of the displaying screen.
M – move the cursor to the middle line of the screen.
L – move the cursor to the end line of the screen.

Navigating within Paragraphs

{ – move the cursor to the start of the current paragraph. If you press { again and again, this will move you to the start of the previous paragraph.

} – move the cursor to the end of the paragraph. If you press } again and again, it will move you to the end of the next paragraph.

How to use jumps for navigation?

Vim keeps a record of each navigation through a jump list. You can move backward and forward directions using the jump list.

The jump list keeps the record of all places you have been visited by tracking the line number, column, and the file/text.

Execute the following command to display the Jump list:

:jumps

You may use the following command based on your jump list −

Ctrl + o – Jump the cursor to the previous position
Ctrl + i – Jump the cursor to the next position

Code Navigation

You can use the following options while you are working on programming code files.

%       cursor will move to match parenthesis
[[        move to start of the function
[{        move to the start of the block

That is all about navigation within a file in Vim editor. In this article, we explained various navigation options and commands which will help you in the future. You can explore more navigation shortcuts using Vim. I hope you like this article.

]]>
Understanding and using VIM Buffers https://linuxhint.com/how_vim_buffers_work/ Thu, 16 Jul 2020 06:37:03 +0000 https://linuxhint.com/?p=63241 While you start working on Vim editor, the most confusing concept about Vim is buffered. Especially for beginners, like other editors, they assume the displaying windows and tabs will be closed after closing the entire file. To understand the basic concept of buffers, it is important to know how vim displays file and buffers will work on them.

Today, in this article, we will give you a basic understanding of Vim buffers and how you can perform various actions using buffers. We have implemented Vim buffer tasks on Ubuntu 20.04 operating system.

What are buffers?

In Vim editor, buffers are memory portion loaded with the file content. But, not works on the original file. The original file remains the same until the buffers written on it. All files which open are associated with a specific buffer. Buffers are not associated with a file. You can make many buffers as you want.

When you use buffers in Vim, they can be hidden from the displaying view. If you open a file for editing, then it automatically creates a buffer, and each file will remain accessible until you close the Vim.

Press ‘Ctrl + Alt + t’ to open the terminal. Now, you will access the Vim command-line editor using the following command:

$ vi

How to create Vim buffers?

Well, to create a new buffer on Vim, you can use a couple of commands.

Use the following command to create a new buffer. The below command will split the vim interface into two horizontal windows.

:new

Use the following command that will create a new buffer and split the vim screen into two vertical windows.

:vnew

As we mentioned above, if you will edit a file, then it will automatically make a new buffer. So, follow the below command to edit a file in vim.

:edit file-name

For example, we have created  a file named ‘buffersintro’, use the following command to edit this file on vim:

:edit buffersintro

To edit multiple file buffers without saving the changes, you need to enable the option using the following command. Otherwise, you will get an error message.

:set hidden

How to manage Vim buffers?

To view the list of buffers, you will run the command as follows on Vim editor:

:ls

But, alternatively, you can also use the following command to perform the same action on Vim:

:buffers

The following output will be displayed on Vim. The first is the number column which indicates the buffer number, in the second column, you will see some sign indicators which represents the buffer status:

%: sign indicates the buffer in the current window
#: alternate buffer edit
a: indicates the active buffer which is visible and loaded.
h: means hidden buffer if you will show on your screen.

The third is the name of the buffer or file name. The last argument indicates the line number on which pointer points.

If you want to make any buffer in an active state, then you will type the following command:

:buffer number

The buffer number you will use from the buffer list.

To load all buffers in split windows, you will use the following command:

:ball

The above command will open all buffers in a new window as follows:

You can also open buffers in vertical window orientation using the following command on vim:

:vertical ball

To open a particular buffer in a new window, for this purpose, issue the following command on Vim:

:sbuffer

You can also use the shortcut for this purpose. Type buffer number, then you will press ctrl w^.

Delete buffers

Once the modification in a file is completed, now you can delete the buffer from the list by issuing the following command on the Vim:

:bdelete arg

Or

:bd arg

Where arg may be the file’s name or the number the buffer, you want to remove from the list.

First, you list buffers using :ls command.

For example, you want to delete the 3rd buffer named with ‘newfile’ from the list. So, you will type the following command to do this.

:bdelete 3

Or

:bdelete newfile

Now, list all buffers. You will see that the 3rd buffer has been removed from the buffer’s list.

You can even delete multiple buffers from the list using the following command:

:bdelete buffer-name1 buffer-name2…

Or

:2,4bdelete (it will delete the numbers from the second buffer up to 4)

Buffers Navigation

You can use the following command for buffers navigation:

  • Add a file into the new buffer  :badd <filename>
  • Switch to specific buffer N  :bN
  • Jump to the next buffer in the buffer list :bnext
  • Jump back to the previous buffer in the buffer list :bprevious
  • Jump to the first buffer :bfirst
  • Jump to the last buffer :bfirst

In this article, we have given a basic understanding of the Vim buffers. We see that how to deal with Vim buffers and use them. If you want to explore more, then using :help buffer, you can explore each and everything related to Vim buffers. I hope this article will help you to explore more advanced things related to Vim buffers.

]]>
VIM Plugins with VIM Vundle https://linuxhint.com/installing_vim_vundle_plugin_ubuntu/ Thu, 16 Jul 2020 06:22:54 +0000 https://linuxhint.com/?p=63271 Vim is a well-known console-based source code, and the text editor offers many advanced features. The most important feature of Vim is customization and extensibility using various plugins. As we know that it is a highly configurable tool; therefore, managing all these plugins manually is a very tedious job. For this purpose, you need a plugin manager to manage all configurations. Vundle is a plugin manager that manages all plugins.

In this article, we will discuss how to install the Vim Vundle plugin manager on the Ubuntu system and manage all plugins on the Vim text editor.

Installing Vundle on Ubuntu 20.04

Install the Git version control system, available in any Linux operating system official repository. Here in this article, we will use Ubuntu 20.04 package repository to install git.

Update the apt repository using the following command:

$ sudo apt update

Now, install the git by typing the following command:

$ sudo apt-get install git -y

After executing the above command, git to be installed on your Ubuntu system. Now, using the URL https://github.com/VundleVim/Vundle.vim access the official Vundle website.

The following web page to be displayed in your browser:

Click on the green button named “Clone or download”. The following popup dialog will appear’.

Click on the Copy icon. The URL of the git repository to be copied.

Now, access the terminal and follow the syntax as given below:

$ git clone URL-paste ~/.vim/bundle/Vundle.vim

You will paste the copied URL in the following command. The final command should look like the below command.

$ git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim

The Github repository to be cloned in the user’s home directory. In my case, the path of the directory is ‘/home/kbuzdar/.vim/bundle/Vundle.vim’.

Now, open the ~/.vimrc file using the following command:

$ vim ~/.vimrc

Now, if the ‘.vimrc’ file doesn’t exist before then. It will create and open an empty file.

Press Esc key and i to go in insert mode. Now paste the following code in this file:

syntax enable
set tabstop=4
set expandtab
set number
filetype indent on
set autoindent
set nocompatible
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'VundleVim/Vundle.vim'

" Add plugins here which you want to add

call vundle#end()
filetype plugin indent on

Now save this file and exit vim using the following command:

:wq!

Now open the vim using the following command through terminal:

$ vim

Now, using the following command, we will install or initialize the Vim Vundle plugin manager:

:PluginInstall

The Vim Vundle plugin manager to be installed on vim. In the following output, you can see the installation of Vim Vundle plugin:

Search plugin

Using the Vundle plugin manager, you can search for newly available plugin by using the following syntax:

:PluginSearch <plugin-type or name>

How to install a plugin from GitHub using Vundle package manager?

You can install a plugin using the VIM Vundle package manager. For this purpose, we will open the plugin web page of Github. For example, we want to install the ‘powerline’ Github plugin from their repository.

Follow the following steps to install a plugin from the Github repository:

1. Open the plugin page of Github and copy the name section marked in the following output screenshot.

2. Now, open the file ~/.vimrc in vim and paste the line in it file as follows:

3. Install this plugin on vim using the following command:

The powerline plugin to be installed on Vim. Now, list the installed plugins using the following command:

:PluginList

As you can see, the powerline Github plugin has been installed on Vim.

Remove or delete plugin through Vim Vundle

You can also remove a plugin from the installed plugins list. Navigate to the particular line and press ‘Shift + D’. After that, the plugin to be removed from the list.

Now, also remove the plugin from the ~/.vimrc file as follows:

That’s all about the Vim Vundle plugin manager.

In this article, you learned using the VIM Vundle Plugin Manager. You can manage all VIM plugins easily and in a quick way. Moreover, you can search and install more Github plugins for installation. I hope you enjoyed this article.

]]>
Vim vs. Nano https://linuxhint.com/vim_vs_nano/ Tue, 14 Jul 2020 16:44:25 +0000 https://linuxhint.com/?p=63110 Vim, an acronym for Vi Improved, was released in 1991 as an improved project of vi, an older, screen-oriented text editor of originally developed for the Unix operating system. Vim is designed to be extremely versatile and fast, like its predecessor, Vi. On most Linux systems, Vim comes pre-installed and virtually available for all types of operating systems. Vim is available everywhere, therefore it really pays off to learn the basics to edit a text file with this text editor. Upon opening Vim, the Vim text editor interface shows on your system.

$ vim /home/user/kbuzdarconf.txt
// how to create file on Vim

The GNU nano, commonly known as ‘nano,’ is an improved project of the Pico text editor, which was released in 1999. Like Vim, Nano also comes pre-installed on most Linux systems. The Nano text editor an ideal tool for beginners. On startup, the Nano text editor shows the following interface.

$ nano /home/user/kbuzdarconf.txt
// how to create file with nano

When you search for terminal-based text file editing, then you will find that two of the top choices are Vim and Nano. Which one is better? This is a long debate and I’m not going to directly answer this question, but will instead focus on the differences between nano and Vim. This article highlights some of the differences that set these text editors apart.

Ease of Learning

The graphs in the image above show the learning curves of various text editors, in which Nano and Vim are also included. When you start working with Vim, you might not even know how to edit a file on it. Initially, you might need to find a cheat sheet on Google, but in a couple of hours, you will to know the basics of the Vim text editor. You can also download the GUI version of VIM, known as gVim, to practice some common commands. The toolbar and menus will also make it easy to learn how to use Vim. Then you have Nano, which is an improved text editor of Pico, has no learning curve, and is relatively user-friendly compared to Vim. Even if you have not worked with Nano before, you can easily learn how to use this text editor with a little knowledge and without requiring any additional help.

Productivity

Vim behaves like a model, and while you are using Vim, you will be constantly changing between the edit mode and the command mode. On the other hand, with the Nano text editor, you only use one mode with some special key combinations. So, Vim is much faster than Nano.

Users

Vim is necessary for a Linux system administrator. This text editor is also good for programmers because you can use it to program code in the form of a plain text file that is easy to copy and manipulate. Furthermore, Vim is good for anyone wanting to work with command line text editors often, and even works for writers. Vim is therefore a good program for all users.

Nano is great text editor for beginners who are new to terminal-based text editing. Nano is also useful for those who want to make just a few simple edits. If you are not a “perfect” Linux user, then Nano might be for you.

Important Features

To differentiate between these text editors, it would help to list some important features of Vim and Nano.

Using Vim, you can unlock speed and efficiency with some powerful features, which include window support, macros, command repetition, text objects, registers, filters, auto-completion, and global substitution.

Nano does not support advanced features, such as window splitting, macros, auto-completion, viewing multiple files at once, rectangle selecting/vertical block/editing, etc.

Vim is a more powerful tool with which you can make complicated edits in a quick and easy way. With Nano, it can prove more difficult and time-consuming to make complicated edits.

So, Vim or Nano?

If you want to perform more advanced tasks using the command line, then you may find Vim is best to use. Vim is simple and attractive in its own way. So, it is better to prefer Vim over Nano, because if you are using a nano text editor, and you just started learning some important features of Vim. You will perform more efficiently and effectively as compared with Nano. So, it is up to you to choose whichever text editor best fulfills your needs.

]]>
How to Configure and Use Auto-Complete with Vim https://linuxhint.com/vim_auto_complete/ Tue, 14 Jul 2020 16:39:30 +0000 https://linuxhint.com/?p=63116 When you are using a text editor for work, your biggest concern may be having to type every single word on your own, especially when you have a lot of pending tasks. If you are always trying to find workarounds for making tedious tasks easier, auto-complete is one of those features that can make your work process more efficient. The auto-complete feature of Vim gives you suggestions based on the context, and you can choose the most suitable word out of the suggestions without needing to type it on your own. This article will explain how to configure and use the Vim auto-complete feature in Ubuntu 20.04.

Configuring and Using Auto-Complete with Vim

First, create a dummy file to use for practicing the five methods mentioned below. To do so, perform the following steps:

  • Type the following command in your terminal and then press the Enter key:
    vim DummyFile.txt
    Replace the term “DummyFile” with the name of the file that you want to create. You can also modify its extension according to your requirements, though this file alone will be sufficient for all the methods discussed in this article. This command is also shown in the following image:
  • After this command has been executed, an empty text file will appear on your screen.

How to Configure and Use Auto-Complete in Text Files with Vim

The auto-complete feature is configured by default for Vim text files. Therefore, you only need to learn how to use this feature. To configure and use auto-complete with Vim, perform the following steps:

  • Press Esc+ i to enter Insert Type any random text in the dummy file that you created in the previous step. In this case, I have written two lines, as well as the letter c, as highlighted in the image below: 
  • To activate the auto-complete feature for this word, press Ctrl+ n. A list of words will appear on your screen, from which you may choose the most suitable word. If there is only a single match, however, then VIM will automatically complete this word, as shown in the following image:

How to Configure and Use Auto-Complete in JavaScript Syntax with Vim

To configure and use auto-complete in JavaScript syntax with Vim, perform the following steps:

1. Switch to Cmdline mode of Vim by pressing Esc, followed by a colon.

2. Type the following command and press the Enter key:

:set omnifunc=javascriptcomplete#CompleteJS

This command is also shown in the image below:

3. Switch to Insert mode and start typing any JavaScript syntax.

In this example, I just wrote document, then I pressed Ctrl+ x, followed by Ctrl+ o. Vim showed me a list of suggestions, as shown in the following image:

How to Configure and Use Auto-Complete in Html Code with Vim

To configure and use auto-complete in Html code with Vim, perform the following steps:

1. Switch to Cmdline mode by pressing Esc, followed by a colon (;).

2. Type the following command and press the Enter key:

:set omnifunc=htmlcomplete#CompleteTags

This command is also shown in the image below:

3. Switch to Insert mode and start typing any Html code.

In this example, I wrote <!DOCTYPE and I pressed Ctrl+ x, followed by pressing Ctrl+ o. Vim showed me a list of suggestions, as shown in the following image:

How to Configure and Use Auto-Complete in CSS Syntax with Vim

To configure and use auto-complete in CSS syntax with Vim, perform the following steps:

1. Switch to Cmdline mode by pressing Esc, followed by a colon (;).

2. Type the following command and press the Enter key:

:set omnifunc=csscomplete#CompleteCSS

This command is also shown in the image below:

3. Switch to Insert mode and start typing any CSS syntax.

In this example, I wrote font: and pressed Ctrl+ x, followed by pressing Ctrl+ o. Vim showed me a list of suggestions, as shown in the following image:

How to Configure and Use Auto-Complete in PHP Code with VIM?

To configure and use auto-complete in PHP Code with Vim, perform the following steps:

1. Switch to Cmdline mode by pressing Esc followed by a colon.

2. Type the following command and press the Enter key:

:set omnifunc=phpcomplete#CompletePHP

This command is also shown in the image below:

3. Switch to Insert mode and start typing any PHP code. In this example, I wrote date( and I pressed Ctrl+ x, followed by pressing Ctrl+ o. Vim showed me a list of suggestions, as shown in the following image:

Conclusion

By following the methods discussed in this article, you can easily configure and use the auto-complete feature in VIM with simple text files, as well as with various scripting languages.

]]>
What is the VIM Editor, and why is it great! https://linuxhint.com/vim_text_editor/ Mon, 13 Jul 2020 15:23:42 +0000 https://linuxhint.com/?p=63059 While working on Linux distributions, there are various tasks where we will need to work on a text editor, including scripting/programming, text or configuration file editing, and many more. You can use and install several popular text editors on your Linux based operating environment. However, in this article, we will discuss the benefits and features of the VIM text editor and why it is great to use the on the Linux system.

What is the VIM editor?

The first screen-oriented text editor was Vi that created for the Unix environment; it was built for text manipulation.  Vim is a popular text editor on Linux, which stands for ‘Vi Improved’. It is the clone of the Vi Unix text editor, and it supports more features than Vi. In simple words, Vim is a text editor that you can install on your Linux system. The main features of Vim, including highly configurable, syntax highlighting, graphical versions, mouse support, advanced editing commands, visual mode, and integrate a large number of extensions or plugins.

Why is vim so popular? Let us discuss some important features of vim, which makes it unique from other text editors. There are the following reasons why users preferred to use vim over others.

Vim is an Open-source and cross-platform

Vim is an open-source and freely available text editor that is designed for both application GUI as well as for command-line. You can install Vim on every system. Vim is available on Mac OS, Linux and Windows as well. On most of the modern Linux systems, the vim is already installed by default. If it is not installed then, you can install it using the following command on different Linux distributions:

$ sudo apt install vim [On Ubuntu / Debian]
$ sudo yum install vim [On CentOS]
$ sudo dnf install vim [Fedora ]

Vim is documented well

The vim documentation is well written and simple to use. Vim provides a built-in manual, which can be accessed using the: help command. This manual gives more details than Vim’s man page.

Vim Community

Vim is one of the oldest and most popular editors and hence with that has a large community to support users.  Many coders and system admins you meet will be either a daily or occasional user of Vim.  Forums like stack overflow and others will easily find experts to share tips on Vim with you.

Vim supports portable configurations

The portable configurations mean that the Vim text editor enables you to import the same configurations on your Linux systems. You can also share the configurations with your friends on the Internet as well. You just need to do is copy a few files and directories, and nothing else.

Vim is customizable and extensible

Vim provides extensive support to various plugins. You can use a lot of plugins out there that enhance the Vim’s functionality.  You can read about the VIM plugins in our other articles.  There are many configuration options that let you setup VIM your own way.

Vim consume fewer system resources

The main strength of Vim is its simplicity and smallness; therefore, this text editor doesn’t use more system resources as compared to other text editors like emacs, nano, etc. especially the graphical editors. Vim is lightweight and very fast, even when modifying the large numbers of files source code. You can run it over ssh for various remote operations on any type of server.

Moreover, Vim offers some important effective key-bindings; thus, it allows you to carry out any type of imaginable task using the keyboard. Vim text editor offers many capabilities, and it is very efficient due to its simplicity.

Vim supports multiple File Formats and Programming Languages

Vim editor, by default, supports multiple file formats and several programming languages. Using Vim, you can detect any type of file, by checking the file name and by inspecting the file content for specific text.

Vim is ext, , remely powerful

Vim is a powerful text editor that provides you to do tasks quickly. You can perform tasks very quickly and in an efficient manner, and usually with the keyboard only (no mouse), once you learn how Vim works. Some important features of vim include registers, macros, command repetition, text objects, auto-completion, searching, and global substitution.

Vim is interesting and Fun!

Last feature but not least, Vim is very interesting and fun to learn. Once you start working on Vim extensively on a daily basis, you will feel really do amazing tasks with it.

In this article, we explained some useful features of the Vim text editor. You can explore more of its features when you use it on your system. I hope you enjoyed this article.

]]>
Vim Cheat Sheet https://linuxhint.com/vim_cheat_sheet/ Mon, 13 Jul 2020 15:22:19 +0000 https://linuxhint.com/?p=63056 Vim is a free, open-source text editor that comes installed by default with most operating systems. This tool is one of the most popular and powerful text editors that has been the preferred choice of many programmers. Learning to use Vim effectively can be a challenge, as Vim contains a lot of commands, and memorizing each and every command could take time. Below, we have compiled some of the most used Vim commands into a cheat sheet that will be helpful for using this text editor.The following table contains the most common and useful Vim commands to know, along with the functionalities of each command.

Command

Function

File Management

:w Write file to disk
Ctrl+g Show file information
ga Show character information
:q Quit vi without saving file
:wq Write file to disk and quit vi
:q! Ignore warning and discard changes
:w filename Save the file as filename
:r filename Read and insert filename

Navigation

h Move cursor left
l Move cursor right
j Move cursor down one line
2j Move cursor down 2 lines
k Move cursor up one line
2k Move cursor up 2 lines
w Jump to start of next word (punctuation considered words)
W Jump to start of next word (spaces separate words)
e Move to end of next word (punctuation considered words)
E Move to end of next word (no punctuation)
b Move backwards to start of current word
B Move backwards to start of current word (no punctuation)
( Move a sentence back
) Move a sentence forward
{ Move a paragraph back
} Move a paragraph forward
$ Move to end of line
^ Move to first non-blank character in line
0 Move to start of line
G Move to last line of document
3G Move to line 3
gg Move to first line of document
:n Go to line n in document
Ctrl+d Scroll down half a screen
Ctrl+u Scroll up half a screen
Ctrl+f Page forward
Ctrl+b Page backward

Switching Modes

i Enter Insert mode
v Enter Visual mode
Esc Return to normal mode from Insert and Visual mode

Insert/Append Text

i Insert text before current cursor location
I Insert text at beginning of line
a Append text after current cursor location
A Append text at end of current line
o Create new line for text below current cursor location
O Create new line for text above current cursor location
ea Insert (append) at end of current word

Search and Replace

/pattern Search forward
?pattern Search backward
* Search forward for word under cursor
# Search backward for word under cursor
r Replace single character at cursor position
R Replace characters starting at cursor position
cc Replace entire line
:%s/search/replace/g Replace every occurrence of search with replace.
:%s/search/replace/gc Replace every occurrence of search with replace with confirmation

Cut, Copy and Paste

x Cut character under current cursor location
X Cut character before current cursor location
dw Cut from current cursor location to next word
D Cut from current cursor location to end of current line
dd Cut entire current line
Y Copy selected text
yy Copy entire current line
p Paste text after cursor
P Paste text before cursor

Undo and Redo

u Undo last change
Ctrl+r Redo changes that were undone

Working with Multiple Files

 

:e filename Edit file in a new buffer
:ls List available buffers
:bn Move to next buffer
:bp Move to previous buffer
:bfirst Move to first buffer
:blast Move to last buffer
Ctrl+ws Split windows
Ctrl+ww Switch windows
Ctrl+wq Quit window
Ctrl+wv Split windows vertically
:tabnew Create new tab
gt, :tabn, Move to next tab
gT, :tabp Move to previous tab
:tabfirst Move to first tab
:tablast Move to final tab
#gt Move to tab number #

Set Line Number

:set number Show line numbers
:set nonumber Do not show line numbers

Visual Mode Commands

y Copy selected text
d Delete selected text
c Delete selected text and enter Insert mode
> Increase indent
< Decrease indent
= Fix indentation of current line
~ Change case

The cheat sheet above should fill you in on the most used Vim commands. Vim can be hard to use at first but mastering a few commands can help you to gain more productivity in text editing and coding.

]]>
Opening and Switching Between Multiple Files and Windows in VI https://linuxhint.com/opening_switching_multiple_files_vim/ Mon, 13 Jul 2020 15:19:45 +0000 https://linuxhint.com/?p=63044 By default, Vim starts with a single window, which is enough for editing a single file. But sometimes, you may have to work on multiple files. Vim makes it easier to work with multiple files at once with its window management system, allowing you to work on multiple files at the same time within a single Vim session. You can choose to view one file at a time, or you can split your workspace to view multiple files side by side.This article will explain how to open multiple files and windows in Vim, as well as how to switch between multiple files and windows.

Opening and Switching Between Multiple Files

Editing multiple files in the same session can speed up your work. When editing multiple files, it takes some time to exit one session and then open a new session for another file. Staying in the same session helps you to efficiently work on multiple files at the same time.

Opening Multiple Files in Vim

You can open multiple files at the start of the Vim editing session from the command line, or at any time from inside the Vim editing session.

From the Command Line

To open multiple files in Vim at the start of the Vim editing session, specify the files as follows:

$ vim file1 file2

By default, the first file (file1) will open in Vim. Go ahead and edit this file, and once you are finished, save it using the :w command. After saving, you can switch to the next file.

From Inside Vim

You can also add additional files at any time during the Vim editing session. For instance, while editing file1 and file2, you can add a file3.

To edit another file during the Vim session, first save the current file using :w in Normal mode, and then use the following command:

:e filename

Switching Between Files in Vim

Note that to switch to another file, you will first have to save the current file, if you have made some changes to it. If you have not saved the current file, Vim will not let you switch files, unless you specify with the exclamation mark (!). This notation will discard the changes made to the current file and forcefully switch to the other file. For instance, if you have made some changes to file but you decide to discard those changes and switch to another file, use the exclamation mark (!) following the commands listed below.

Note: Issue all the below commands in Vim’s Normal mode.

To switch to the next file, issue either of the following commands:

:n

Or

:bn

To switch to the previous file, issue the following command:

:N

Or

:bp

To switch to the first file, issue the following command:

:bf

To switch to the last file, issue the following command:

:bl

To switch to a specific file number, issue the following command (for file number 3, use the command “b 3”):

:b number

To switch to a specific file filename, issue the following command (for file name file1, use “:b file1”):

:b filename

To switch back and forth between two files, issue the following command:

:e#

Where the # symbol represents the number of the alternate file.

Or, you can use the following shortcut:

Ctrl+^

To save all open files, issue the following command:

:wall

To quit the current file, issue the following command:

:bw

To quit all open files, issue the following command:

qall

To forcefully quit all the files, discarding the changes, issue the following command:

:qall!

To list all open files, issue the following command:

:ls

In the ls: output, the % refers to the current file, while the # refers to the alternate file.

Opening and Switching between Multiple Windows

By default, the Vim opens only a single window, even if you have opened multiple files. However, you can view multiple windows open at once in Vim. This can be achieved by splitting the windows horizontally to create two windows of the same width, or vertically to create two windows of the same height. Using this method, you can view multiple windows at once in a single Vim session.

From the Command Line

You can open multiple windows from the command line at the start of the Vim editing session. To do so, split the window either horizontally or vertically using the following methods.

Splitting Windows Horizontally

To split the window horizontally, use the following syntax:

$ vim -o file1 file2

This command will split the Vim editing session horizontally, into two equal-sized windows.

Splitting Windows Vertically

To split the windows vertically, use the following syntax:

$ vim -O file1 file2

This command will split the Vim editing session vertically into two equal-sized windows.

Splitting Windows inside of Vim

You can also split windows during the Vim editing session. To do so, open a file in Vim, and then split it either horizontally or vertically using the following methods.

Splitting Windows Horizontally

To split windows horizontally in Vim, use the following command:

:split

You can also use the following shortcut:

Ctrl+w,s

When no argument specified, the current file will be displayed in both split windows. To open another file in a new window, use the command :split, followed by the desired filename, as follows:

:split filename

Splitting Windows Vertically

To split windows vertically in Vim, use the following command:

:vsplit

You can also use the following shortcut to split the windows vertically:

Ctrl+w,v

With Vim, you can split the windows even further, either horizontally or vertically.

Switching between Horizontal Windows

To switch to the next window below the current window, use either of the following shortcuts:

Ctrl+w, j or Ctrl+w, Down arrow

To switch to the next window above the current window, use either of the following shortcuts:

Ctrl+w, k or Ctrl+w, Up arrow

Switching between Vertical Windows

To switch to the next window to the right of the current window, use:

Ctrl+w,l or Ctrl+w,Right arrow

To switch to the next window to the left of the current window, use either of the following shortcuts:

Ctrl+w,h or Ctrl+w,Left arrow

To cycle through all Vim windows, use the following shortcut:

ctrl+w,w

To close the current window, use the following command:

:close

You can also use the following shortcut:

Ctrl+w,c

To close all windows except the current window, use the following command:

:only

You can also use the following shortcut:

Ctrl+w,o

Conclusion

With Vim’s window management system, you can handle multiple files at the same time quickly and efficiently. This article showed you how to open and switch between multiple files and windows in the Vim text editor. Hopefully, this should make it easier for you to use this amazing text editing tool.

]]>
In-Depth Usage of Vim Visual Mode https://linuxhint.com/vim_visual_mode/ Mon, 13 Jul 2020 15:17:18 +0000 https://linuxhint.com/?p=63028 Vim is a useful text editor in Ubuntu 20.04 that is composed of multiple operating modes. This article will show you how to use Vim’s visual mode, a powerful editing mode that can be used to highlight and edit the text within different files in a slick, convenient fashion. Visual mode gives you a very comfortable visualization of the text that you want to edit or modify and allows you to use different commands to manipulate selected text. This article will describe the in-depth usage of Vim’s visual mode in Ubuntu 20.04.

In-Depth Usage of Vim Visual Mode

To make use of Vim visual mode in Ubuntu 20.04, you will need to perform the following steps:

1. First, you will need to launch the terminal in Ubuntu 20.04. To do so, you can press Ctrl+ T, or you can click on the Activities icon located at your desktop and then type “terminal” in the search bar that appears, double-clicking on the search results to launch the terminal. You can also right-click on your desktop and then select the Open Terminal option from the menu that pops up. The newly launched terminal window is shown in the image below:

2. Next, create a dummy text file for demonstrating usage of VIM’s visual mode. To try this out, type the following command in your terminal and then press the Enter key:

vim FileName.txt

Here, replace the FileName with the name of your dummy text file. This command is also shown in the following image:

3. As soon as you run this command, an empty text file will appear on your screen. Type any random text in the file, and then press :wq, while being in the Cmdline mode for saving your newly created file. This step is shown in the image below:

Select and Edit a Phrase in Simple Visual Mode

1. Open the dummy file again and point the cursor to the beginning of the phrase that you want to select. Press “v” to enter the simple visual mode, as highlighted in the following image:

2. With the help of the arrow keys, select as many parts of a line as you want, as shown in the image below:

3. To delete the selected text, press “d,” and you will see that the selected text is no longer present, as shown in the image below:

4. To paste this selected text somewhere else, point your cursor at the desired location and then press “p.” You will notice that the selected text has been pasted at the selected location, as highlighted in the image below:

5. To replace the selected text, after selecting the text, press “c.” The selected text will immediately disappear, and you will be able to insert new text at the selected position, as shown in the following image:

Select, Edit, and Indent Lines in Visual Line Mode

1. Point your cursor to the line that you want to select and press “V” to enter visual line mode. You will notice that the line where your cursor is pointed is immediately selected. Use the arrow keys to select more than one line, as shown below:

2. To delete the selected lines and place them elsewhere, press “d” and point your cursor to where you want to place the lines. Press “p,” and the selected lines will be pasted at your chosen location, as shown in the following image:

3. To change the indentation of the selected lines, use the “>” key to increase indent and use the “<” key to decrease indent, as shown in the image below:

Check Indentation of Columns in Visual Block Mode

1. You may need to check if every character in a specific column, or in more than one column, is indented alike. To enter visual block mode, point your cursor to the column and press Ctrl+ v, as highlighted in the following image:

2. Use the down arrow key to check the indentation of all the characters in the selected column. To check the indentation of more than one column, use the right arrow key to navigate and select the columns, as shown in the image below:

Conclusion

By following the steps described in this article, you can easily master VIM’s visual mode, allowing you to edit the text within your files with ease.

]]>
What are the VIM Survival Commands that you need to Operate it? https://linuxhint.com/basic_vim_commands/ Fri, 10 Jul 2020 17:20:37 +0000 https://linuxhint.com/?p=62982 Whenever you are learning to use a new utility in any operating system, there are some basic hacks that you must learn to operate that utility successfully. These hacks will not necessarily make you a pro of that utility; however, they will ensure that you never get stuck while performing the basic functions in that utility. In the Linux operating system, most of the functions are performed through commands since it provides you with a command-line interface (CLI). VIM text editor also has a hand full of beneficial commands that you must learn to use it well. Therefore, in this article, we will share with you some survival commands that you need to operate the VIM text editor in Ubuntu 20.04.

VIM Survival Commands that you need to Operate it in Ubuntu 20.04:

The survival commands that you need to operate the VIM text editor in Ubuntu 20.04 are discussed below:

Command # 1:

VIM text editor has multiple different modes of operation. However, the most common out of these modes is the Normal mode and the Insert mode. If you ever feel the need for toggling between these two modes, then all you have to do is to press the Esc key. By default, the VIM text editor is in the Normal mode. Pressing the Esc key for once will take you to the Insert mode where you can edit files, whereas pressing the Esc key again will take you back to the Normal mode.

Command # 2:

If you are a naïve user of VIM text editor, then you may make mistakes while editing your files and then get worried about how to revert the changes that you have accidentally made. However, VIM provides you with a very powerful command for undoing what you have unintentionally changed. All you have to do is to switch to the Normal mode and then press u key. Doing this will undo the recently made changes.

Command # 3:

Now when you have edited your file completely and want to quit from VIM text editor after saving this file, then you will need to switch to the Command mode or Cmdline mode. For doing that, first, you need to be in the Normal mode. Then type a colon to get into the Cmdline mode. Now type wq followed by the colon and press the Enter key to save your newly created file and for exiting from the VIM text editor. This command is also shown in the following image:

Command # 4:

If you have created a very long text file or you are reading a long text file, then you might need to toggle up and down every now and then. For going half page up, all you have to do is to press Ctrl+ u. Typing this key combination will immediately take you to half page up.

Command # 5:

Similarly, for going half page down, all you have to do is to press Ctrl+ d. Typing this key combination will instantly take you to half page down.

Command # 6:

The last survival command that we will talk about is the search command, with the help of which you can easily find something that is written in your file. All you have to do is to press the Forward Slash “/” key. Tap on this key, then type whatever you want and then press the Enter key to find the desired results. If there is more than one result, then you might feel the need to check them all. Press the n key for going to the next search result, whereas if you want to go back to the previous search result, you can press the N key. For demonstrating this command, I had a dummy text file in which I wanted to search for the alphabet “k”. Therefore, I typed “/” followed by the alphabet “k”. The search results of this query are shown in the image below:

Conclusion:

In this article, we talked about a few very basic commands that are also referred to as VIM survival commands because whatever you want to do with the VIM text editor, you must know these basic commands for operating it properly. This is not an exhaustive guide; therefore, we did not intend to bombard the reader with tons of different commands. The commands discussed in this article are particularly meant for the people who are new to this text editor.

]]>
VIM Modes and how to change the mode https://linuxhint.com/vim_modes/ Tue, 07 Jul 2020 17:45:42 +0000 https://linuxhint.com/?p=62853 Vim is the most popular and extremely powerful text editor. It possesses a lot of features that you would not expect to have in a text editor. Most of these features make it much easier for you to do a lot of work in a little time. The Vim editor is a modal text editor; it uses modes for different purposes like inserting text, running commands, and selecting text. Modes basically decide whether pressing any key on the keyboard will insert those characters or move the cursor through the document. Therefore, it is important to know what each mode is and how to change the modes.

This article will describe what Vim modes are and how to change them. Vim is a free and open-source text editor that comes installed by default with most of the operating systems.

Please note that all the commands and processes discussed in this article have been tested on the Ubuntu 20.04 LTS (Focal Fossa).

Vim Modes

In Vim, there are three modes of operation: Normal, Insert, and Visual.

Normal mode

Normal mode is the initial mode of the Vim editor. When you open a new file edit an existing one, it starts in normal mode by default. In normal mode, you cannot insert any character. Normal mode is also known as command mode because all the keystrokes you perform are interpreted as commands. For instance, if you press k, it will move the cursor position up one line instead of inserting the character “k”. Similarly, if you press yy, it will copy the current line instead of inserting “yy”. Also, in normal mode, the uppercase and lowercase letters are treated differently. For instance, pressing o create a new line for the text below the current cursor location, while pressing O creates a new line for text above the current cursor location

To access normal mode from other modes, press Esc key.

Insert mode

Insert mode is where you can insert your text in the file. This mode inserts every character you type at the current cursor location.

Visual mode

Visual mode allows you to select text so that you may perform certain operations (cut, copy, delete) on it.

Changing the modes

As already discussed, when you create or open a file in vim, it first opens in Normal mode.

In order to type any character, you will need to switch to the Insert mode. There are different commands to enter into Insert mode from Normal mode that are i, I, o, O, a, and A. The most commonly used command to enter in to insert mode is “i”. To shift back to normal mode, press Esc.

To switch to the visual mode from Normal mode, different commands are v, V, Shift + v, and Ctrl + v. The most commonly used command to enter in to insert mode is “v”.

To switch to the visual mode from Insert mode, first shift to Normal mode by pressing the Esc, then press v to get into the Visual mode.

Basic commands

Following are some basic commands that can be used for inserting and manipulating text in Vim:

File related commands

:w write the file to the disk
:q quit vi without saving the file
:wq write the file to disk and quit vi
:q! Ignore the warning and discard the change
:w filename Save the file as filename

Moving the cursor

j move the cursor down one line
k move the cursor position up one line
l move the cursor to the bottom of the screen
0 move to the beginning of the line
$ move to the end of the line

Inserting Text

I insert text at the beginning of the line
i insert text before the current cursor location
a insert text after the current cursor location
o Create a new line for the text below the current cursor location
O Create a new line for text above the current cursor location

Changing text

cc Remove the whole line and start Insert mode.
s Remove the character under the cursor and start Insert mode.
r Replace the character under the cursor

Copying pasting

y Copy the selected text to clipboard
yy Copy current line
P insert the text “before” the cursor,
p Insert the text at the point after the cursor

Deleting Text

X delete the character before the current location
x delete the character under the current location
D Cut to the end of line
dd Cut current line

Undo/Redo

u undo last change

 

Ctrl_R Redo

The text editor should be optimized for editing, not just writing, and Vim is one of them. It has separate modes for editing, inserting, and selecting text. In this article, you have learned about vim Normal, Insert, and Visual mode and also how to switch between different modes. I hope you liked the article!

]]>
Important vim Editor Commands https://linuxhint.com/25_important_vim_editor_commands/ Fri, 03 Jul 2020 18:24:23 +0000 https://linuxhint.com/?p=62774 The vim text editor is an improvement over the original vi editor. This program is an elite text editor that you can have your hands on for free! Vim is free and open-source and is available for all the major platforms. Vim is a CLI text editor that comes with tons of features and support from the programming community.

This article will cover some of the most important vim commands you should master to make the most out of this text editor. Priority is placed on simple, rather than complex, commands that are useful to use with this program. As the title suggests, this article includes 25 of the most important vim editor commands.

vim on Linux

As mentioned earlier, Vim is an improved version of the vi editor. The vi editor comes pre-installed with any Linux distro, as vi is part of UNIX. However, the vim editor does not come pre-installed, so you will have to install vim separately. Vim is a super popular editor and should be available directly from the package server(s) of your distro.

Below, I have listed the commands to install Vim for some of the popular Linux distros out there. If you do not see your distro down here, please do your own research to perform this step.

Debian/Ubuntu and derivatives:

$ sudo apt-get install vim -y

Arch Linux and derivatives:

$ sudo pacman -S vim

CentOS/RHEL and derivatives:

$ sudo yum install vim

openSUSE and derivatives:

$ sudo zypper install vim

Important vim Commands

Vim offers a number of commands by default. Mastering these commands can guarantee a consistent Vim experience wherever you go. However, Vim also allows you to create your own commands. This article will discuss mostly the built-in vim commands.

First, launch Vim by running the following command:

$ vim

Exiting vim

If you have ever been in the vim editor, then you might be familiar with this meme. Anyone using Vim for the first time has probably seen this issue, including myself. Upon opening the vim text editor, many do not know how to exit the editor. It may sound stupid, but I believe this to be a common experience among Vim users. When you launch the editor, vim can show you how to quit the editor.

To exit the vim editor, run the following command:

$ :quit

However, the recommended way is to use the abbreviation of the quit command. This will save some time.

$ :q

Say you want to discard the current changes and exit vim without saving any changes you made. Use the following command instead to quit vim and discard changes:

$ :q!

Navigation

Navigating through the text is a necessary function. With vim, there are two ways you can navigate through the text you are editing: by using the arrow keys, or by using the hjkl keys.

  • H – left
  • L – right
  • K – up
  • J – down

All of these keys are located at the home row, so you can access these commands quickly and easily. It takes a little bit of practice to get used to this navigation system, though.

Insert Mode

Vim is a modal editor, behaving differently in whatever mode you might be on. For most, the “Insert” mode should be familiar. In fact, most other text editors work in this manner.

To enable “Insert” mode, press i.

To return to normal mode, press Esc, and you will return to the “Normal” mode.

Deleting Characters

Need to delete something you just typed? Depending on the mode that Vim is in, there are two ways to delete characters.

If you are on “Normal” mode, press x to delete characters. The “x” button behaves like the “Delete” key in a normal text editor. If you require backspace-like behavior, then use X (uppercase).

If you are in “Insert” mode, using the “backspace” or “Delete” key will delete text.

Copy, Cut, and Paste

Copy/paste is one of the most common functions of a text editor. In the case of Vim, this function becomes a bit more complicated.

To select the text you want to copy or cut, move your cursor to the desired location and press v (lowercase). If you want to select the whole line, then press V (uppercase).

To copy the selected text, press y. To copy the entire line, press yy or Y (uppercase). To cut the selected text, press d.

To paste, press P (uppercase). If you want to paste after the cursor, press p (lowercase).

Saving a File

Once you have performed all the text edits that you require, it is now time to save the file.

To save the currently open file, enter the following command:

$ :w

Deleting Line

To delete the current line, move your cursor to the desired line and enter the following command:

$ dd

Undo and Redo

If you have entered a typo or wish to undo an action, quickly press the undo/redo button(s). Chances are that you may need to use the undo function more frequently when using vim.

To perform an undo, press u.

To perform a redo, press “Ctrl + R”.

Moving to the Start/End of a Line

To bring your cursor back to the beginning of the current line, press ^. The “Home” key will also perform this function.

Search and Replace

Vim offers a robust search feature. To perform a basic search, use the following command structure:

$ /<search_term>

The above command will search forward. To search backward, use the following command instead.

$ ?<search_term>

To go to the next search result, press n (lowercase). To go to the previous search result, press N (uppercase).

Replace in vim is also an interesting feature. To perform a replacement, you must first understand the command structure. To do so, enter the following command:

$ :s/<search_word>/<replace_word>/<flag>

There are two flags you should focus on: g (replace the current line only) and gc (replace for all lines). If you use the flag gc, vim will ask whether you want to replace the selected text.

Split View

In some situations, you may have to work with multiple text files at once. In this case, you can split the vim screen into multiple sections.

There are two types of splits that vim offers: vertical and horizontal splits.

To perform a vertical split, run the following command:

$ :vsplit <path_to_file>

To perform a horizontal split, run the following command:

$ :split <path_to_file>

You can also have multiple splits at the same time.

To move from one split-screen to another, you can use “Ctrl + W” (press twice to switch). If you want to manually navigate to a window, press “Ctrl + W + H/J/K/L”.

Customizing vim

Vim offers many options for customization. You can customize almost any feature with the help of vimrc and plugins. You may find it strange, but vim has plenty of plugins, thanks to the awesome community surrounding this text editor program.

The first step of customizing vim is mastering the vimrc file, a configuration file that vim loads every time it starts. Vim uses this script to configure behavior, load plugins, and perform various actions. The vimrc file is written in vimscript language. Check out the beginner’s guide to vimrc here.

Final Thoughts

Vim is a powerful editor with infinite possibilities. While it is easy to learn certain features and commands of vim, mastering this text editor will take more effort and time. However, once mastered, you will definitely feel the difference using this program. Hopefully, this guide was able to help you in some way.

Vim also comes with vimtutor, a fun vim tutorial app to teach yourself vim.

$ vimtutor

Here are some interesting tutorials for you. Check out common vim shortcuts, vim syntax highlighting, vim plugins, and Vim Awesome, a major repo of vim plugins. If you are interested in mastering every single aspect of Vim (along with all its advanced features), I highly recommend checking these tutorials out.

Enjoy!

]]>
VIM Exit and Save, for Beginners https://linuxhint.com/vim_exit_and_save/ Tue, 28 Apr 2020 16:59:07 +0000 https://linuxhint.com/?p=59196

Syntax to Exit and Save from VIM Editor

Press esc key to ensure you are in command mode.  Then press the colon key to enter command line mode.  Command line mode will have a colon at the bottom left of the screen where you can enter command lines.  Then press ‘wq’ and ‘enter’ to indicate exit and save.  ‘w’ is short for write indicating save the file contents to disk.  ‘q’ is short for quit which indicates exit vim editor.

:wq

The screenshot below is of entering the ‘wq’ command in command line mode to instruct vim to exit the program after saving the contents, aka write and quit.

Understanding VIM Modes and How to use Them

Vim’s primary modes of operation are Insert Mode, Command Mode, Command Line Mode and Visual Mode.  The editor will be in one of these modes at any time, and interacting with the vim editor using keystrokes will take different actions depending on which mode the editor is currently in.  If you try to enter ‘wq’ to save and exit, when in insert mode it will not in fact save the contents you are working on nor exit the vim editor.  So therefore you need to be aware when using vim which mode you are in.

Insert Mode: in this mode you can actually type content into a file.  You are doing editing and not instructing Vim the editor what to do other than what text to enter into a file contents.  You can enter Insert Mode from the Command Mode by hitting the ‘i’ key which stands for insert.  You can also hit the ‘a’ key which will also enter the insert mode, but after moving the cursor after the current position, which is why ‘a’ in this case stands for append.

Command Mode: this is the mode where keystrokes are used to instruct vim what to do and how to function but not for entering new text or editing text in a file.  To enter Command Mode hit the ‘esc’ key on the keyboard.

Command Line Mode: a little mini command line prompt appears at the bottom left of the screen and allows you to enter commands such as we have shown in this tutorial, you can use ‘w’ which stands for writing a file and you can use ‘q’ which stands for quitting the editor.  These can be combined into a single instruction and you will exit the editor and save the file.

Visual Mode: visual mode allows you to highlight text and then use that selected text in copy and paste or other common operations on selected text.  All of this can be done from the keyboard without a mouse unlike GUI based editors such as Notepad or Visual Studio.

How to Save Your Contents but not Exit the Editor

If you want to save your work in the file you are editing but not exit the vim editor just use the ‘w’ command to write the file and omit the ‘q’ command as shown below.

:w

How to Exit the Editor But Not Issue a Save

If you want to exit the editor only, and not issue a save command, then just issue the ‘q’ command in the command line mode as shown below.  This command assumes you have not made any changes so far to the content or else you will get an error as shown in the second screenshot below.

:q

No error above.

Error above because exit command was issued without a save file command.

How to Exit the Editor But and Not Save Changes

If you have made changes, but you DO NOT want to save these changes to disk and want to revert to the previous content at the time of the last save issue the ‘q’ command with the ‘!’ command at the command line mode as shown below.

:q!

Conclusion

All of the information above may seem like too much complexity just to exit the editor and save the contents of the file you are working on, but there are reasons for it and everything is logical.  The vim editor can be operated almost entirely from the keyboard without use of the mouse which is ergonomically and speed wise usually more efficient for programmers and experience IT professionals.  Therefore all of the instructions must be specified with different key combinations and not the use of a graphical mouse pointer.  In order to accommodate rapid programming and usage of VIM the different modes of operation were introduced so the same keys can have different actions depending on the current mode.  So when you want to do a quick simple command to exit the editor while at the same time saving the contents of the file you are doing, it’s just a few keystrokes on the editor and not browsing through menus with a clumsy mouse.  Learn the tricks of VIM and you will be on the path to being an elite coder or systems administrator.

More VIM Education

]]>
Best vim color schemes and how to install https://linuxhint.com/best_vim_color_schemes/ Sat, 22 Feb 2020 12:48:50 +0000 https://linuxhint.com/?p=55471 Vim, an open-source editor comes with a few color schemes installed by default. However, you can download and install a new color scheme if you are bored with the default color scheme or if you want to give a new look and feel to your code.

Color schemes are basically a combination of colors that describe how source code can be highlighted. It comes handy as the colors can help you identify various data types, functions, parameters, etc. This way you can find what you are looking for. Sometimes, the syntax highlight can help you find syntax errors. Also, note that the color schemes only applied to the source instead of the editor’s background.

In this article, we will list some of the best vim color schemes and also how to download and install a new color scheme in your Vim editor. In addition, we will also learn how to use the pre-installed color scheme in Vim editor.

Check out following few color schemes to improve your Vim experience:

  1. Solarized Dark
  2. Gruvbox
  3. Ayu
  4. Palenight
  5. Inkpot
  6. Monokai
  7. Vim-one
  8. Purify

Turn on syntax highlighting

To turn on the syntax highlighting in vim, shift to Normal mode by pressing the Esc key. Then type

:syntax on

It will turn on the syntax highlighting and will show the default theme.

To permanently turn on the syntax highlighting, edit the ~/.vimrc file by using the following command in Terminal:

$ vi ~/.vimrc

Then add the following line in it:

syntax on

View preinstalled color schemes

Some color schemes are already installed on your system.  You can find those color schemes in the /usr/share/vim/vim*/colors directory as .vim extension.

To view pre9nstalled schemes from the terminal, run the following command in Terminal:

$ ls –l /usr/share/vim/vim*/colors

Set a Color Scheme

To set a new color scheme in vim, open vim editor and press Esc to shift to Normal mode. Then type the color scheme followed by the name of the color scheme as follows:

:colorscheme morning

Or just

:colo morning

Also, you can permanently change the vim color scheme be editing the ~/.vimrc file and adding the following line:

colorscheme morning

Installing a new color scheme

To install a new color scheme for Vim, you will need to download it from the git hub repository. Here I am going to download a vim theme “Monokai” from the Git repository.

For Monokai color scheme, open the following link, then right-click and save it as .vim in your Downloads directory.

https://raw.githubusercontent.com/crusoexia/vim-monokai/master/colors/monokai.vim

Alternatively, you can use wget followed by the wget to download the .vim file. Once downloaded, move the downloaded .vim file to the ~/.vim/colors directory. In some distributions like in mine, this directory might be in /etc/vim/colors. Therefore, to move the .vim file, run the following command:

$ mv ~/Downloads/monokai.vim  ~/.vim/colors

or

$ mv ~/Downloads/monokai.vim  /etc/vim/colors/

This color scheme is now ready to be used. To test it, open  a vim file and type the following line in normal mode:

: colo monokai

You can see the new vim color scheme has been installed successfully.

To permanently set the newly installed color scheme, edit the ~/.vimrc file and add the following lines:

syntax on
:colorscheme monokai

Once done, shift to Normal mode using the Esc key and type the following command to save and exit the file.

Conclusion

This is how you can install and set the new color scheme in your Vim editor. The next time when you open any text file in vim, the syntax highlighting will be by default enabled and the new color scheme is applied. To shift back to the default color scheme, simply replace the new color scheme name with the “default”.

]]>