learnvimscriptthehardway / chapters / 30.markdown

Full commit

Execute Normal!

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

: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:

: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 string 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.


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.