Vim Tips Wiki
Advertisement
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
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.">"
    else
      exe "normal a</".tag.">"
    endif
    normal `<
    exe "normal i<".tag.">"
    normal `<
  endif
endfunction

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

Comments

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?

Advertisement