Vim encodes text to html and hex (for javascript)

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

original text

รกh hรญhรญ

in html:

& aacute; hh & iacute; h & iacute;

in hex:

\ xE1h h \ xEDh \ xED

+3


source to share


3 answers


For HTML coding, it depends on how thorough you want to be. One way to do this is by using the Perl module HTML::Entities

. This is thorough and quick, but quite 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 first two maps encode HTML entities, the latter decode them. They apply to the entire file or to a range of selected lines.

+4


source


here is one way to hide these non-ascii characters with a HEX value:

%s/[^\x00-\x7f]/\=printf('\x%x',char2nr(submatch(0)))/g

      



with your string as an example, the command changes it to:

\xe1h h\xedh\xed

      

+1


source


It's too long to post here - essentially an endless series of replacements - and could possibly be smarter, but my first vimscript feature is good at what it does: replace normal characters with appropriate HTML objects.

Scroll down for another function that does the opposite.

+1


source







All Articles