The hex value of g:foo_key
will be 0x09 (a tab). You can use the
strtrans()
function to get a readable representation of this:
:echo strtrans("\<Tab>")
<09>
Note that this prints <09>
, and not <Tab>
. They are the same, and there is no way to know which one the user has entered. It may also show up as ^I
(depends on value of display
).
Getting the key name is not something I can figure out how to do with a simple
function call, but in the key_name_entry
struct in misc2.c
you can find a
list of keynames; making a function for this is easy:
let g:chars = {
\ '<09>': '<Tab>',
\ '<1b>': '<Esc>',
\ }
fun! StringTrans(char)
if get(g:chars, a:char, -1) != -1
return g:chars[a:char]
else
return strtrans(a:char)
endif
endfun
You probably want to expand g:chars
; note that you have to type the literal
hex value with <C-v><Tab>
, <C-v><Esc>
, etc.
Note that this still won't return exactly what the user has typed, since there are multiple names for some characters (for example <NL>
, <LF>
, <Newline>
, and <Linefeed>
are all the same).
Doing the reverse with eval()
is perhaps easier:
:let foo = '\<Tab>'
:echo foo
\<Tab>
:let foo_expanded = eval('"' . foo . '"')
:echo strtrans(foo_expanded)
<09>
string()
function. Combined witheval()
, it makes it easy to pass things around without bending over backwards to quote values. You can see it at work f.i. here.string()
as useful in general, not necessarily here.string()
: assignment:let foobar="foo\tbar"
, direct use::echo foobar
, passing it along::exec 'echo ' . string(foobar)
. Things can get hairy when writing complicated sort functions, or functions forfilter()
,map()
, and the like. But even then,string()
avoids a lot of complexity.