# Text Editing with Vim

## Introduction to Vim

Vim is a text editor that can be used directly from the command line. Vim is based on an older text editor called vi which was developed in 1976 as part of the early BSD version of Unix. Vim is an improved version of vi which was initially developed in 1991, and which is still actively maintained.

Vim allows us to edit files directly on the command line when connected to a remote server like cpsc.umw.edu. Using Vim can be quite different from graphical text editor programs, but it can be extremely efficient. Vim offers editing tools and shortcuts not present in other text editors. Taking the time to learn it will pay off in the long run.

## The Vim Command

To start using Vim, you can run the vim command:

ifinlay@cpsc:~$vim  Unlike the other commands we have used, vim is interactive. It does not run immediately and print its output, but rather runs for a while and only returns you to the command prompt when you quit. You should see something like this, if you run vim as shown above: The initial Vim screen. Most of the time, we will pass vim a file name as an argument: ifinlay@cpsc:~$ vim file


Vim opening a new file.

If the argument is an existing file, Vim will open it and allow you to edit that file. If it is not an existing file, Vim will create it.

## Modes

Vim is different from most text editors in that it has modes. Which mode Vim is in determines how the keys you press will be interpreted. This increases the learning curve of Vim, but allows Vim to use single keys for different things in different modes which allows for fewer key presses.

Below are some of Vim's most useful modes:

• Command Mode

The default mode that Vim starts in. Used for entering commands such as to cut, copy, paste or format text.

• Insert Mode

Used to actually enter text into the file you are editing.

• Replace Mode

Like insert mode except that the text being entered overwrites existing text in the file.

• Visual Mode

Used to visually select text.

The graph below shows how you can switch between Vim modes:

In command mode, the keys v, i, and Shift-R take you to visual, insert and replace mode respectively. In any mode, you can reach command mode by tapping the Escape key.

## Moving Around

One benefit of Vim is that, in command mode, you can navigate the file you are editing without moving your hands off of the home row of your keyboard.

The common way to navigate a file one character at a time is to use the h, j, k and l keys:

 h Left j Down k Up l Right

You can also use the arrow keys to navigate, but that moves your hands off of the home row of the keyboard.

Vim also has several other movement commands that allow you to move to different positions in the file:

 w Forward one word. b Backward one word. gg Top of the file. G Bottom of the file. 12G Go to line 12. ^ Beginning of the line. \$ End of the line.

This is only a small subset of the motion commands that Vim supports. We will look at more later on in the course.

## Saving and Quitting

We also need to be able to save changes to our file. This is done with the :w command. When you are in command mode, and type the colon character, your cursor will jump to the bottom of the screen.

If we passed Vim a file name as an argument when we started it, or if we have previously saved the file, then Vim will save with the :w command.

If not, then Vim will give us an error message:

To specify a filename, we can use:

:w filename

Replacing "filename" with the name of the file we want to save to.

To quit Vim, we can use the :q command. If we have unsaved work, Vim will warn us:

We have two options, we could either save our file first, or use the :q! command to quit without saving (generally a bad idea of course).

There are two ways to save and quit with one command, :wq and ZZ.

## Copying, Cutting and Pasting

Some of Vim's most commands for cutting, copying and pasting text are summarized in the table below:

 x Cut the current character. dd Cut the current line. dw Cut from here to the start of the next word. yy Copy the current line. yw Copy from here to the start of the next word. p Paste after the current position. P Paster before the current position.

Note that in Vim, 'd' stands for delete, but corresponds to the familiar notion of 'cut'. Likewise, 'y' stands for yank and corresponds to copy. 'p' actually stands for put, but means the same thing as paste.

Of course you must be in command mode to use any of these commands. If you are in insert mode and type 'dd', then it will actually write the letters 'dd' into the file!

Note that Vim does not use the same clipboard as the rest of your operating system. If you have a web browser window open, and copy some text from a web page, you cannot paste it into Vim using 'p'. If you think about it, the browser is running on your local computer, while Vim is running on the CPSC server, a completely separate machine. So Vim has no clue what is in your clipboard.

If you want to copy text from another window into Vim, you will have to use the paste command of your terminal. Recall that a terminal is the program running on your local machine which sends your commands over SSH. The keyboard shortcut to do this differs by terminal, but "Control-Shift-V" is common. Also, make sure Vim is in insert mode, otherwise it will interpret the characters being pasted as commands.

You can also copy text from Vim into another program on your local system using your terminal. Generally, you highlight the text in the terminal, and then copy it using the terminal. This differs by terminal. Some use "Control-Shift-C" and some copy it automatically when selected. Then it is in your local system buffer.

