Vim Hints 004 (HPR Show 1776)

Dave Morriss

Vim Hints 004 (HPR Show 1776)

More movement commands

So far we have seen how to move by character, by word and by line. We saw how Vim has two concepts of word with some demonstrations of what that means.

Now we will look at more movement commands.

This information can be found in the Vim Help (type :help motion.txt) and is online here. I will be making reference to the Vim documentation in this episode, even though it is very detailed and covers many aspects which we have not yet covered. There is a help page about Vim Help (type :h help) which is online here.

Sentences and paragraphs

Sentences and paragraphs are referred to as text objects in Vim.

A sentence is defined as ending at a '.', '!' or '?' followed by either the end of a line, or by a space or tab.

In Normal mode the ) command moves forward one sentence, and ( moves backward. Both commands, like those we have seen before, take a count, so 3) moves forward three sentences.

In the context of Vim a paragraph is a group of sentences which begins after each empty line.

In Normal mode the } command moves forward one paragraph, and { moves backward. Again both commands take a count, so 2} moves forward two paragraphs.

Moving up and down

There are many ways of moving up and down in a file. We have already seen two such commands: - and +. Both can be preceded by a number, so 10- moves up ten lines and positions to the first non-blank character and 10+ moves downwards in an equivalent way.

The G command will move to a specific line in the file. Typing a G on its own in Normal mode will move to the end of the file. Typing 1G will move to the first line of the file (there is also a gg command that does the same). Otherwise, any number before the G will move to that line, so 42G moves to line 42.

The gg command mentioned above can also be used to move to a particular line, so 42gg moves to line 42 in the same way as 42G.

Searching

Not surprisingly, with Vim you can search the file you are editing. Full information can be found in the Vim Help (type :h pattern.txt) or online here.

Searching forward is initiated by typing the / key in Normal mode, and to search backward the ? key is used.

When a search is initiated the / or ? character appears in the command line at the bottom of the screen and the next characters you type are the search target. The typing of the target is ended by pressing the <CR> (or <Enter>) key and the search is initiated.

The search target can be something quite simple like a sequence of letters and numbers, but it is actually a pattern which can be a regular expression. This is quite a large subject so we will deal with it in more depth in a later episode of this series. For now we will restrict ourselves to the simpler aspects.

Typing the following sequence in Normal mode:

/the<CR>

will result in a search for the characters the and the cursor will be positioned on the next occurrence forward from the current location.

Pressing the <Esc> key while typing the search target will abort the search.

Once the first occurrence has been found pressing n will move to the next occurrence. This results in forward movement if the search used / and backward movement when using ?.

Pressing N causes the search to change direction.

Preceding a search by a number causes it to skip to the nth instance of the target. So typing 3 then:

/but<CR>

will position to the third instance of but from the current cursor position.

There are a number of settings that affect the searching process, and some recommended ones are listed and explained below in the Configuration file section. In short they do the following:

ignore the case of letters when searching except when the target contains a capital letter, when an exact match is searched for

start the search as the target is being typed

continue the search at the top (or bottom) of the file when the bottom (or top) is reached

highlight all the search matches

Matching pairs

Vim can move the cursor between matching pairs of characters such as '(' and ')', '{' and '}' and '[' and ']'. The command that does this in Normal mode is %.

If the cursor is placed on the opening character of the pair it will jump to the closing one. If on the closing character it will jump to the opening one. If it is positioned before the opening character of the pair it will jump to the closing one. If it is between the pair it will be positioned to the opening character.

The command will also move between the start and end of a C-style comment:

/* C-style comment */

It is possible to extend the pairs of characters that this command recognises, and there is a Vim plugin available which considerably enhances its functionality. I will leave this subject until later in this series when we look at Vim plugins.

Commands that make changes

When Vim is editing a file it makes a copy of its contents into a buffer. This is what is displayed and can be manipulated. As we already know, the changes can be discarded with :q! or saved to the file with :w. Changes can also be undone with the u command.

The commands in this section perform changes to the buffer.

Insert commands

These are commands that insert new text into the buffer. They can all be preceded by a count.

Full information can be found in the Vim Help (type :h insert.txt) or online here.

Appending text

The a command appends text after the cursor. Vim enters Insert mode and text will continue to be added until the Escape (<Esc>) key is pressed. If there was a count before the command the insertion is repeated that many times.

