Skip to content

Instantly share code, notes, and snippets.

@pasela
Created December 17, 2011 19:30
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pasela/1491146 to your computer and use it in GitHub Desktop.
Save pasela/1491146 to your computer and use it in GitHub Desktop.
Escape/Unescape unicode string.
" unicodeescape.vim - Escape/Unescape unicode string.
function! UnicodeEscapeString(str)
let oldenc = &encoding
set encoding=utf-8
let escaped = substitute(a:str, '[^[:alnum:][:blank:][:cntrl:][:graph:]]', '\=printf("\\u%04x", char2nr(submatch(0)))', 'g')
let &encoding = oldenc
return escaped
endfunction
function! UnicodeEscape() range
let oldreg = @x
execute 'normal gv"xy'
let @x = UnicodeEscapeString(@x)
execute 'normal gv"xp'
let @x = oldreg
endfunction
function! UnicodeUnescapeString(str)
let oldenc = &encoding
set encoding=utf-8
let escaped = substitute(a:str, '\\u\([0-9a-fA-F]\{4\}\)', '\=nr2char("0x" . submatch(1))', 'g')
let &encoding = oldenc
return escaped
endfunction
function! UnicodeUnescape() range
let oldreg = @x
execute 'normal gv"xy'
let @x = UnicodeUnescapeString(@x)
execute 'normal gv"xp'
let @x = oldreg
endfunction
command! -range UnicodeEscape :<line1>,<line2>call UnicodeEscape()
command! -range UnicodeUnescape :<line1>,<line2>call UnicodeUnescape()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment