Search code examples
vimencoding

vim encode text to html and hex (for javascript)


Is there any easy way to encode accents and special characters to html or hex ones? With Vim.

original text

áh híhí

to html:

&aacute ;h h&iacute ;h&iacute ;

to hex:

\xE1h h\xEDh\xED


Solution

  • For HTML encoding it depends on how thorough you want to be. One way to do it is to use the Perl module HTML::Entities. It's thorough and fast, but rather heavy:

    nnoremap <silent> <Leader>h :silent %!perl -CIO -MHTML::Entities -pe '$_=encode_entities $_'<CR>
    vnoremap <silent> <Leader>h :<C-u>silent '<,'>!perl -CIO -MHTML::Entities -pe '$_=encode_entities $_'<CR>
    nnoremap <silent> <Leader>H :silent %!perl -CI  -MHTML::Entities -pe '$_=decode_entities $_'<CR>
    vnoremap <silent> <Leader>H :<C-u>silent '<,'>!perl -CI  -MHTML::Entities -pe '$_=decode_entities $_'<CR>
    

    The former two maps encode HTML entities, the latter ones decode them. They apply to either the entire file, or to a range of marked lines.