meisterluk’s advent calendar: Vim for programmers

In vim you have all tools to generate real programs. Vim’s imperative scripting language is called vimscript. I would like to show you some basic. Use :help usr_41 to get more information. The following content can be saved as “script.vim” and can be used by typing :source script.vim in an other vim session (of course, you shall not change the working directory). There is no need for the inital colon before ex commands (because nearly everything is executed by ex) and double-quotes introduce a comment (as I mentioned before). Basically this is my workout of the first sections of usr_41.txt

" simple vimscript
" the syntax is similar to ruby

" define a simple variable
let i = 47

" overwriting var
let i = 47
while i >= 43
    let i -= 1
endwhile
echo i "is the answer"

" a 'for' loop
for i in range(1, 4)
    echo i "... "
endfor

" numbers
" negative octal, positive hexadecimal, positive octal
echo -024 0x14 024

" valid variable names match [a-zA-Z_][a-zA-Z0-9_]*
let _VIMRC = "~/.vimrc"

" variable scopes
" s:    local
" b:    local to a buffer
" w:    local to a window
" g:    global
" v:    variable predefined by Vim

" for example this variable is defined local
let s:vim = "rocks"
unlet s:vim " delete var

" unlet with exclamation mark
" if (exists(var)) delete it; else ignore.
unlet! _VIMRC 

" exists() checks existence of variable.
if !exists("s:count_calls")
    let s:count_calls = 0
endif
let s:count_calls = s:count_calls + 1
echo "called" s:count_calls "times"

" auto-converts string to a number
" Strings and Numbers are the two basic data types.
if "true"
    " will not be executed
    echo "string 'true' is true"
endif

Another thing I would like to talk about is the modeline. Every programmer has its own vim settings. Modifying a file of another programmer possibly destroys the whole program format like whitespaces in HTML or think about the tab-or-spaces-discussion of python. In this case it would be wise to add a comment in the file, which tells you the most important vim settings of the author. And Vim automatically reads this line and executes the set commands:

vim: autoindent nosmartindent expandtab shiftwidth=4

Enable modeline (:set modeline) to auto-read such lines, you might find at the bottom or top of a source file. Vim will search for it, if modeline is enabled. The settings can also be colon-separated (for compatibility reasons). You will get more information about that feature with :help modeline. For example if you want to make settings dependent on your Vim version, use the documentation in this case.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>