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.
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)==">"?">":submatch(1)=="<"?"<":submatch(1)=="&"?"&":""/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)==">"?">":submatch(1)=="<"?"<":submatch(1)=="&"?"&":""/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 "< elif match[2] == ">" ...with ">" elif match[3] == "&" ...with "& [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?