Wednesday, May 23, 2007

Hello World in VIM

OK, I feel myself empowered enough to actually write a "Hello World!" in VIM.

function Hello(wrld)
let hw = "Hello ".a:wrld."!"
echo hw

call Hello("World")

Save that to hw.vim and run this:

$ vim -u hw.vim -c ":q"

It should print "Hello World!" and wait for you to press Enter before quiting. (-u hw.vim tells vim to load hw.vim as substitute of ~/.vimrc and -c ":q" tells vim after loading ~/.vimrc (which is substituted with hw.vim) to execute ":q" to terminate.)

Dissection. :function & :endfunction are start and end of function definition. :let creates new variable hw which contains string "Hello " concatenated with a:wrld (function argument) and "!". (:help :let describes operator '.' which is string concatenation operator.) :echo is used to print the value contained in variable hw to screen. If we pass as parameter "World" to the function, hw would contain "Hello World!" string.

N.B. Colon ':' before command names, when is inside of script file - e.g. ~/.vimrc - is optional and used by me here merely to highlight that commands are all from normal mode. Also when you say to VIM :help :let, colon before let would tell vim that you are interested precisely in let command of normal mode - not something else. (Just like in :help 'ts', where single quotes tells vim to look for ts only amongst settable options.)

P.S. Adding that function to you ~/.vimrc with call Hello($LOGNAME) would greet you with silly "Hello <Your-Login-Name-Here>!" message every time you would launch vim.

No comments: