Wrap a visual selection in an HTML tag
From Vim Tips Wiki
Tip 1495 Previous Tip • Next Tip
Created: January 29, 2007 Complexity: intermediate Author: Max Cantor Minimum version: 5.7 Karma: 12/6 Imported from: Tip#1495
There are a bunch of HTML wrapper tips and tricks out there, but I couldn't find any that suited my desire to be able to quickly wrap an arbitrary visual highlight in an arbitrary HTML tag.
I haven't tested the function below thoroughly, but it works in every visual mode, even if you're doing per-character visual mode and end your selection on a different line. I like to make all of my HTML tags uppercase, but if you don't bother, you can change the line:
let a:tag = toupper( input( "Tag to wrap block: ") )
to
let a:tag = input( "Tag to wrap block: ")
There may be a quicker way to input the arbitrary tag than with an input() call, but I kind of like this one.
Here's the function, and a mapping to go with it:
" Wraps visual selection in an HTML tag
vmap ,w <ESC>:call VisualHTMLTagWrap()<CR>
function! VisualHTMLTagWrap()
let a:tag = toupper( input( "Tag to wrap block: ") )
let a:jumpright = 2 + len( a:tag )
normal `<
let a:init_line = line( "." )
exe "normal i<".a:tag.">"
normal `>
let a:end_line = line( "." )
" Don't jump if we're on a new line
if( a:init_line == a:end_line )
" Jump right to compensate for the characters we've added
exe "normal ".a:jumpright."l"
endif
exe "normal a</".a:tag.">"
endfunction
[edit] Comments
Why don't you do it the opposite way:
normal `> exe "normal a</".a:tag.">" normal `< exe "normal i<".a:tag.">"
Here, you don't have to care about shifting your selected area.
[edit] Tags case
Since XHTML defines all tags and attributes to be in lowercase, I'd suggest to follow this convention in HTML as well.
