Write and map vim macros/functions (howto and example)


vim allows the definition of functions or macros and specification of key sequences (can be just one key) to trigger them (mapping). This article provide a simple example that shows how to write a vim function and how to to map it.


Sample macro and its mapping

This script when added in ~/.vimrc will map the key F7 to the function CompileRunPDF() which compiles a latex file and produces a PDF then preview it using xpdf.

" map the key F7 to the function CompileRunPDF defined below
 map <F7> : call CompileRunPDF()<CR>

" Here we define the function
 func! CompileRunPDF()

" save the current file
 exec "w"

" call latex on the current file then run dvips on the file
" generated by latex. The %< variable corresponds to the
" current file name stripped of its extension.
 exec "!latex % && dvipdf %<.dvi && xpdf %<.pdf"

" back to insert mode when the xpdf program exits
 exec "i"

 endfunc


Labels: , Wireless Internet Security Coding Network Monitoring