I am looking for a
g8 equivalent that prints the hex values of the character under the cursor according to the file encoding of the file loaded in a buffer rather than assuming it's utf-8.
Is there such a thing?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.Sign up to join this community
There's nothing built-in, but the following mapping seems to do the trick.
" g9 Print the hex values of the bytes used in the " character under the cursor / selected text, using the " actual 'fileencoding' of the buffer. function! s:ShowHexFileEncodingCharacter( isSelection ) let l:text = (a:isSelection ? ingo#selection#Get() : ingo#text#GetChar(getpos('.')[1:2])) if empty(l:text) echomsg 'NUL' return endif let l:encoding = (empty(&l:fileencoding) ? &encoding : &l:fileencoding) let l:output = ingo#buffer#temp#Call(function('GetHexFileEncodingCharacters'), [l:encoding, l:text]) let l:hex = substitute(l:output, '0a\%(00\)*$\|\%(00\)\+0a$', '', '') " Remove the encoding of the trailing LF. echomsg substitute(l:hex, '..\zs', ' ', 'g') endfunction function! GetHexFileEncodingCharacters( fileencoding, text ) let [l:save_fileencoding, l:save_fileformat] = [&l:fileencoding, &l:fileformat] let [&l:fileencoding, &l:fileformat] = [a:fileencoding, 'unix'] " Always use Unix fileformat to make the removal of the newline easier. try silent call ingo#lines#PutWrapper(1, 'put', a:text) silent 1delete _ %!xxd -ps -c 999 finally let [&l:fileencoding, &l:fileformat] = [l:save_fileencoding, l:save_fileformat] endtry endfunction nnoremap <silent> g9 :<C-u>call <SID>ShowHexFileEncodingCharacter(0)<CR> xnoremap <silent> g9 :<C-u>call <SID>ShowHexFileEncodingCharacter(1)<CR>
It uses the
:! command to filter the character through the external
xxd command (which ships with Vim and performs a hex dump). This uses some functions of my ingo-library plugin.
For completeness, note that
ga uses the
encoding (not fileencoding) when it is a non-unicode encoding. You should be aware of the other consequences of setting
encoding to a value other than utf-8, though.
encoding setting is actually the internal encoding used in vim (almost always utf-8 these days - setting it to a different unicode encoding is interpreted as utf-8 as well) - it's used for buffer contents, variables, options, etc. Having it as something other than UTF-8 limits what characters you can have any of those places, and changing it while vim is running will change the meaning of any values (including buffer contents) that are already loaded with non-ASCII text. This also explains why
g8 normally always return unicode and UTF-8 values - because the buffer is in
encoding (= utf-8) regardless of what encoding the file was in.