= Vimscript Functions = <> ---- == Example == Source a file like: {{{ function HelloWorld() echom "Hello, World!" endfunction }}} Or run the following in an interactive `vim(1)` session: {{{ :function HelloWorld() : echom "Hello, World!" :endfunction }}} ---- == Definition == A function is defined with the `:function` command. Function names ''must'' begin with an uppercase letter. If a function is defined within a scope, it may begin with a lwoercase letter. Best practice is to always use an uppercase letter anyway. === Arguments === A function that takes no arguments can be defined like: {{{ :function Foo() : echom "Foo" :endfunction }}} A function that takes an argument can be defined like: {{{ :function Bar(bar) : echom a:bar :endfunction }}} Note the `a:` scope on references to the argument. The argument is otherwise referenced by name. Note also that the `a:` scope is immutable. A function that takes any number of arguments can be defined like: {{{ :function Baz(...) : echom a:0 : echom a:1 :endfunction }}} The elipses (`...`) capture zero or more arguments. Note that the captured arguments are referenced by index like `a:0`. These argument specifications can be mixed. A function that takes two or more arguments could be defined with `:function Ham(spam, eggs, ...)`. === Return Values === If a function does not return explicitly, it returns 0. This can lead to tricky logic bugs, especially when functions are used in boolean checks. {{{ :if TextwidthIsTooWide() : echom "WARNING: Wide text!" :endif }}} On the other hand, it can also make writing functions with a boolean return value simpler. Only the true cases have to be checked and returned explicitly; the false cases will pass through and implicitly return 0. {{{ :function TextwidthIsTooWide() : if &l:textwidth ># 80 : return 1 : endif :endfunction }}} ---- == Usage == A function can be called explicitly, like: {{{ :call Function() }}} In this case, the return value is thrown away. To call a function and immediately print the return value (as though it were a constructed message), try: {{{ :function HelloWorld() : return "Hello, World!" :endfunction :echom HelloWorld() }}} ---- CategoryRicottone