The right way to wrap block of lines in custom text in vim

vim

I would like to be able to select several lines using vim when editing an HTML file, then enter some hotkey and get these lines wrapped in a django comment block.

For example, I have:

one line
another line

I want to get:

{% comment %}
one line
another line
{% endcomment %}

Best Answer

I have the following mapping set up to quickly disable a block of C++ code using #if 0...#endif

:vmap 0 V'<O#if 0<Esc>'>o#endif<Esc>

What this does is set up a mapping that only works while Visual mode is enabled (vmap), which disables visual mode (V), goes to the beginning of the last visual selection ('<), enters a new line above it (O), enters the "#if 0" text then quits edit mode (<Esc>), then goes to the end of the last visual selection ('>), adds a line below (o) and enters the "#endif" text.

You could do something similar by replacing the start and end text, e.g.

:vmap 0 V'<O{% comment %}<Esc>'>o{% endcomment }<Esc>

Note that this requires the use of line-by-line visual mode, entered with a capital V, rather than character-by-character visual mode that uses a lowercase v.

Related Question