24

How can one use a variable when executing something via normal! in vimscript?

Example:

function! MyFunction(someArg)
   normal! (a:someArg)l
endfunction

This should move the cursor someArg steps to the right.

2

3 Answers 3

35

The execute function takes a string as argument, it expands the string and execute it a a regular ex command. Thus you can do:

function! MyFunction(someArg) 
    execute "normal! ". a:someArg. "l" 
endfunction

The . is a standard vimscript operator to concatenate strings.

execute can be shortened to exe.

See :h :execute


EDIT I'll add a point about the comment of @Christian Brabandt about the concatenation with a ..

The doc says:

Multiple arguments are concatenated, with a space in between. To avoid the extra space use the "." operator to concatenate strings into one argument.

So the command could be:

execute "normal!" a:someArg . "l"

The executed command will be:

normal! 2l
3
  • 11
    you don't need the '.'. exe will concatenate strings with a space without it. Sep 22, 2016 at 20:33
  • 2
    @ChristianBrabandt Wait seriously? I did not know that.
    – Tumbler41
    Sep 22, 2016 at 20:36
  • @ChristianBrabandt I didn't know that thanks!
    – statox
    Sep 23, 2016 at 7:42
4

For completeness's sake, I find the string concatenation using . is not pleasant to read. We may use printf to concatenate strings and variables for better readability.

execute printf("normal! %sl", a:someArg)
1
  • And if you expect a:someArg to be a count, you can even force that interpretation using %d in your printf format.
    – filbranden
    Sep 24, 2020 at 11:25
1

statox' answer is the best answer but I think the command looks cleaner that way:
(leave spaces between . and strings)

let i = 4
execute "normal! " . i . "l"
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.