Home CPSC 225

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:

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:

hLeft
jDown
kUp
lRight

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:

wForward one word.
bBackward one word.
ggTop of the file.
GBottom of the file.
12GGo 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:

xCut the current character.
ddCut the current line.
dwCut from here to the start of the next word.
yyCopy the current line.
ywCopy from here to the start of the next word.
pPaste after the current position.
PPaster 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:

dCut the selection.
yCopy 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:

Copyright © 2024 Ian Finlayson | Licensed under a Creative Commons BY-NC-SA 4.0 License.