Skip to content

Instantly share code, notes, and snippets.

@dahu
Created June 22, 2015 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dahu/5f87d130ca8986ea95d6 to your computer and use it in GitHub Desktop.
Save dahu/5f87d130ca8986ea95d6 to your computer and use it in GitHub Desktop.
The naive beginnings of a toy hex editor in Vim
" Barry Arthur, June 2015
" The start of a Hex editor in Vim
function! HexInit()
let lines = getline(1, '$')
let s:idx = []
let s:hex = []
let s:asc = []
for l in lines
call add(s:idx, strpart(l, 0, 8))
call add(s:hex, strpart(l, 10, 39))
call add(s:asc, strpart(l, 51))
endfor
tabnew
call append(0, s:asc)
norm! Gdd
vsplit | enew
file Hex
call append(0, s:hex)
norm! Gdd
augroup Hex
au!
au InsertLeave,CursorHold * call HexUpdate()
augroup END
vsplit | enew
call append(0, s:idx)
norm! Gdd
2 wincmd w
1
endfunction
function! HexUpdate()
if bufname('%') != 'Hex'
return
endif
let ln = line('.')
let hex = split(substitute(getline('.'), ' ', '', 'g'), '\zs')
3 wincmd w
exe ln
norm! 0D
let asc = ''
for hh in map(range(0, len(hex)-2, 2), 'hex[v:val] . hex[v:val+1]')
let n = str2nr(hh, 16)
let n = n < 32 ? char2nr('.') : n
let asc .= printf("%c", n)
endfor
call setline(ln, asc)
wincmd p
endfunction
function! HexSearch(pat)
let pat = substitute(a:pat, '\zs', '\\_s*', 'g')
return '/' . pat . '/'
endfunction
command! -nargs=1 HexSearch exe HexSearch(<q-args>)
" WARNING: THIS WILL EAT YOUR CAT!
" Use vanilla xxd to generate initial hex dump (no fancy options)
" Use xxd -r -ps Hex to reverse the hex back into binary/ascii/etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment