1

I currently have <Enter> mapped to :nohlsearch in normal mode. This allows me to leave search highlighting on for all new searches, but easily turn it off when it (soon after usually) becomes a distraction.

This works great usually, the exception is when I'm using q: to edit the command history to produce a closely related ex command or whatever. The behavior of Enter in that context is to execute the command (or search in search history edit), but the normal-mode remapping overrides that. Consequently, I need to hit enter from insert mode to execute the command.

How can I map Enter to :nohlsearch in normal mode but retain the "execute" behavior of Enter in the command-history edit window?

1 Answer 1

4

I have the following in my vimrc to force regular behavior of enter in certain situations:

augroup vimrc_CRfix
  au!

  " Quickfix, Location list, &c. remap <CR> to work as expected
  autocmd BufReadPost quickfix nnoremap <buffer> <CR> <CR>
  autocmd CmdwinEnter * nnoremap <buffer> <CR> <CR>

augroup END

I cannot remember why I’m using nnoremap and not unmap <buffer>; it’s possible the latter works.

3
  • Super-awesome, this works! :)
    – scanny
    Nov 1, 2018 at 17:52
  • 2
    Since you are using a buffer local mapping (i.e. <buffer>) it takes precedence over the global <cr> mapping so you do not need to unmap. Another thought: nnoremap <buffer> <expr> <cr> v:hlsearch ? ":nohlsearch\<cr>" : "\<cr>" which will disable the search if the search is active & if there is no search give you the normal <cr> behavior. See :h :map-local, :h :map-<expr>, and :h v:hlsearch for more Nov 1, 2018 at 19:10
  • @PeterRincker i think the second half could be an additional answer; mine is more general because of the way mapping i use for <CR>
    – D. Ben Knoble
    Nov 1, 2018 at 19:21

Your Answer

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

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