chapters/30.markdown @ efe4cc9cbd7e

Don't map things to keys that terminals might eat.

Thanks to Sven Hergenhahn for reporting this.
author Steve Losh <steve@stevelosh.com>
date Wed, 31 Oct 2012 18:28:40 -0400
parents a2fb13918fc6
children 0e78ce34b11d
Execute Normal!
===============

Now that we've seen `execute` and `normal!` we can talk about a common Vimscript
idiom.  Run the following command:

    :::vim
    :execute "normal! gg/foo\<cr>dd"

This will move to the top of the file, search for the first occurrence of "foo",
and delete the line that contains it.

Previously we tried to use `normal!` with a search command but couldn't enter
the return needed to actually perform the search.  Combining `normal!` with
`execute` fixes that problem.

`execute` lets you build commands programmatically, so you can use Vim's normal
string escape sequences to generate the non-printing characters you need.  Try
the following command:

    :::vim
    :execute "normal! mqA;\<esc>`q"

What does this do?  Let's break it apart:

* `:execute "normal! ..."`: run the sequence of commands as if they were entered
  in normal mode, ignoring all mappings, and replacing escape sequences with
  their results.
* `mq`: store the current location in mark "q".
* `A`: move to the end of the current line and enter insert mode after the last
  character.
* `;`: we're now in insert mode, so just put a literal semicolon in the file.
* `\<esc>`: this is a string escape sequence which resolves to a press of the
  escape key, which takes us out of insert mode.
* ```q``: return to the exact location of mark "q".

It looks a bit scary but it's actually quite useful: it puts a semicolon at the
end of the current line while leaving your cursor in place.  A mapping for this
could come in handy if you forget a semicolon when writing Javascript, C, or any
other language with semicolons as statement terminators.

Exercises
---------

Read `:help expr-quote` again (you've seen it before) to remind yourself how to
use string escapes to pass special characters to `normal!` with `execute`.

Put down this book for a while before you go on to the next chapter.  Get
a sandwich or a cup of coffee, feed your pets if you have them, and relax for
a bit before continuing.