Technology
 

Text template with placeholders

From Vim Tips Wiki

Tip 322 Previous Next created August 29, 2002 · complexity basic · author lars_e_krueger · version 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 ;;

<pre>
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).

[edit] Comments

Mu-Template proposes a support for placeholders when inserting template files: script#222

Moreover, regarding C or C++, I propose several files that define abbreviations that support placeholders: script#336

It is based on a collection of scripts of mine: script#50


This is an easy and excellent idea! I start now to use it everywhere in my expansions because the jumping is quick and smooth and accurate.

I have

imap ;; <Esc>/%%%<CR>3xi
map ;; /%%%<CR>3xi

because it inserted an unwanted space (at least in my environment).