The A command also appends text but at the end of the line

Inserting text

The i command inserts text before the cursor. As before Insert mode is ended by pressing the Escape (<Esc>) key. If there was a count before the command the insertion is repeated that many times.

The I command inserts text at the start of the line before the first non-blank. The insertion is repeated if a count was present.

Vim has an alternative command gI which is like I but inserts the text in column 1.

Beginning a new line

The o command begins a new line below the cursor and allows text to be entered until Escape (<Esc>) is pressed. The count causes the new line and any text to be repeated.

The O command begins a new line above the cursor and allows text to be entered until Escape (<Esc>) is pressed. The count causes the new line and any text to be repeated.

Examples of text insertion

Typing 80i-<Esc> at the start of a blank line will create a line of 80 hyphens.

Typing eas<Esc> while on a word will append an s to it

Typing 10oHello World will cause 10 lines containing Hello World to be inserted

Deletion commands

Full information can be found in the Vim Help (type :h change.txt) or online here.

The x command in Normal mode deletes the character under the cursor. With a count it deletes characters after the cursor. It will not delete beyond the end of the line.

The X command in Normal mode deletes the character before the cursor. With a count it will delete that number before the cursor. It will not delete before the start of the line.

The dd command deletes lines, one by default, or more if a count was given.

The D command deletes from the character under the cursor to the end of the line, and if a count was given, that number minus 1 more full lines.

There is a d command as well but we will look at that shortly.

Change commands

The cc command deletes the number of lines specified by the count (default 1) and enters Insert mode to allow text to be inserted. The <Esc> key ends the insertion as before.

The C command deletes from the cursor position to the end of the line, and if a count was given, that number minus 1 more full lines, then enters Insert mode. The <Esc> key ends the insertion as before.

There is a c command as well but we will look at that shortly.

The s command deletes count characters and enters Insert mode, which is ended with the <Esc> as usual.

The S command is a synonym for the cc command described above.

Changes and movement

At last we can join together the movement commands and some of the commands that change things in Vim. This is where some of the real editing power of Vim resides.

Deleting with movement

We skipped the d command in the above section because it only really comes into its own in conjunction with motions. This command when followed by a motion command deletes the thing encompassed by the motion.

So, for example, dw deletes to the beginning of the next word from the position of the cursor. The table below shows some examples of the operator+movement combinations:

Command | Action
dw | Delete from the cursor to the start of the next word
de | Delete from the cursor to the end of the next word
d$ | Delete from the cursor to the end of the line (same as D)
d0 | Delete from before the cursor to the beginning of the line
d) | Delete from the cursor to the end of the sentence

Changing with movement

Similar to the d command we also skipped the c command in the above section.

So, for example, cw deletes to the beginning of the next word from the position of the cursor, then enters Insert mode for a replacement to be inserted. The table below shows some examples of the operator+movement combinations:

Command | Action
cw | Change from the cursor to the start of the next word
ce | Change from the cursor to the end of the next word
c$ | Change from the cursor to the end of the line (same as C)
c0 | Change from before the cursor to the beginning of the line
c) | Change from the cursor to the end of the sentence

There are many more ways of deleting and changing text with movement which we will look at in more detail in a future episode.

Configuration file

The story so far

In the last episode we extended the configuration file with a ruler and status line. Now we can add some more settings that make Vim more convenient to use.

Full information on the options available in Vim can be found in the Vim Help (type :h options.txt) or online here.

Stop beeping!

Vim has a tendency to beep to alert you to events and errors. This can be a tiny bit annoying, especially in a shared workplace. Instead of an aural alert you can request a visual one with the command:

set visualbell

The abbreviation is se vb and the inverse is set novisualbell or se novb.

Showing incomplete commands

As we have seen, Vim commands can consist of sequences of numbers and command letters. For example 23dd means delete 23 lines.

The command:

set showcmd

makes Vim show the command that is being typed. So with 23dd the 23d part will be visible waiting for the final d, after which the display will be cleared and the command actioned.

The display of the partial command is shown in the status line at the bottom of the screen.

The abbreviation is se sc and the effect can be reversed with set noshowcmd or se nosc.

Command history

