Ready-to-paste HTML-escaped Code in Vim

I’ve seen countless of websites that paste code and do not escape the <, > and & characters, resulting in broken HTML and missing code. I have been using online HTML entity encoders when pasting code, but today I decided to code a little Vimscript for my Vim.

Escape HTML Entities in VIM

This may not work for everyone. My Vim is 7.3, compiled from sources, with --with-features=big --enable-pythoninterp --with-python-config-dir=/usr/lib/python2.6/config/ configuration flags.

" HTML Entities
vmap <silent> ,hx :<C-U>call HTMLentities()<CR>
function! HTMLentities()
    
    " yank last selection into register a
    silent execute "'<,'> y a"
    " add buffer and display in vertical split
    silent execute "badd ____a"
    silent execute "vsplit ____a"
    " set buffer type to temporary
    silent execute "set buftype=nofile"
    " insert contents of register a
    silent execute "put a"
    " replace <, > and & entities
    silent execute '%s/\([><&]\)/\=submatch(1)==">"?"&gt;":submatch(1)=="<"?"&lt;":submatch(1)=="&"?"&amp;":""/ge'
    " cleanup
    silent execute "0d"
    " copy to OS clipboard
    silent execute "%y+"
    " close window
    silent execute "q"
    silent execute "bdelete ____a"
    " paste anywhere you like
    echo "Copied to clipboard!"

endfunction

Select some text in visual mode, hit ,hx and you should be able to paste escaped code without fear of breaking any HTML. The most complicated part is this:

%s/\([><&]\)/\=submatch(1)==">"?"&gt;":submatch(1)=="<"?"&lt;":submatch(1)=="&"?"&amp;":""/ge

It’s a replace pattern. It uses the \= execute modifier and compares the submatch with ternary operators. Expanded into pseudo-code, this looks like this:

[in all range] substitute ([><&]) with...
  if match[1] == "<"
    ...with "&lt;
  elif match[2] == ">"
    ...with "&gt;"
  elif match[3] == "&"
    ...with "&amp;
[kthnxbye]

Let me know how it works for you, what other features one can add to make it look better; for example, re-indentation. Does you favorite text editor do this?