Simple string function in VIM
Recently I have posted a script for automatically picking up a ctags' tags file, if one found in obvious locations.
New thing for me in the script is definition and calling of a user function. User functions in VIM are documented under :help user-functions
topic. (Standard functions are documented under :help functions
. Pressing ^] on function name would bring you to detailed description of corresponding function.)
So, from POV of vimrc, function definition is simply set of commands, open with 'function Name([params])' line and closed with 'endfunction' line. Name must start with capital letter. Parameters are given as comma separated list - types are automagically deduced by VIM itself. Normally, most parameters would be strings and numbers - and VIM apparently can convert them silently one into another w/o bothering user about that (a-la Perl or JavaScript).
Inside of function one puts normal VIM commands (:help :normal
). To access parameters, their names must be prefixed with 'a:' (:help internal-variables
has nice list of all prefixes.)
To generate a value, function must use inside a return
command (:help :return
). Function will stop and callee would receive value given to return.
Function found in .vimrc become global and available everywhere. Additionally one can put function definitions in external file and then call :source
to make them available (:help :source
).
To call a function, one can use :call
command:
:call FindCtagsHere('/home/ifilipau/trunk/src/','/')
or simple :echo
(which also prints function return value)::echo FindCtagsHere('/home/ifilipau/trunk/src/','/')
or to save the value in variable one can use :let
::let x=FindCtagsHere('/home/ifilipau/trunk/src/','/')
because (compared to simpler :set
used for options, :let
(used for generic variable manipulation) evaluates right side of assignment operator).
3 comments:
OK, so suppose that I have a (terribly complicated) shell command:
/bin/echo "Hello world!"
or:
/bin/hostname
How would I use a vim function to insert the output of these commands at the current cursor position?
Regards, Homme.
"How would I use a vim function to insert the output of these commands at the current cursor position?"
I have put together something here.
type r: !/bin/echo "Hello world!"
Post a Comment