The solution would depend on your terminal and how it's set up. Unix terminals generally send a meta character or sequence when you hold Alt and press another key. There are two traditional ways of sending meta characters to terminal programs:
Take the ASCII value of the other key pressed (i.e. the one that's not Alt) and OR
it with 128 (setting bit 7 high). This is discouraged these days because the resulting 8-bit character code isn't compatible with UTF-8 or even 8-bit encodings like Latin-1.
Send an escape character, ASCII 27, and then the ASCII code for the other key. This works well with a variety of encodings, but it can complicate the handling of cases where you actually meant to send an explicit escape character, e.g. when you hit Esc in Vim.
If your terminal is set to use #2, you might be tempted to do noremap <Esc><CR> viw
. However, this will make Vim pause any time it receives an escape. To avoid this, you can set
an <A-CR>
key code and use that in the map
; this makes it so that Vim can treat the sequence as different from an escape+character sequence (in particular, the sequence can have a timeout that's much shorter than the one used by other mappings; since terminals send the escape character and the following character almost simultaneously, this can guard against accidentally triggering a key code when you're not trying to).
The set
command itself interprets strings like <Esc>
literally (i.e. doesn't convert that into ASCII 27), so you have to wrap it in an exec
:
exec "set <A-CR>=\<Esc>\<CR>"
After that, you can finally do a mapping:
noremap <A-CR> viw
You probably also want to set a very short ttimeoutlen
so you don't accidentally trigger this new mapping with EscReturn, e.g.
:set timeout timeoutlen=3000 ttimeoutlen=100
would make "normal" mappings wait a full 3 seconds between keys but key code mappings only a tenth of a second.
References:
:h :set-termcap
:h :map-alt-keys
:h 'ttimeout'