## Searching

To search for something in a file in Vim, you can type / key followed by whatever text you want to search for, then hit enter. Vim will take you to the next instance of that text in the file (or tell you if it is not found).

For example, to search for the text "function", we could use:

/function

To switch between multiple matches, use the n and N keys.

To search backwards, we can use ? instead of /:

?function

To search for the word currently under the cursor, we can use the * key. For example, if the cursor is any place in the word "function" below:


void function() {
// ...
}


And we press the asterisk key, then Vim will search forward for the next appearance of the word "function" in the file. This is handy for moving between uses of functions or variables in programming.

If we want to search backwards for the word under the cursor, we can use # instead of *.

## Replacing

Vim has a very powerful replace command. The basic usage of it is as follows:

:%s/old text/new text/

This will replace "old text" with "new text" on each line where "old text" appears.

The '%' specifies that the replacement should be done for the whole file. The 's' stands for substitute, and the / characters separate the old and new sections.

The substitute command can also take optional flags at the end. One useful one is the 'g' flag:

:%s/old text/new text/g

With the g flag, Vim will replace the old text with the new text multiple times on the same line if necessary. For example, say we are renaming 'x' to 'x_position' in the code below:


int x;
int temp = x * x;

If we perform the command:
:%s/x/x_position/

Then only the first x on each line will be replaced giving us this:


int x_position;
int temp = x_position * x;


With the 'g' flag:

:%s/x/x_position/g
We get this:

int x_position;
int temp = x_position * x_position;


Another useful flag is the 'c' flag which stands for confirm. With this flag, Vim will ask us if we want to perform the replacement at each match:

:%s/x/x_position/gc

Each time Vim finds the 'x' this time, it will ask us whether we want to replace it with 'x_position'. This is great if you think your substitution might catch more than you intended.

## Visual Mode

Vim has command mode commands for manipulating arbitrary sections of text. However, this can be more easily accomplished with visual mode. This mode allows us to select a piece of text, and then apply some operation to it (such as cut, copy or substitute).

To enter visual mode, use the 'v' key from command mode. Then, any movements we do will move one end of the visual selection:

Vim in visual mode.

If we want to manipulate the other end of the selection, we can use the 'o' key.

The following commands will manipulate our selection in visual mode:

 d Cut the selection. y Copy the selection. = Automatically indent the selection. > Increase the indentation level of the selection. < Decrease the indentation level of the selection.

The last three are helpful for editing source code. Vim is able to automatically indent your code in several programming languages based on the curly braces etc. It can also increase or decrease the indentation level.

Something else we can do with visual mode is to perform a substitution only in the selection. In the example above, the substitute command:

:%s/x/x_position/gc

Will replace x with x_position in the entire file. What if we only want to perform the substitution in one section? We simply select the portion of the file visually, then replace the "%" character with "'<,'>" as in the example below:

:'<,'>s/x/x_position/gc

You actually do not even need to type that sequence yourself. If you type the colon inside visual mode, Vim will automatically place the '<,'> onto the command line for you.

There is also a line visual mode, which you can enter with the "Shift-V" shortcut. This is exactly like visual mode, except that it selects entire lines as opposed to potentially only a potion of a line. If you want to work with whole lines, this is more convenient.

Vim in line visual mode.

## Undo and Redo

To undo some action in Vim, use the u command. To redo it, use Control-R. That is, hold the control key and tap the 'r' key. This is one of the few times Vim uses a modifier key for a common command.

One thing to keep in mind with Vim is that all trips to insert mode are counted as just one indivisible "action". This means that if you go into insert mode, and type a large amount of text, then go to command mode and enter the undo command, all of the text will be "undone".

## Learning Vim

We have covered most of the basic text editing features that most text editors support. Vim however has far more functionality that we have not covered yet.

Some tips for learning Vim:

• Run the vimtutor Command

Vim comes with a tutorial that can be invoked with the vimtutor command. The tutorial contains more information than is given here.

• Look to Improve

When reading a long list of Vim commands, you're unlikely to remember most of them right away. Instead, use Vim for a while and then, once you are comfortable with the basics, look for ways to improve your work flow. If you find yourself doing something tedious or annoying, there's almost certainly a better way.

• Practice!

If you are not using the command line for your current programming class, you can still use Vim to write code. Vim can be installed locally on Windows, Linux and OSX. If you are using an IDE, chances are you can install a Vim plugin that will allow you to use Vim shortcuts in that IDE.