Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Vimscript basic mapping


May 24, 2021 Vim


Table of contents


If Vimscript has a feature that allows you to customize Vim to your will, it's not keyboard mapping. You can tell Vim via keyboard mapping:

When I press this key, I need you to give up the default operation and do as I see it.

Let's start with the keyboard mapping of the normal mode. We'll discuss keyboard mapping in insert mode and other modes in the next section.

Feel free to tap a few lines of text, and then run the command:

:map - x

Place the cursor somewhere in the text and - . Note that Vim removes the characters under the current cursor as if you x x.

We already have a button to "remove characters under the current cursor", so - to a slightly more useful feature. To execute a command:

:map - dd

Now move the cursor to any line and press - deletes the entire line of text because dd is to delete the entire line.

Special characters

You can <keyname> special button by using the keyname. Try the following command:

:map <space> viw

Move the cursor to a word and press the space bar. Vim highlights the entire word.

You can also map the decoration typing Ctrl and Alt. Perform:

:map <c-d> dd

Now pressing Ctrl+d execute the dd command.

Comments

Remember the comments we discussed in chapter one? T he keyboard map cannot use comments. Try the following command:

:map <space> viw " Select word

Now that you press the space bar again, something terrible will happen. Think about why this is the case.

When you press the space bar, Vim thinks you're trying to execute the command viw<space>"<space>Select<space>word Obviously, that's not what you meant.

If you look closely at the results of this mapping, you may find something strange. Take a few minutes to figure out what's going on with this mapping and why.

For the time being, don't worry, we'll talk about it again soon.

Practice

Map button - "Delete the current row and paste it to the next line." Then you can move one line of text to the next at the touch of a button.

Add that mapping command to your ~/.vimrc and you can use that mapping every time you start Vim in the future.

Try how to map _ to move the current line up one line.

Add this map to your file ~/.vimrc

Think about what to do if you want to cancel a map or reset a key to the default feature.