Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM functions: when to use "normal", when to use "exec" and when to use nothing?

Tags:

In studying VIM functions to learn to write my own I see that commands are sometimes written preceded with the keyword normal:

normal mz

Sometimes with the normal wrapped in an exec:

exec "normal mk"

Or sometimes alone on the line;

0d

Where in the fine manual is this addressed?

like image 227
dotancohen Avatar asked Mar 15 '12 16:03

dotancohen


2 Answers

You're getting confused with the various modes. More specifically, the command mode and normal mode.

Command mode is where the ex commands are applied, the commands that begin with a colon. VimScript files are just a sequence of ex commands.

When you need to perform a normal mode command while in ex mode (command mode) you use the :normal ex command, which executes the arguments as they would be in normal mode.

When you execute command directly, well, you're executing it directly. In your example, the :d command was used with a range. That's not the same as the d key in normal mode, that's another entirely different command. Check the help for :d and d (the normal command).

The :execute is useful to build a command as a string and execute it as an ex command. In your example, it's useless. But it becomes handy in other cases, as an example when you have a variable holding a line number and wants to use its value in a command:

:let i=4
:exec "2," . i . "d"

Which is just the same as

:2,4d
like image 182
sidyll Avatar answered Sep 22 '22 15:09

sidyll


Well let's ask Vim's extensive built-in help system, which you can access by typing :h followed by the command or keyword you're interested in:

:h norm

:norm[al][!] {commands}

Execute Normal mode commands {commands}. This makes it possible to execute Normal mode commands typed on the command-line. ...

So in other words, normal mz in a script is equivalent to typing mz in normal mode.

:h exec

:exe[cute] {expr1} ..

Executes the string that results from the evaluation of {expr1} as an Ex command. ...

It's not clear to my why the author of the linked script uses exec "normal mk" instead of normal mk (mk in normal mode just sets a mark called "k"). The docs do offer this, though:

:execute is also a nice way to avoid having to type control characters in a Vim script for a :normal command:

:execute "normal ixxx\<Esc>"

This has an <Esc> character, see |expr-string|.

As for 0d, some Ex (command-line) commands can be given a range of line numbers to execute on. 0 is usually interpreted as 1, since Vim line numbering starts at 1, not 0, so :0d (and :1d) simply deletes the first line. :2,4d would delete the second, third, and fourth lines. See :h cmdline-ranges for more details.

like image 30
Jordan Running Avatar answered Sep 22 '22 15:09

Jordan Running