" Binary editing helper function to toggle hex mode function ToggleHex() " hex mode should be considered a read-only operation " save values for modified and read-only for restoration later, " and clear the read-only flag for now let l:modified=&modified let l:oldreadonly=&readonly let &readonly=0 let l:oldmodifiable=&modifiable let &modifiable=1 if !exists("b:editHex") || !b:editHex " save old options let b:oldft=&filetype let b:oldbin=&binary " set new options setlocal binary " make sure it overrides any textwidth, etc. let &filetype="xxd" " set status let b:editHex=1 " switch to hex editor %!xxd -g 1 else " restore old options let &filetype=b:oldft if !b:oldbin setlocal nobinary endif " set status let b:editHex=0 " return to normal editing %!xxd -r endif " restore values for modified and read only state let &modified=l:modified let &readonly=l:oldreadonly let &modifiable=l:oldmodifiable endfunction command -bar Hexmode call ToggleHex() " " vim -b : edit binary using xxd-format! if &binary augroup Binary autocmd! " if on a fresh read the buffer variable is already set, it's wrong autocmd BufReadPost * \ if exists('b:editHex') && b:editHex | \ let b:editHex = 0 | \ endif " convert to hex on startup for binary files automatically autocmd BufReadPost * Hexmode " When the text is freed, the next time the buffer is made active it will " re-read the text and thus not match the correct mode, we will need to " convert it again if the buffer is again loaded. autocmd BufUnload * \ if getbufvar(expand(""), 'editHex') == 1 | \ call setbufvar(expand(""), 'editHex', 0) | \ endif " before writing a file when editing in hex mode, convert back to non-hex autocmd BufWritePre * \ if exists("b:editHex") && b:editHex && &binary | \ let oldro=&ro | let &ro=0 | \ let oldma=&ma | let &ma=1 | \ silent exe "%!xxd -r" | \ let &ma=oldma | let &ro=oldro | \ unlet oldma | unlet oldro | \ endif " after writing a binary file, if we're in hex mode, restore hex mode autocmd BufWritePost * \ if exists("b:editHex") && b:editHex && &binary | \ let oldro=&ro | let &ro=0 | \ let oldma=&ma | let &ma=1 | \ silent exe "%!xxd -g 1" | \ exe "set nomod" | \ let &ma=oldma | let &ro=oldro | \ unlet oldma | unlet oldro | \ endif augroup END endif