chapters/03.markdown @ d7ce6dbc63d3

Credit for flatcap
author Richard Russon (flatcap) <richard.russon@gmail.com>
date Sat, 21 Apr 2012 02:48:14 +0100
parents e66e6a4e104d
children beb0d41a8929
Basic Mapping
=============

If there's one feature of Vimscript that will let you bend Vim to your will it's
the ability to map keys.  Mapping keys lets you tell Vim: "when I press this
key, I want you to do this stuff instead of whatever you would normally do".

We're going to start off by mapping keys in normal mode.  We'll talk about how
to map keys in insert and other modes in the next chapter.

Type a few lines of text into a file, then run:

    :::vim
    :map \ x

Put your cursor somewhere in the text and press `\`.  Notice how Vim deleted the
character under the cursor, just like if you had pressed `x`.

We already have a key for "delete that character under the cursor", so let's
change that mapping to something slightly more useful.  Run this command:

    :::vim
    :map \ dd

Now put your cursor on a line somewhere and press `\` again.  This time Vim
deletes the entire line, because that's what `dd` does.

Special Characters
------------------

You can use `<keyname>` to tell Vim about special keys that are hard to type.
Try running this command:

    :::vim
    :map <space> viw

Put your cursor on a word in your text and press the space bar.  Vim will
visually select the word.

You can also map modifier keys like Ctrl and Alt.  Run this:

    :::vim
    :map <c-d> dd

Now pressing `Ctrl+d` on your keyboard will run `dd`.

Commenting
----------

Remember in the first lesson where we talked about comments?  Mapping keys is
one of the places where Vim comments don't work.  Try running this command:

    :::vim
    :map <space> viw " Use space to select a word

If you try pressing `<space>` now, something horrible will almost certainly
happen.  Why?

When you press the space bar now, Vim thinks you want it to do what
`viw<space>"<space>Use<space>space<space>to<space>select<space>a<space>word`
would do.  Obviously, this isn't what we want.

This mapping is even more interesting though, because if you look closely at its
effect you might notice something strange.  Take a few minutes to try to figure
out what it is before you move on.  Don't worry if you don't get it now, because
we'll talk about it more later.

Exercises
---------

Map the `-` key to "delete the current line, then paste it below the one we're
on now".  This will let you move lines downward in your file with one keystroke.

Add that mapping command to your `~/.vimrc` file so you can use it any time
you start Vim.

Figure out how to map the `_` key to move the line up instead of down.

Add that mapping to your `~/.vimrc` file too.

Try to guess how you might remove a mapping and reset a key to its normal
function.