Vim Tips Wiki

Wrap a visual selection in an HTML tag

1,625pages on
this wiki
Add New Page
Talk0 Share
Tip 1495 Printable Monobook Previous Next

created 2007 · complexity intermediate · author Max Cantor · version 6.0

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. Here's the function, and a mapping to go with it:

" Wrap visual selection in an HTML tag.
vmap <Leader>w <Esc>:call VisualHTMLTagWrap()<CR>
function! VisualHTMLTagWrap()
  let tag = input("Tag to wrap block: ")
  if len(tag) > 0
    normal `>
    if &selection == 'exclusive'
      exe "normal i</".tag.">"
      exe "normal a</".tag.">"
    normal `<
    exe "normal i<".tag.">"
    normal `<

Put it in ~/.vim/scripts/wrapwithtag.vim and enable in ~/.vimrc:

au Filetype html,xml source ~/.vim/scripts/wrapwithtag.vim

When editing HTML file, visually highlight text and press {Leader} w, enter tag name (where {Leader} defaults to the '\' key, but you can override with a :let mapleader = command :help mapleader).


Another option is to use the xml.vim plugin. Save it as ~/.vim/ftplugins/html.vim. To wrap some text with tag, visually select the text, and press <LocalLeader>x (<LocalLeader> is backslash \ by default). To strip the surrounding tag, press <LocalLeader>d.

Why not use ftplugin directory instead of a Filetype autocmd?

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.