By default Vim will remember the last 50 ':' commands (and the last 50 searches) in history tables. When you press the ':' key or begin a search with '/' or '?' the history table can be traversed with the up and down cursor keys. The size of all of the history tables can be extended with the command such as the following:

set history=100

The abbreviation for the above command is se hi=100.

Ignore case when searching

Normally Vim searches for the exact case you provide in your search target. You can switch this off with the command:

set ignorecase

You might think that this is a little counter-intuitive; I certainly did when I first encountered it. However, in conjunction with the next command:

set smartcase

it seems more usable. When the smartcase option is enabled Vim will search for both lower and upper case forms when there are only lower case letters in the target, but will search for an exact match when the target is mixed case.

The abbreviation for set ignorecase is se ic and for set smartcase is se scs. The options can be reversed with set noignorecase (se noic) and set nosmartcase (se noscs).

Searching incrementally

While typing a search pattern, Vim can show where that part of the pattern which has been typed so far matches. This feature is enabled with the incsearch option. The matched string is highlighted, but if the pattern is invalid or not found, nothing is shown. In this mode the screen will be updated frequently so it should not be used over a slow link to a remote system!

set incsearch

The abbreviation is se is and the option is turned off with set noincsearch or se nois.

Wrapping the search around

When searching Vim normally stops at the end (forward searches) or beginning (reverse searches) of the file. With the wrapscan option searches wrap around.

set wrapscan

The abbreviation is se ws and the option is turned off with set nowrapscan or se nows.

As the search wraps a message is displayed in the status line.

Highlighting the search

Vim can be configured to highlight all occurrences of the search pattern with the command:

set hlsearch

The abbreviation is se hls and the option is turned off with set nohlsearch or se nohls.

The highlight stays in effect until cancelled, which can get a little tedious, so Vim allows the current pattern match to be turned off with the command :nohlsearch (abbreviated to :nohl).

Enable extra features in INSERT mode

Vim allows more functionality when in Insert mode than vi. It is possible to work in Insert mode most of the time such as in editors such as Nano. Enabling these features is done with the set backspace option. This is followed by a list of up to three items separated by commas:

indent - allows backspacing over auto indents (not covered yet in this series)

eol - allows backspacing over line breaks (thus permitting inserted lines to be joined)

start - allows backspacing over the start of the insert to previously existing text

To get the full functionality of Vim it is probably wise to use all three items:

set backspace=indent,eol,start

The abbreviation is se bs=indent,eol,start.

Summary

Movement

), ( move forward and backward by sentences

}, { move forward and backward by paragraphs

G, gg move to a specific line or beginning or end of file

% move between matching pairs of characters

Searching

/ to search forward

? to search backwards

Changing

a and A to append text

i and I to insert text

o and O to open a new line and insert text

x and X to delete characters

dd and D to delete lines

dmotion to delete up to a movement target

s and S to change characters

cc and C to change lines

cmotion to change up to a movement target

Configuration file

" Ensure Vim runs as Vim
set nocompatible

" Keep a backup file
set backup

" Keep change history
set undodir=~/.vim/undodir
set undofile

" Show the line,column and the % of buffer
set ruler

" Always show a status line per window
set laststatus=2

" Show Insert, Replace or Visual on the last line
set showmode

" Stop beeping! (Flash the screen instead)
set visualbell

" Show incomplete commands
set showcmd

" Increase the command history
set history=100

" Turn off case in searches
set ignorecase

" Turn case-sensitive searches back on if there are capitals in the target
set smartcase

" Do incremental searching
set incsearch

" Set the search scan to wrap around the file
set wrapscan

" Highlight all matches when searching
set hlsearch

" Allow extra movement in INSERT mode
set backspace=indent,eol,start

Links

Vim Help:

Using Help: http://vimdoc.sourceforge.net/htmldoc/helphelp.html

Motion: http://vimdoc.sourceforge.net/htmldoc/motion.html

Searching: http://vimdoc.sourceforge.net/htmldoc/pattern.html

Insertion: http://vimdoc.sourceforge.net/htmldoc/insert.html

Changing: http://vimdoc.sourceforge.net/htmldoc/change.html

Options: http://vimdoc.sourceforge.net/htmldoc/options.html

Graphical Cheat Sheet: http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html

Vim Hints Episode 3 http://hackerpublicradio.org/eps.php?id=1734