sponsor Vim development Vim logo Vim Book Ad

basic Tip #322: text template with placeholders

 tip karma   Rating 22/13, Viewed by 2167 

created:   August 29, 2002 4:34      complexity:   basic
author:   lars_e_krueger      as of Vim:   6.0

Many scripts/ftplugin provide text or code templates. Sadly none of the marks the places where you are supposed to "fill in the form".
My own code templates for C/C++ insert a triple percent (%%%) where you are supposed to enter something. I mapped ;; to find the next %%% and change them.
All the template mappings are insert-mode only, while the "skip to next placeholder" is both insert and normal mode enabled.

A complete for-loop template for C++ looks like:

:imap <buffer> ;fo <C-O>mzfor( %%%; %%%; %%%)<CR>{ // %%%<CR>%%%<CR>}<CR><C-O>'z;;

The command to go to the next placeholder is this:

:imap <buffer> ;; <C-O>/%%%<CR><C-O>c3l
:nmap <buffer> ;; /%%%<CR>c3l


Every time I need a for-loop ;fo produces this ( _ is the cursor position) :
for( _; %%% ; %%%)
{ // %%%
  %%%
}

Now I enter starting value (i=0):
for( i=0_; %%% ; %%%)
{ // %%%
  %%%
}

and go to the condition using ;;
for( i=0; _ ; %%%)
{ // %%%
  %%%
}

and so forth.

The choice of %%% proved to be almost universal, it even works in MATLAB or LaTeX where % is the comment character.

Even if you forget to replace one %%%, that's not a problem as the compiler flags is as a syntax error (except MATLAB and LaTeX, of course).

It made my life easier, maybe it works for you.

 rate this tip  Life Changing Helpful Unfulfilling 

<<Centura swap with upper/lower line behavier | using folders with latex >>

Additional Notes

hermitte at free.fr, August 29, 2002 8:31
Mu-Template proposes a support for placeholders when inserting template files :
    http://vim.sourceforge.net/script.php?script_id=222
Actually, it is based on Stephen Riehm's bracketing system.

Moreover, regarding C or C++, I propose several files that define abbreviations that support placeholders :
   http://vim.sourceforge.net/script.php?script_id=336
It is based on a collection of scripts of mine :
   http://vim.sourceforge.net/script.php?script_id=50
and also it is strongly inspired by Stephen Riehm's bracketing system.
On my web site, I provide similar script for LaTeX or HTML coding.

Unfortunately, the definition of the templates is quite complex as it is possible to change (through a pair of variables) the markers used (to signal the placeholders) -- the "jumping" (to the next marker) functions are also customisable thanks to variables.

Otherwise,I also remember several alternatives (that focused of the definition of the template) to the same problem. They are here on SF.
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
Sponsored by Web Concept Group Inc. SourceForge Logo