1

Is it possible to map <esc> to close the cmd window and go to normal mode? Currently pressing <C-c> closes the cmd window but takes you into Cmdline mode. So you have to press either <C-c> again or <esc> to go to normal mode.

0

1 Answer 1

2

Is it possible to map <esc>

Remapping Esc is strongly discouraged, as it may interfere with normal keycode processing in terminal version of Vim (see, for example, here).

But, of course, you can remap something else for that particular <buffer> only, so your mapping can't do bad things to other windows (BTW. this technique is also suggested under :h cmdwin):

autocmd CmdwinEnter * nnoremap <silent><buffer>ZQ <C-C><Esc>

In fact, this is a very common pattern in Vim to fine-tune mappings for specific windows, and as such it's useful to add it to your toolbox. A pair of examples taken from my vimrc to illustrate this capability:

augroup vimrc | au!
    ...
    " 'q' to close a non-modifiable window/buffer (e.g. 'help')
    autocmd BufWinEnter * if !&modifiable | nnoremap <buffer>q ZQ | endif
    " <F5> to execute script
    autocmd FileType vim nnoremap <buffer><silent><F5> :update \| source %<CR>
    autocmd FileType sh nnoremap <buffer><silent><F5> :update \|
        \ execute 'terminal' &shell expand('%:S')<CR>
    ...
augroup end
10
  • 1
    Great inspiration in that snippet. If found that mapping to <C-c><C-c> worked better as <C-c><esc> was execting the command. Also mapping <esc> in this situation worked like a charm. noremap : q:i autocmd CmdwinEnter * nnoremap <buffer><esc> <C-c><C-c>
    – nunmap
    Aug 4, 2019 at 7:11
  • 1
    Some of your filetype commands may be better off in .vim/after/ftplugin (leveraging existing machinery, as it were)
    – D. Ben Knoble
    Aug 4, 2019 at 13:39
  • "You should never map Esc." Why not? Do you have a citation for that? Looks like the OP was pretty happy with a solution remapping Esc from there, and I don't really see any problems with it... I also fail to see how the last part on mapping "q" and F5 is in any way relevant to the question. So while your answer does somewhat answer the question, it could be improved by making it shorter and actually using the suggested/requested keybinding...
    – filbranden
    Aug 4, 2019 at 14:09
  • @D.BenKnoble Well, I really don't see what is the benefit of after/ftplugin here. Care to give an example?
    – Matt
    Aug 4, 2019 at 15:28
  • 1
    @filbranden mapping esc tends to... break things. Arrow keys and other special key sequences that are actually escape followed by codes.
    – D. Ben Knoble
    Aug 4, 2019 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.