Wikia

Vim Tips Wiki

Wrap a visual selection in an HTML tag

Talk0
1,610pages on
this wiki
Revision as of 06:27, July 13, 2012 by JohnBot (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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).

CommentsEdit

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?

Around Wikia's network

Random Wiki