Official website for Linux User & Developer
FOLLOW US ON:
Nov
10

Master Vim – Tutorial

by Himanshu Arora

Take a step ahead, learn some advanced features and get more productive with the Vim editor

Thanks to a steep learning curve, many people either avoid using Vim or use it on a very basic level. If you’re guilty of either of these then you’re really missing out.

Vim, first released in November 1991, is a command-line-based text editor that was developed by Bram Moolenaar as an improved Vi clone for Amiga platform. Besides including all the features of the popular Vi editor, it also contains a lot of new features and so derives its name – from ‘Vi improved’. As well as being a text editor, Vim can be used as an integrated development environment by software programmers. Vim provides a wide range of features, but as it is a command-line utility it has a steep learning curve. Please note that Vim is not a word processor, which means that you cannot do layout-related changes with it.

While you will get to know about the real strengths of the Vim editor once you master it, on the whole some of the prominent pros include fast text editing (because of little to almost no use of the mouse) and easy execution from anywhere on the command line. There are also many GUI front-ends (like gVim) available for Vim.

Although it is command-line based, Vim has a loyal following and is extensively used by system administrators and software programmers. Though it is hard to learn and understand all the features that Vim provides, in order to reap its real benefits it is essential to master Vim for your day- to-day work.

Through this article you will learn how to work with multiple files, how to indent and fold code, how to search and replace keywords, how to split the Vim window horizontally/vertically, and many other related features provided by Vim.

Note: This article assumes that you have some basic knowledge (opening, editing, saving and closing a file) of the Vim editor.

text editor IDE
Just type :help and Vim displays some valuable info for newbies

Resources

Vim

Step by step

Step 01

Work with multiple files

While most regular users use Vim to edit one file at a time, it can also be used to edit multiple files in parallel. To open multiple files with the Vim editor, just provide names of all these files as arguments to the vim command. The first file is displayed by default. Type :n to switch to the next file, :prev (or :N) to switch to previous file, :bf to switch to first file, :bl to switch to last file and :bw to close the file.

Step 02

Work with multiple files

Sometimes it is required to open a new or an existing file while editing an already opened set of files. Well, this can be done by typing :e followed by the filename (along with a complete path if it’s not located in the current working directory).

Step 03

Get list of currently opened files in Vim

To get the list of files currently opened in the Vim editor, just type :ls. This will display list of opened files along with other information like the current line number of the cursor in a file, file in current active window (represented by %a), file in previous active window (represented by #) etc. Switch between current and previous active windows by typing :b#.

Step 04

Use wildcard characters

Vim also supports wildcard characters (like *, ? etc) while opening multiple files at a time. This is especially useful in cases where multiple log files begin with a common set of characters like the current date (2013-08-05– –.log), or where multiple programming source files have same language extension such as .c or .cpp.

Step 05

Copy-paste across the files Another frequent requirement is to copy from one file and paste into another. For this, you need to split the Vim window to open both files. This can be done either by using the -o option with the vim command (vim -o <file1-name> <file2-name>); or by opening a file with vim <file1-name>, then opening the second file in split window mode from within the active Vim window with :split <file2- name>. To switch cursor control between the two windows, press Ctrl+w (a couple of times).

Copy-paste operation across the files can be done as follows: open files in split mode (as explained above); copy the required text from one file; press Ctrl+w to switch the control to the other file; then paste the copied text.

You can also split a Vim window vertically. All you need to type is :vsp <file-name> from within an active window.

Step 06

Close all files

To close all the opened files in one go, add ‘a’ to regular close options like :q, :wq or :q!. So, to close all the files in a single shot, do something like :qa or :wqa or :qa!.

vim text editor IDE
Close all files

Step 07

Close files without closing Vim

Normally, when the last open file is closed, the Vim application also exits. But, if it is required to close the last open file without closing the application, then just type :bd. This closes the current file and opens an empty buffer.

Step 08

Fold blocks of code

Another frequent requirement – which software programmers usually have – is to fold some blocks of code in order to save window space. This helps them to focus on the required code blocks. Vim does support block folds. For this, the first step is to bring cursor inside the braces of the function definition. For example, bring the cursor to the first line of the function body. Once there, just type va}zf. As you type this, you will observe that va is used to activate visual mode in Vim, while } selects the complete block including curly braces and zf enables the fold.

