Learning Vim script: How to execute scripts

A Vim script file consists of a series of colon commands, also known as Ex commands or command-line commands. Even language constructs like loops, functions, etc are also colon commands; more on that later. Use the source command to execute a script file.

:source script.vim

It is not compulsory to use .vim as the extension for Vim script files, but it is the custom and is recommended. The source command executes each statement in the script. If there are any echo statements in the script their output will be printed in the command line.

The :source command can be shortened to :so. Typically you will be executing files that you are currently editing. So the filename can be shortened to the % symbol. 

:so %

You could create a mapping in your vimrc to save and execute the script.

:au FileType vim nnoremap <buffer> <F12> :w <bar> source %<CR>

Calling Functions

Once the script file is sourced, the global functions defined in it will become accessible from the command line. 

:call DisplayStats()

This is useful when you need to call the function with some other buffer active. You could create command-line abbreviations for the function calls to make this easier.

:cabbrev cds call DisplayStats()

If you want to learn more about abbreviations, please click here.

For functions that you need to test often, maps may be the better option.

If the function needs to be tested with different arguments,  user-defined commands might be preferable to abbreviations or maps.

:command -nargs=1 LK call ListKeyword(<args>)

Using the command line

As mentioned earlier Vim script consists entirely of colon commands which work in the command line as well. Command-line commands do not have to be single-line commands. For example, you can define a function directly in the command line. This might seem somewhat useless, but it allows you to do a useful thing. You can copy a sequence of colon commands to a Vim register and execute the contents of the register. For example, you can copy Vim script commands from a website to the system clipboard and execute them like so:

:@+

If you have copied the commands from inside Vim, they will be in the unnamed register, so execute them like so:

:@"

Leave a Comment

Your email address will not be published.