Skip to content

Instantly share code, notes, and snippets.

@kamichidu
Created July 22, 2014 10:37
Show Gist options
  • Select an option

  • Save kamichidu/4b37c7b928de0d57e400 to your computer and use it in GitHub Desktop.

Select an option

Save kamichidu/4b37c7b928de0d57e400 to your computer and use it in GitHub Desktop.
let s:native2ascii= {}
function! s:native2ascii.encode(s)
" `s' is &encoding
let chars= split(a:s, '\zs')
let length= len(chars)
let buf= []
let i= 0
while i < length
let c= iconv(chars[i], &encoding, 'utf8')
let cn= char2nr(c, 1)
let i+= 1
if cn > 0x003d && cn < 0x007f
if c ==# '\'
let buf+= ['\', '\']
continue
endif
let buf+= [c]
continue
endif
if c ==# ' '
if i == 0
let buf+= ['\']
endif
let buf+= [' ']
elseif c ==# "\t"
let buf+= ['\', 't']
elseif c ==# "\n"
let buf+= ['\', 'n']
elseif c ==# "\r"
let buf+= ['\', 'r']
elseif c ==# "\f"
let buf+= ['\', 'f']
elseif c ==# '=' || c ==# ':' || c ==# '#' || c ==# '!'
let buf+= ['\', c]
else
if cn < 0x0020 || cn > 0x007e
let buf+= ['\', 'u', printf('%04x', cn)]
else
let buf+= [c]
endif
endif
endwhile
return iconv(join(buf, ''), 'utf8', &encoding)
endfunction
function! s:native2ascii.decode(s)
let chars= split(a:s, '\zs')
let length= len(chars)
let buf= []
let i= 0
while i < length
let c= chars[i]
let i+= 1
if c ==# '\'
let c= chars[i]
let i+= 1
if c ==# 'u'
" read the xxxx
let buf+= [nr2char(printf('%d', '0x' . join(chars[i : i + 3], '')), 1)]
let i+= 4
else
if c ==# 't'
let c= "\t"
elseif c ==# 'r'
let c= "\r"
elseif c ==# 'n'
let c= "\n"
elseif c ==# 'f'
let c= "\f"
endif
let buf+= [c]
endif
else
let buf+= [c]
endif
endwhile
return iconv(join(buf, ''), 'utf8', &encoding)
endfunction
echo '計画表 = \u8a08\u753b\u8868'
echo s:native2ascii.decode('\u8a08\u753b\u8868')
echo s:native2ascii.encode('計画表')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment