You can create your own function to run on any file open with Vim editor. And it is simple to automate your mundane stuff on Vim editor.
Here is the step-by-step procedure for adding and calling a new function for Vim editor. I will also explain Vim function example and use cases.
Are you ready for writing your first Vim function? I am sure, you have a Linux system with Vim editor installed.
Step 1: Open vimrc File
vim ~/.vimrc
Note: It is not necessary you will be having this file. if it is not there, just create it.
Step 2: Write a New Function in the vimrc file
To make it simple I am writing a function that prints some message (says – First Vim function.)
function! FirstFunction() echom "First Vim function!" endfunction
Don’t confuse with the word echom
. For now, you can consider it as equivalent as bash command echo
. Other syntaxes of the function are self-explanatory.
Save the file. (Command to the file- wq!
)
Step 3: Calling / Executing Vim Function:
You don’t need to compile the function. You can call this function from Vim editor with any of the file.
Open any of the text files in Vim editor.
Vim Command to execute the Vim function from the command line:
:call FirstFunction()
So, it will print the following message.
First Vim function!
Here we are using the return command which returns the message to the calling function.
function! Play() return "Playing with Linux!" endfunction
Run following command:
:echom Play()
It prints the message as below.
Playing with Linux!
Now, let’s check…
;
(semicolon) at the end of each statement, unlike most of the programming languages.+=
or ++
operators?The +=
operator is included in the latest vim version. So it is available in Vim since version 7.0.
The operator ++
does not support yet in Vim function.
For example:
firstFunction- is invalid function name. FirstFunction- is valid function name.
What’s the next?
There are also many built-in functions you can use with the Vim.
You can explore the various rules and commands for writing Vim function. These rules and commands are well documented in the Linux/Ubuntu.
In Vim editor, run following command to get the help from the document.
:help :call
Explore the return functionality.
:help return
Also, Explore the Vim Hardway to Excel in Programming:
Let me know your view about this simple tutorial about Vim function example. If you have any point to discuss, write in the comment section.