To open the fold, press zo; to close it, press zc. Make sure that the cursor is within the block while performing fold open and close. Typing va}zf creates a fold (that is invisible). zo and zc work only when a fold is created. An existing fold can be deleted by typing zd.

Step 09

Manual indenting

Another important feature that Vim provides is code indentation. Software programmers are required to indent their code and Vim provides easy steps for code indentation. To indent a single line of code, you can use >> or << to indent the line to the right or left respectively. Multiple lines can also be indented using [number-of-lines]>> or [number-of-lines]<<; for example, 10>> or 10<<. This is a better technique than indenting each line, but you still need to count the number of lines to indent. This could prove frustrating, especially if the number of lines is very large.

Fortunately, there is another trick: to select the lines by working with Vim in visual mode. In order to do this, you first need to bring Vim into visual mode. This (as mentioned previously) can be done using va. Once in visual mode, use the arrow keys to select all the lines that you want to indent in one go. After this, all you need to do is press > or < and the whole selected area will be indented accordingly.

Step 10

Automatic indentation

For those programmers who want everything automated, Vim also provides an auto-indenting feature. For example, to enable auto-indenting for C code, use :set autoindent and :set cindent. Now, try writing some C code and you will see that Vim automatically produces indentation as you write it.

Sometimes, depending upon the existing settings of your Vim editor, lines might get indented to a number of spaces other than four spaces or any other default value that you desire. As a solution to this, you can set the number of spaces to indent using :set shiftwidth=<number-of-spaces>. For example, use :set shiftwidth=4 to indent lines by four spaces.

Step 11

Search words

To search for a word in the active window, simply type /[search keyword]. This will enable Vim’s search mode and find the first occurrence of the searched keyword. Use n (just press n) in order to search more occurrences of the keyword. Note that you cannot do a backward search here.

If you need to do a backward search then just type :?[search keyword]. This will enable Vim’s backward search mode. Again, use n to continue the search, but backwards this time.

Sometimes the keyword is present in the text/source file and it is desired to find other occurrences of that word in the current text/ source file. In this case, just put the cursor below that word and press * (ie Shift+8). This way, you can search for a word without even typing it.

Step 12

Replace words

Vim also supports search and replace operations. To execute a basic replace operation, just type :%s/[keyword- to-search]/[keyword-to-replace-with] to replace keyword-to-search with keyword-to- replace-with.

This trick is good if you want to replace all the occurrences of a searched keyword, but what if it is desired to replace only selected occurrences? Well, there is a way through which you can run a search and replace operation in interactive mode. This means that Vim will confirm before replacing the keyword each time. This can be done through :%s/[keyword-to-search]/[keyword-to- replace-with]/c.

The first occurrence is always highlighted and Vim displays a prompt (in green, at the bottom) where you can input your choice of whether you want to replace this occurrence or not. Here, y = Yes, replace this occurrence; n = No, skip this occurrence; a = Replace this and all other occurrences; q = Quit the command; l = Replace this match and then quit the command.

Use Ctrl+e (^E) and Ctrl+y (^Y) to scroll the window up and down in this mode. Also, use i and I (along with /c, for example /ci or /cI) for case-insensitive and case-sensitive search.

  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.
    • Geoff Halsey

      I use to avoid Vim, but if you are working on Linux servers in a text only environment you soon become familiar with it. It really comes into its own on editing conf files, with its built in colour coding. When you return to a graphical environment you miss, it and start using there too.